Why can't a non-static inner class have static members (fields and methods)?

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

I know that to create a non-static object of an inner class, an object of an external class is required, and the created non-static object of the inner class automatically has a hidden link to the object of the outer class. But why does a non-static inner class have static elements? A Java developer just has to deny access to non-static fields of an outer class inside a static method of an inner class, this will make more sense, no?

If it makes no sense to have static members in an inner class, why can an inner class inherit static members by inheriting a class that has static members?

I read this post . As already mentioned:

Inner classes can inherit static members that are not compilation although they cannot declare them. Nested classes that are not inner classes can freely declare static members in accordance with the usual rules of the Java programming language.

Is this an agreement?

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 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() {
    };
}
+9
source share
3 answers

, . , , () . , , .

, , , (Outer.Inner.StaticMember).

+8

1. An object of Non-static inner class instance/object Outer Class (.. ).

, .

3. Instance variables methods Non-static inner class , > static (.. ),

4.. Instance inner class, a Object of Outer enclosing class. non-static class outer enclosing class.

:

Outer o = new Outer();
Outer.Inner i = o.new Inner();
+13

It makes no sense to provide a static method inside a non-static inner class. Instead, can you use a non-static method inside an outer class?

+1
source

All Articles