2017-04-11 1 views
-3

ドキュメントには、「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. 

    } 

} 
+0

よく...あなたがやっていることや手がかりを知らずに知っている人。 (コードなし) – SomeJavaGuy

+0

@SomeJavaGuyがコードを追加しました。助けてください。 –

+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; 
     } 
    } 
} 
関連する問題