我正在尝试从WebView类访问setName方法,但是当我在调用callSetNameFunction中出现错误时出现错误。我创建了新的webview对象并将其存储在webfragment类的对象中,但是无法访问webview类中的方法。我怎样才能做到这一点。我还没有做过很长时间的java,还在学习。
WebView类
public class WebView {
private String name;
public WebView (String name) {
this.name = name;
}
public WebView () {
this.name = name;
}
public void setName(String name) {
if(name != null) {
this.setName(name);
} else {
System.out.println("Thats not his name");
}
}
public String getName() {
return name;
}
}
WebFragment类
public class WebFragment {
Object myObject;
public WebFragment() {
myObject = new WebView();
}
public Object getWebView() {
return myObject;
}
public void callSetNameFunction() {
myObject.setName();
}
}
答案 0 :(得分:2)
3次更正
Object myObject
必须为WebView myObject;
如果要使用WebView
对象中的方法,如果要使用myObject
类,则必须将WebFragment
类的WebView
属性声明为getter
类型它声明的方法。
注意:您还必须将public WebView getWebView() {
签名更改为myObject.setName();
myObject.setName("name");
应该收到一个参数,例如:public WebView () {
this.name = name; // Warning: The assignment to variable name has no effect
}
不带参数的构造函数在设置变量时不起作用:
public WebView () {
}
必须是:
#include <memory>
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
//base class
class Car
{ public:
Car(int speed): speed(speed) {};
Car(const Car& c): speed(c.speed)
{ cout <<"Copy Constructor Car" <<endl;
}
virtual void display()
{ cout <<" speed: " <<speed <<endl;
}
virtual Car* clone()const =0; // virtual copy constructor
private:
int speed;
};
typedef std::shared_ptr<Car> CarP;
class Garage
{ private:
vector<CarP> cars;
public:
Garage() {}
//copy constructor of the garage
Garage(const Garage &toCopy)
{ cout <<"Copy Constructor Garage" <<endl;
for (CarP c : toCopy.cars)
{ CarP cp(c->clone());
ReceiveCar(cp);
}
}
void ReceiveCar(CarP toCopy)
{ cars.push_back(toCopy);
}
void display()
{ for (CarP c : cars) c->display();
}
};
class Saab: public Car
{ public:
Saab(int speed): Car(speed)
{ cout <<"Constructor Saab" <<endl;
}
void display()
{ cout <<"Car: Saab"; Car::display();
}
Saab* clone()const
{ return new Saab(*this);
}
};
class AstonMartin: public Car
{ public:
AstonMartin(int speed): Car(speed)
{ cout <<"Constructor AstonMartin" <<endl;
}
AstonMartin(const AstonMartin& toCopy): Car(toCopy)
{ cout <<"Copy Constructor AstonMartin" <<endl;
}
void display()
{ cout <<"Car: AstonMartin"; Car::display();
}
AstonMartin* clone()const
{ return new AstonMartin(*this);
}
};
int main()
{
CarP saab =std::make_shared <Saab>(100);
CarP aston =std::make_shared <AstonMartin>(200);
Garage montreal;
montreal.ReceiveCar(saab);
montreal.ReceiveCar(aston);
montreal.display();
Garage miami(montreal); // your decision to offer the user a copy constructor:
miami.display();
}
答案 1 :(得分:0)
将您的方法更改为以下
public void setName(String name) {
if(name != null) {
//this.setName(name);
this.name=name;
} else {
System.out.println("Thats not his name");
}
}
还有这个:
public void callSetNameFunction() {
WebView wvob=(WebView)myObject;
wvob.setName("ola");
}
setName方法与WebView类有关。对象类引用无法找到它。