使用 Java 从方法设置实例变量

Set Instance Variable from Method using Java

正如标题所解释的那样,我希望能够使用方法 中包含的计算产生的数据来设置实例变量。

我制作了一个示例代码来演示我正在尝试做什么,以及我在搜索互联网后拼凑的解决方案。但显然,我未能成功复制其他人所做的事情。

在此先感谢您的帮助。

这段代码的目的是使用"myMethod"方法将"Max"的实例变量设置为“6”的值,然后使用"printMethod"打印 "Max".

的值
public class Main {
//Main class, Of Coruse. 
    private int Max;
//The value I wish to be changed by the method. 

    public int getMax() {
        return Max; 
    }//The process which is supposed to get the value from the method. 

    public static void main(String[] args) {
        Main Max = new Main();
        {
            Max.printMax();
        }
    }//The main method, and non-static reference for printMax. 

    public void myMethod() {//Method for assigning the value of "Max" 
        int Lee = 6;
        this.Max = Lee;
    } 

    public void printMax() {//Method for setting, and printing the value of "Max" 
        Main max = new Main();
        int variable = max.getMax();

        System.out.println(variable);
    } 
}

我认为您对 class 实例的工作方式有一些误解。我建议你先学习OOP的基础知识。

总之,虽然你没有告诉我预期结果应该是什么,但我猜你想打印6。所以这是解决方案:

private int Max;

public int getMax() {
    return Max;
}

public static void main(String[] args) {
    Main Max = new Main();
    Max.printMax();
}

public void myMethod() {
    int Lee = 6;
    this.Max = Lee;
}

public void printMax() {
    this.myMethod();
    int variable = this.getMax();
    System.out.println(variable);
}

让我解释一下我所做的更改。

  • 在你的main方法中,new Main()后面的{}不需要了,所以我删掉了。
  • printMax中,不需要再次创建Main实例,因为this已经一个。
  • 您无法打印 6 的原因是因为变量 max 从未更改过。为什么?因为您只是 声明了一个方法 来改变 max,但是那个方法 (myMethod) 并没有被调用!所以我只是添加了一行来调用 myMethod.