java - 任务02 : How does this Java Code work?

标签 java

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 的原因是 sstatic。这意味着 Learning 的所有实例都共享相同的 s 值。因此,将 t1s 实例修改为 6 也会修改 t2 的 s 实例,然后该实例会递增在其构造函数中,变为 7

关于java - 任务02 : How does this Java Code work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895325/

相关文章:

java - 从文件中为hadoop中的映射器创建自定义键值

java - RestAssured - 如何检查 <a id ="some number"></a> 中的 id?

java - 找不到适合 jdbc :oracle:thin:@localhost:1522:xe 的驱动程序

java - 自动化/处理第 5 个下拉列表 url https ://jedwatson. github.io/react-select/named as Github users(Aysnc with fetch.js)

java - 为什么我无法使用 List 引用类型对象访问 LinkedList 方法

java - FileUtil.copyMerge 不只是删除合并的文件?

java - Java中接口(interface)实现的继承

java - 有没有办法可以修改 ParseTree 及其附带的 TokenStream?

java - 错误: not statement in java

JavaFX 8 - Tabpanes 和选项卡,每个选项卡都有单独的 FXML 和 Controller