java - 获取另一个类的变量值

标签 java static getter

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/

相关文章:

c - 跳入 C 中的一个 block

java - 面向对象设计 : Static fields

objective-c - 为 NSOperationQueue 创建 Setter

java - 使用java检查datalake中是否存在文件夹

java - Math.scalb 有什么用?

java - 如何让任务x在计划任务y之后运行

java - junit类中的顺序

java - 定义一个不返回特定字段的 setter/getter 是好的做法吗?

Java for-each on getter

java - XSLT 2.0 从 xml 生成输出文件名