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
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.
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.
精彩评论