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() {
};
}