What exactly is the reason that we cannot declare static methods in [publicly available] inner classes unless these inner classes are also declared static? azi

Possible duplicate:
Why can't we use the static method in the inner class?

Hello everyone, in java, what exactly is the reason that we cannot declare static methods in [publicly available] inner classes if these inner classes are also not declared static?

Surprisingly, top-level classes can have any number of static methods without the need for any special modifier

+7
source share
2 answers

Non-static inner classes arise only in the context of an instance of an outer class.

So ... if you have a static method, the whole inner class should be static. Without doing this, you could not guarantee that the inner class existed when you tried to call the static method.

+2
source

The question that is being asked is if you have a static method inside an inner class, what would you call this static method? The answer is that you cannot.

The inner class is bound to instances of the outer class.

From effective Java - "Every instance of a non-static [nested] class is implicitly associated with a containing instance of its containing class."

This is the reason why the static "inner" class is static. This is actually a static nested class and its full-blown class, which is just present in the enclosing class for ease of packaging.

+1
source

All Articles