开发者

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]

This question already has answers here: 开发者_C百科 Closed 11 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜