Java Nested Interfaces and Inner Classes

Why can't a Java nested interface be non-stationary? And why can't the inner class contain static non-final members?

I ran into questions while going through Gosling, and so far I could not find the answer.

+4
source share
2 answers

If the nested class is non-static (i.e. the inner class), this means that each instance of it is bound to an instance of the outer class. Since the interface does not have its own instances, it seems that implementation classes should not be bound to an external object, so a static default value seems reasonable.

+8
source

I'm not sure why you cannot have static non-final members in an inner class, but since static members are not tied to any particular instance of an object, it doesn't matter if it is in an inner or outer class.

eg.

class OuterClass { private static int staticMember; class InnerClass { void incStatic() { staticMember++; } } } 

You can access the static member from the inner class, as if it were inside the inner class.

+2
source

Source: https://habr.com/ru/post/1347225/


All Articles