Language/Java
익명 클래스
Jinn
2024. 1. 6. 23:34
일회용 클래스. 정의와 생성을 동시에 함.
// 익명 클래스 형태
new 조상클래스() {
// 멤버
}
class A {
public static void main(String[] args) {
Button b = new Button("Start");
b.addActionListener(new EventHandler()); // 2. 생성
}
}
class EventHandler implements ActionListener { // 1. 정의
public void actionPerformed(ActionEvnet e) {
System.out.println("ActionEvent occurred");
}
}
한 번만 사용될 클래스인 EventHandler 클래스를 익명 클래스로 작성하면 아래와 같다.
class A {
public static void main(String[] args) {
Button b = new Button("Start");
b.addActionListener(new ActionListener() { // 정의 + 생성
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent occurred");
}
});
}
}