3

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

Mark Pope
11.3k11 gold badges52 silver badges59 bronze badges
asked Jan 28, 2014 at 13:48
0

3 Answers 3

6

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

answered Jan 28, 2014 at 13:51
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the prompt repliy @marcin_j :) But just FYI, i didn't get any warnings :|
Maybe it depends on ide / java compiler / used parameters, I pasted your code into rextester.com/runcode.
3

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.

answered Jan 28, 2014 at 13:51

1 Comment

It's slightly better, but OP is confused about "accessing by objects", which doesn't at all happen, however your answer reads otherwise. No objects at all are involved here, and even variables are optional. ((Encloser)null).m1() brings this out most poignantly.
2

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

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

answered Jan 28, 2014 at 13:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.