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; 
     } 
    } 
} 
관련 문제