我正在研究Java中的静态变量和实例变量,我无法理解代码的输出。

问题描述 投票:0回答:1
package java_course;

public class staticVsInstance {

    static int x = 11; 
    private int y = 33; 

    public void method1(int x) {
        staticVsInstance t = new staticVsInstance();
        System.out.println("t.x "+t.x + " " +"t.y  "+ t.y + " " +"x "+ x + " "+"y " + y);
        this.x = 22;
        this.y = 44;
        System.out.println("t.x "+t.x + " " +"t.y  "+ t.y + " " +"x "+ x + " "+"y " + y);
    }

    public static void main(String args[]) {

        staticVsInstance obj1 = new staticVsInstance();

        System.out.println(obj1.y);
        obj1.method1(10);
        System.out.println(obj1.y);
    }
}

而输出是

33
t.x 11 t.y  33 x 10 y 33
t.x 22 t.y  33 x 10 y 44
44

是否 this.y 指代 obj1.yt.ymethod1?

为什么没有改变 this.y 任何影响 t.y?

java static this instance-variables
1个回答
0
投票

y 是一个全局实例变量。当你调用 obj1.method1(10);, thismethod1 指的是 obj1. 所以... this.y 指代 obj1.y 方法1中。

为什么改变this.y对t.y没有任何影响?

因为 this 指的是 obj1 所以你是在改变 obj1t.

© www.soinside.com 2019 - 2024. All rights reserved.