【问题标题】:JAVA instance vs local variableJAVA 实例与局部变量
【发布时间】:2025-12-05 06:20:06
【问题描述】:
import comp102x.IO;  
  
public class testing {
  
        private int x;

        public testing(int x) {
  
                x = x;
        }

        public static void main(String[] args) {
  
                testing q1 = new testing(10);
                IO.outputln(q1.x);
        }
}

为什么输出是 0 而不是 10?这是一个 JAVA 脚本。实例和局部变量的概念让我很困惑,有人可以帮忙解释一下吗?

【问题讨论】:

标签: java instance local


【解决方案1】:
public testing(int x) {      
  x = x;
}

这里你只是将局部变量 x 的值重新赋值给它自己,它不会改变实例变量。

要么改变局部变量的名字,像这样:

public testing(int input) {
  x = input;
}

或确保将值分配给实例变量,如下所示:

public testing(int x) {
  this.x = x;
}

【讨论】: