Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
SCJP Online Training » Discussions

Static methods in inner classes

Why it was designed in such a way that we cannot create static methods in inner classes in java?

It is because of an implicit reference to the outer class? and so no valid syntax exist to access inner static methods?


Thank you!

You answered your own question correctly!


When it comes to non-static inner classes, the class spans through the scope of an object of its outer class. A static member in the class makes no sense as you can't access the class in a static way at the first place. It should only work if you make the outer class static.


When it comes to method-local inner classes (as in this question), you still can't define a static member in it, because the life of the class spans through the scope of the method. Consider this:


public void doSomething() {
   class Bug {
       static int x = 0;
   }
   x++;
   System.out.println(x);
}



Let's suppose the above code works. With that assumption, what would be the output when you call the doSomething() method twice? When that method is called at the second time, would Bug be the same class as in the first method call? Or should it be considered as a new class? Allowing it run either way brings in a lot of ambiguity.


The general sense of a method-local inner class is to span through the scope of the method, and theoretically, it should have no meaning after the method exists. That said, there's no point in allowing static access in a class that only spans through the method's life.

ExamLab © 2008 - 2024