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


因此,换句话说,我是部分正确的人,我根本不明白为什么要打印测试:07,因为没有循环,为什么t2:87不是t2:86?

我最初期望的是这样的:

test: 03
t1: 03
t2: 86


任何专业人士想检查吗?

提前致谢。

最佳答案

每次创建Learning时都会调用new Learning(),因为它是Learning类所有实例的构造函数。您创建两个Learning实例,因此test被打印两次。值是87的原因是因为sstatic。这意味着Learning的所有实例都为s共享相同的值。因此,将t1s实例修改为6也会修改t2的s实例,然后在其构造函数中将其递增,并变为7

10-05 23:21