public int getwidth() {
return width;
}
public int gethight() {
return hight;
}
我在另一个类中有这个方法。我现在需要在另一个类(class)中使用它们来获取此信息。问题是:尽管(在我看来)它不是静态上下文,但它不断告诉我它是静态上下文,因此它不起作用。
void setWidth() {
/* getterclass is the class where the getwidth method is in */
this.width = getterClass.getwidth();
}
我按照这个方法尝试过,但是不行。
无论我做什么,它总是告诉我这是一个静态上下文。
在我看来,我在某个地方犯了一个可怕的错误。
最佳答案
您需要有该类的实例才能在非静态上下文中调用该方法。当您说类名-点-方法时,这是在尝试调用静态方法。
您需要创建该类的实例或接受一个作为参数。
void setWidth()
{
GetterClass instance = new GetterClass();
this.width = instance.getwidth();
}
或
void setWidth(GetterClass instance)
{
this.width = instance.getwidth();
}
关于java - 获取另一个类的变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21008989/