2014-02-19 5 views
2

익명 클래스가 인터페이스의 유형으로 정의 된 경우 익명 클래스가 인터페이스를 구현하지만 다른 클래스의 유형으로 정의 된 경우 (아래 그림 참조) 클래스를 확장하지 않는 것처럼 보입니다. 그것을 말했다). 익명 클래스는 중첩 클래스를 확장하는 경우Java에서 익명 클래스와 유형으로 정의 된 관계는 무엇입니까?

여기
public class AnonymousClassTest { 

    // nested class 
    private class NestedClass { 
     String string = "Hello from nested class."; 
    } 

    // entry point 
    public static void main (String args[]){ 
     AnonymousClassTest act = new AnonymousClassTest(); 
     act.performTest(); 
    } 

    // performs the test 
    private void performTest(){ 

     // anonymous class to test 
     NestedClass anonymousClass = new NestedClass() { 
      String string = "Hello from anonymous class."; 
     }; 

     System.out.println(anonymousClass.string); 

    } 
} 

는 다음 넣어은 "익명 클래스에서 안녕하세요."것, 출력을 실행하지만 때 "중첩 된 클래스에서 안녕하세요."를 읽고

+1

익명의 클래스에서 두 번째 필드를 선언한다고 생각합니다. String 수정자를 제거해보십시오. 문자열 만들기 = "안녕하세요 익명의 클래스에서." 문자열 필드를 비공개로 설정합니다. – Others

+0

그러나 이것은 사실이지만 익명 클래스의 String을 재정의하려고합니다. 상위 문자열에 접근하려면'super.string'을 사용하지 않아야합니까? – Continuity8

+0

아 ... 이제 알겠습니다. 필드가 무시할 수 없다는 것을 알지 못했습니다. 유일한 방법입니다. 나는 String 필드를 메서드처럼 취급하고있었습니다. – Continuity8

답변

3

필드는 무시할 수 없습니다. 클래스가 string이라는 필드를 선언하고 하위 클래스도 string이라는 필드를 선언하면 string이라는 두 개의 별도 필드가 있습니다. 예를 들어,이 프로그램은 :

class Parent { 
    public String string = "parent"; 
    public int getInt() { 
     return 1; 
    } 
} 

class Child extends Parent { 
    public String string = "child"; // does not override Parent.string 
    // overrides Parent.getInt(): 
    public int getInt() { 
     return 2; 
    } 
} 

public class Main { 
    public static void main(final String... args) { 
     Child child = new Child(); 
     System.out.println(child.string);   // prints "child" 
     System.out.println(child.getInt());   // prints "2" 
     Parent childAsParent = child; 
     System.out.println(childAsParent.string); // prints "parent" (no override) 
     System.out.println(childAsParent.getInt()); // prints "2" (yes override) 
    } 
} 

인쇄

child 
2 
parent 
2 

childAsParentParent 입력 때문에

, 그래서 실제 인스턴스 런타임 타입 Child있는 경우에도, Parent 선언 필드를 의미한다.

필드가 아닌 방법을 사용하도록 데모를 수정하면 예상했던 결과가 표시됩니다.

+0

아아, 알겠습니다. 고마워요! 내가 방법 일 것 인 것처럼 나는 들판을 다루고 있었다. 그래서 익명의 클래스를 정의하는 것은 그것을 정의하는 데 사용되는 타입을 확장합니까? 그러나 부모 유형으로 정의되었으므로 해당 필드에 액세스하면 해당 필드의 부모 인스턴스에 액세스합니다. – Continuity8

+1

@JonathanWhite : Re : 첫 번째 질문 : 예. 재 : 두 번째 질문 : 만약 당신이 정확하게 당신을 이해한다면, 정확히는 아닙니다. 예를 들어'System.out.println (new NestedClass() {String string = "Hello from anonymous class.";}. 문자열);''hello from anonymous class. 형식이 익명 인 표현식에서. 'anonymousClass.string'이''Hello from nested class. ''라는 이유는'anonymousClass' 표현식이'NestedClass' 타입이라는 것입니다. 무슨 뜻인지 알 겠어? – ruakh

+0

네, 감사합니다. – Continuity8