0

I know that static variables are part of class and not part of the Object . How can the following lines of code work without any problem

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();
   }  
}

The output i get is

Global 99
Local 99

How can the m1 object access i variable of the class?

2 Answers2

1

It is the very same i variable in both cases.

unfortunately, java allows you to access static fields using non-static syntax.

That is all there is to this, nothing else behind this.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

Yes, it is allowed for non-static members to access and update static members.

See this for more information here

Community
  • 1
  • 1