如何通过调用方法来分配类变量值?

psy*_*ama 3 java

我试图通过方法为类变量赋值.但是,在执行超出方法范围后,变量仍然初始化为默认值.我们如何在Java中实现这一目标?

我想通过调用方法hello()将x初始化为5.我不想通过使用构造函数或使用它来初始化.可能吗?

public class Test {
    int x;
    public void hello(){
        hello(5,x);
    }
    private void hello(int i, int x2) {
        x2 = i;
    }
    public static void main(String args[]){
        Test test = new Test();
        test.hello();
        System.out.println(test.x);
    }
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 10

当你这样做

hello(5,x);
Run Code Online (Sandbox Code Playgroud)

然后

private void hello(int i, int x2) {
    x2 = i;
}
Run Code Online (Sandbox Code Playgroud)

看起来你可能试图将字段本身作为参数传递给hello方法,并且在做的时候x2 = ix2想要引用该字段.这是不可能的,因为Java仅支持按值传递.即只要将变量作为参数赋给方法,它将包含它包含的值,而不是变量本身.

(感谢@Tom在评论中指出对问题的这种解释.)