Java:为什么结果是5而不是10?

jav*_*uce 0 java oop

让A.java文件为:

    class B {static int i; }

    class A {
        public static void main(String[] args) {
            B a=new B();
            B b=new B(); 
            a.i=10;
            b.i=5; 

            System.out.println(a.i);
        }
    }
Run Code Online (Sandbox Code Playgroud)

为什么结果是5而不是10?

谢谢.

Jon*_*eet 6

因为你的变量是静态的.这意味着它与类型有关,而不是与该类型的任何特定实例有关.您的代码相当于:

// These are actually ignored as far as the subsequent lines are concerned.
// The constructor will still be executed, but nothing is going to read the
// values of variables "a" and "b".
B a = new B();
B b = new B();

// Note this is the *type name*.
B.i = 10;
B.i = 5; 
System.out.println(B.i);
Run Code Online (Sandbox Code Playgroud)

IMO允许通过这样的表达式访问静态成员是一个设计错误 - 在某些IDE(例如Eclipse)中,如果您愿意,它最终会发出警告甚至错误.