익명 클래스란 무엇인가?
익명 클래스는 이름이 없는 클래스를 의미한다.
클래스의 선언과 객체의 생성을 동시에 하기 때문에 단 한 번만 사용될 수 있고 오직 하나의 객체만을 생성할 수 있는 일회용 클래스이다.
익명 클래스는 다음과 같은 특징을 가진다.
- 생성자를 가질 수 없다
- 하나의 클래스로 상속받는 동시에 인터페이스를 구현하거나 둘 이상의 인터페이스를 구현할 수 없다. 즉 오로지 하나의 클래스를 상속받거나 단 하나의 인터페이스만을 구현할 수 있다.
예시 코드로 나타내면 다음과 같다.
// 익명 클래스를 사용하지 않은 경우
class Innerclass {
public static void main(String[] args) {
Classb b = new ClassB("make");
b.addActionListener(new EventHandler());
}
}
class EventHandler implements ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent occurred...");
}
}
//익명 클래스를 사용한 경우
class Innerclass {
public static void main(String[] args) {
Classb b = new ClassB("make");
b.addActionListener(new EventHandler(){
public void actionPerformed(ActionEvent e) {
System.out.println("ActionEvent occurred...");
});
}
}
'Dev > Java' 카테고리의 다른 글
지네릭스(Generics) - 지네릭스를 알면 API 문서를 읽기 쉽다! (0) | 2024.03.25 |
---|---|
Comparator 와 Comparable 의 차이 - 객체 내부 비교와 외부 비교 관점 (1) | 2024.03.25 |
Java Stream ( feat. Optional 과 collect ) (1) | 2024.03.18 |
다형성(Polymorphism)과 참조변수 ( with. instanceof 연산자의 필요성) (0) | 2024.03.12 |
람다식 ( Lamda expression ) / @FunctionalInterface (0) | 2024.03.11 |