2009-11-18 2 views
4

나는이 라인을 통해 조금 의심했습니다 : 우리는 또한 다음과 같은 구문을 사용하여 익명 클래스를 정의 할 수있는 이유익명 클래스 질문

익명 클래스,

다음 생성자를 정의 할 수 없습니다 :

new class-name ([ argument-list ]) { class-body } 
+0

모두에게 감사드립니다! 이제 나는 이해했다. – Javadoubts

답변

9

익명 클래스에서 생성자를 정의하지 않으면 수퍼 클래스에서 생성자를 호출하고 있습니다.

익명 클래스에 적절한 생성자를 추가 할 수 없지만 유사한 작업을 수행 할 수 있습니다. 즉, 초기화 블록.

public class SuperClass { 
    public SuperClass(String parameter) { 
     // this is called when anonymous class is created 
    } 
} 

// an anonymous class is created and instantiated here 
new SuperClass(parameterForSuperClassConstructor) { 
    { 
     // this code is executed when object is initialized 
     // and can be used to do many same things as a constructors 
    } 

    private void someMethod() { 

    } 

} 
3

귀하의 예는 익명의 서브 클래스 class-name을 만들고, 당신은 당신의 익명 클래스에 특정 생성자를 만들 수 없습니다. 인수 목록은 class-name 생성자에 대한 인수 목록과 동일합니다.

1

이것은 정의 된 생성자가있는 class-name이라는 추상 클래스가 있음을 의미합니다. 익명 클래스에서 해당 생성자를 사용하는 것은 하위 클래스의 생성자에서 super()를 사용하는 것과 비슷합니다.