I just started with Java again, was looking into the Nested Classes topic, and was trying out some stuff, when 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 doesn't give any error/exception. It just runs. The confusion here is, how are instances able to call the Static Methods here? Aren't Static Methods like the Class Methods in Ruby?

Any explaination would be appreciated :)

有帮助吗?

解决方案

This is what language allows:

ee.m1();

but you should rather write:

Encloser.m1();

you compiler should issue warning like below, to inform you of that:

source_file.java:37: warning: [static] static method should be qualified by type name, Encloser, instead of by an expression ee.m1();

其他提示

Static methods can be accessed (but should not be, as a good programming practice) by objects too, because at compile time, these variable types are resolved into class names.

In compile time instance variables are replaced with class names if they are calling static methods.

ee.m1(); is interpreted as Enclosee.m1();

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top