静态变量与非静态变量

use*_*619 0 java

我定义了一个对象并声明了一个静态变量i.在该get()方法中,当我尝试打印实例和类变量时,两者都打印相同的值.

不是this.i实例变量吗?它应该打印0而不是50吗?

public class test {
    static int i = 50;
    void get(){
        System.out.println("Value of i = " + this.i);
        System.out.println("Value of static i = " + test.i);
    }

    public static void main(String[] args){
        new test().get();
    }

}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 8

不,只有一个变量 - 您没有声明任何实例变量.

遗憾的是,Java允许您访问静态成员,就像您通过相关类型的引用访问静态成员一样.这是一个设计缺陷IMO,一些IDE(例如Eclipse)允许您将其标记为警告或错误 - 但它是语言的一部分.你的代码是有效的:

System.out.println("Value of i = " + test.i);
System.out.println("Value of static i = " + test.i);
Run Code Online (Sandbox Code Playgroud)

如果通过相关类型的表达式去,它甚至不检查值-例如:

test ignored = null;
System.out.println(ignored.i); // Still works! No exception
Run Code Online (Sandbox Code Playgroud)

尽管如此,仍然会评估任何副作用.例如:

// This will still call the constructor, even though the result is ignored.
System.out.println(new test().i);
Run Code Online (Sandbox Code Playgroud)