Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Instance able to access static method

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 :)

like image 415
Gaurav Manchanda Avatar asked Jan 17 '26 14:01

Gaurav Manchanda


2 Answers

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

like image 199
marcinj Avatar answered Jan 20 '26 02:01

marcinj


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.

like image 36
codingenious Avatar answered Jan 20 '26 03:01

codingenious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!