Why a non-static inner-class cannot have static members (fields and methods)?

inner-classes, java, non-static, static, static-members

Solution

Technically there I don't know of any reason why the language restricts the use of static elements for inner classes. A nonstatic inner class can be emulated by using a normal class that takes the (formerly) enclosing instance as an argument to the constructor. Of course there are many little differences when it comes to visibility rules an visibility scopes.

I presume it was a language design decision, mostly because statics in non-static inner classes are confusing and non-intuitive to access (Outer.Inner.StaticMember).

Problem

Possible Duplicate: Why cant we have static method in an inner class? I know that the creation of a non-static inner-class object requires an outer-class object and the created non-static inner-class object automatically have a hidden reference to the object of the outer-class. But why can't a non-static inner-class have static members? The Java designer just have to disallow the access of non-static outer-class fields inside a static method of the inner-class, it would make more sense, non? If it does not make sense to have static members in an inner class, why inner class can inherit static members by inheriting a class who has static members? I read this post too. As is mentioned: Inner classes may inherit static members that are not compile-time constants even though they may not declare them. Nested classes that are not inner classes may declare static members freely, in accordance with the usual rules of the Java programming language. Is it a convention? Here is my code: ``` public class OuterClass { private int outerClassField; public void doSomethingOuterClass() { outerClassField = 1; } public static void doSomethingStaticOuterClass() { // outerClassField = 2; // Error: Because static method cannot access an specific object's field } public class InnerClass extends ClassWithStaticField { // Error: Why a non-static inner class cannot have static fields ? // public static int innerClassStaticField = 1; public void doSomethingInnerClass() { outerClassField = 3; staticField = 1; } // Error: Why a non-static inner class cannot have static methods ? // public static void doSomethingStaticInnerClass() { // outerClassField = 4; // } } public static void main(final String[] args) { // If it does not make sense to have static members in an inner class, why inner class can inherit statis members by inheriting a class who has static // members? OuterClass.InnerClass.staticField = 1; OuterClass.InnerClass.staticMethod(); } } class ClassWithStaticField { public static int staticField; public static void staticMethod() { }; } ```

Original source

Related problems