Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what exactly is the reason that we cannot declare static methods in [public] inner classes unless those inner classes are also declared static?azi [duplicate]

Possible Duplicate:
Why cant we have static method in an inner class?

Hi all, in java what exactly is the reason that we cannot declare static methods in [public] inner classes unless those inner classes are also declared static?

Amazingly top level classes can have any number of static methods without the need to have any special modifier

like image 749
Pacerier Avatar asked May 10 '11 02:05

Pacerier


2 Answers

Non-static inner classes come into existence only in the context of an instance of the outer class.

So ... if you're going to have a static method, the whole inner class has to be static. Without doing that, you couldn't guarantee that the inner class existed when you attempted to call the static method.

like image 67
Brian Roach Avatar answered Nov 11 '22 07:11

Brian Roach


The question to ask is -- if you do have a static method inside an inner class, how would you call that static method? The answer is, you can't.

An inner class is tied to instances of the outer class.

From Effective Java -- "Each instance of a nonstatic [nested] class is implicitly associated with an enclosing instance of its containing class".

This is the reason for making the "inner" class static. This actually a static nested class and its a full-blown class thats merely present in the enclosing class for packaging convenience.

like image 30
Kal Avatar answered Nov 11 '22 09:11

Kal