Java – access to instances of static methods

I just started using Java. I was looking at the nested class topic and tried something. Suddenly, this happened:

class Encloser
{
  static int i;

  static void m1()
  {
    System.out.println(i);
  }

  static void m2()
  {
    Enclosee.accessEncloser();
  }

  static class Enclosee
  {
    static void accessEncloser()
    {
      i = 1;
      m1();
    }

    static void accessEncloserNew()
    {
      m2();
    }
  }
}

class EncloserTest
{

  public static void main(String[] args)
  {
    Encloser ee = new Encloser();
    Encloser.Enclosee e = new Encloser.Enclosee();
    ee.m1();
    ee.m2();
    e.accessEncloser();
    e.accessEncloserNew();Encloser.m1();
    Encloser.m2();
    Encloser.m1();
    Encloser.Enclosee.accessEncloserNew();
    Encloser.Enclosee.accessEncloser();
  }

}

Running the above code will not give any errors / exceptions It just runs The confusion here is, how does an instance call a static method here? Isn't it a static method like the class method in ruby?

Any explanation will be appreciated:)

Solution

This is allowed by the language:

ee.m1();

But you should write:

Encloser.m1();

The compiler should issue the following warning to inform you:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>