public class Learning {
int i = 1; // i is assigned to 1.
static int s = 2;// s is assigned to 2.
Learning() {
i = 0; s++; // i is assigned to 0 and s increases to 2.
System.out.println("test: " + i + s);// this line will display test: 03 since the values are above given.
}
public static void main (String [] args) {
Learning t1 = new Learning();// Creating and instance variable from the Class Learning.
System.out.println("t1: " + t1.i + t1.s);//t1 reaches with the help of the . the value of i as well as s and again this line will print out t1: 03
t1.s = 6;// Now the variable get s new value which is 6
Learning t2 = new Learning();// Creating another instance variable from the class called Learning
t2.i = 8;// Now the value for i is set for 8.
System.out.println("t2: " + t2.i + t2.s);// Now I thought the program would display t2: 86 since I have already got the value 8 and 6 assigned above, but it doesn't do that.
}
}
好吧伙计们,正如上面所看到的,我有了一个新的Java代码,我想总而言之我确实理解了很多东西,至少我在我理解的东西上面做了注释,并且认为我的思维方式是正确的。
请随意检查我的上述评论,如果我错了,请纠正我。
我已经测试过,上面的代码实际打印如下:
test: 03
t1: 03
test: 07
t2: 87
所以换句话说我是部分正确的,我根本不明白为什么它打印 test: 07,因为没有循环,为什么 t2: 87 不是 t2: 86?
我最初期待这样的事情:
test: 03
t1: 03
t2: 86
有专业人士想检查一下吗?
提前致谢。
最佳答案
每次创建 new Learning()
时都会调用
Learning
,因为它是 Learning 类的所有实例的构造函数。您创建了两个 Learning
实例,因此 test
被打印两次。该值为 87
的原因是 s
是 static
。这意味着 Learning
的所有实例都共享相同的 s
值。因此,将 t1
的 s
实例修改为 6
也会修改 t2 的 s
实例,然后该实例会递增在其构造函数中,变为 7
。
关于java - 任务02 : How does this Java Code work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895325/