【问题标题】:I am working on static and instance variables in Java, where I couldn't understand the output of the code我正在研究 Java 中的静态和实例变量,我无法理解代码的输出
【发布时间】:2020-08-07 15:03:49
【问题描述】:
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 指的是method1 中的obj1.y 还是t.y

为什么更改this.yt.y 没有任何影响?

【问题讨论】:

  • y 不是静态的,这意味着每个对象都有不同的实例,t 对象与this 对象是不同的对象。
  • 感谢您的回答。您的回答非常有帮助

标签: java static this instance-variables


【解决方案1】:

y 是一个全局实例变量。当您调用obj1.method1(10); 时,this 中的method1 指的是obj1。所以this.y在method1中引用obj1.y

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

因为this 指的是obj1,所以您正在更改obj1 的实例变量而不是t

【讨论】:

  • 感谢您的回答。您的回答非常有帮助
猜你喜欢
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多