Ch7-51~52. 익명 클래스
0. 목차
Chapter7. 객체지향 프로그래밍Ⅱ
Ch7 - 51. 익명 클래스
Ch7 - 52. 익명 클래스 예제
Ch7 - 51. 익명 클래스
▶ 익명 클래스(anonymous class)란?
▷ 이름이 없는 일회용 클래스
▷ 정의와 생성을 동시에
// 클래스 정의
class Name extends Object{ }
// 객체 생성
Name name = new Name();
그런데 이름이 없다면?
// 클래스 정의
class ? extends Object{ }
// 객체 생성
? name = new ?();
조상의 이름을 대신 적어 줌
// 정의 + 생성
new Object {
// 멤버 선언
}
▶ 익명 클래스(anonymous class)의 선언 방법
▷ 방법1 : 조상 클래스 이름 빌리기
new 조상 클래스 이름 {
// 멤버 선언
}
▷ 방법2 : 구현 인터페이스 이름 빌리기
new 구현 인터페이스 이름 {
// 멤버 선언
}
Ch7 - 52. 익명 클래스 예제
▶ AWJ(java의 윈도우 프로그래밍) 코드를 익명 클래스로 변경
▷ EventHandler는 일회성 클래스
class Test {
public static void main(String[] args) {
Button button = new Button("Start");
button.addActionListener(new EventHandler()); // 객체 생성
}
}
class EventHandler implements ActionListener { // 클래스 정의
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent coourred!");
}
}