2017-05-07 153 views
0

我知道静态变量是类的一部分,而不是对象的一部分。如何代码工作的以下行没有任何问题Java中的静态变量

class M 
{ 
    static int i=0; 
    void Inc() 
    { 
    System.out.println("Global "+M.i); 
    System.out.println("Local "+this.i); 
    } 
}  

public class StaticTest 
{ 
    public static void main(String args[]) 
    { 
    M m1=new M(); 
    m1.i=99;  //How can the m1 object access i variable of the class 
    m1.Inc(); 
    } 
} 

输出我得到的是

Global 99 
Local 99 

如何之类的M1对象访问我的变量?

+0

所有实例变量共享该静态变量。你引用了它不正确,但它仍然运行 –

+0

http://stackoverflow.com/questions/17242649/can-non-static-methods-modify-static-variables –

回答

1

在两种情况下它都是非常相同的变量。

不幸的是,java允许您使用non-static语法访问静态字段。

这就是这一切,没有任何其他背后。

0

是的,它允许非静态成员访问和更新静态成员。

查看更多的信息here