内部类'实例无法访问外部类'数据成员

时间:2017-04-11 12:34:41

标签: java inner-classes

文档说“InnerClass的实例只能存在于OuterClass的实例中,并且可以直接访问其封闭实例的方法和字段。”这意味着使用内部类的实例,我可以访问外部类的成员。但我无法这样做。

public class TopLevel {

    private int length;

    private int breadth;

    public class NonstaticNested{
        private static final int var1 = 2;

        public int nonStaticNestedMethod(){
            System.out.println(var1);
            length = 2;
            breadth = 2;
            return length * breadth;
        }
    }

    public static void main(String[] args) {



        TopLevel topLevel = new TopLevel();
        NonstaticNested nonStaticNested = topLevel.new NonstaticNested();

        // Trying to access the length variable on 'nonStaticNested' instance, but not able to do so.

    }

}

1 个答案:

答案 0 :(得分:0)

我希望主要评论是自我发言。

public class A {
    int a = 1;

    public static void main(String[] args) {
        B b = new B(); 
        // Works as "a" is defined in "A"
        System.out.println(b.a);
        // Works as "b" is defined in "B"
        System.out.println(b.b);
        C c = new C();
        C.D d = c.new D();
        // Works as "c" is defined in "c"
        System.out.println(c.c);
        // Works as "d" is defined in "D"
        System.out.println(d.d);
        // Error here as there is no "c" defined within "D", it´s part of "C" and here´s your
        // logical mistake mixing it somewhat with what inheritance provides (just my guess).
        System.out.println(d.c);
    }
}

class B extends A {
    int b = 1;
}

class C {
    int c = 1;
    class D {
        int d = 2;
        public D() {
            // Has access to "c" defined in C, but is not the owner.
            c = 2;
        }
    }
}