Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

forDevLife

[java] 익명 클래스(anonymous class) 본문

Java

[java] 익명 클래스(anonymous class)

JH_Lucid 2021. 5. 28. 21:43
new 조상클래스 혹은 구현 인터페이스 이름() {
	//멤버 선언
}

- 말 그대로 이름이 없는 일회용 클래스. 딱 한번 인스턴스 만들고 끝냄

- 이름이 없으므로 조상 / 인터페이스 이름을 쓴다.

- 클래스 정의 + 생성을 동시에 한다.

 

package com;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Ex14_0 {
    public static void main(String[] args) {
        Button b = new Button("Start");
        b.addActionListener(new EventHandler());
    }
}
class EventHandler implements ActionListener { 
    public void actionPerformed(ActionEvent e) {
        System.out.println("ActionEvent occured");
    }
}

- 기존 코드를 보면, actionPerformed라는 메서드 딱 한번을 사용하기 위해 EventHandler라는 것을 만든다.

- 한번쓰고 말거면 비효율적이라, 이를 익명 클래스로 만든다.

 

package com;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Ex14_0 {
    public static void main(String[] args) {
        Button b = new Button("Start");
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("ActionEvent occured");
            }
        });
    }
}

- 위의 규칙 대로, EventHandler라는 클래스 이름 제거 하고,

- 인터페이스 이름을 new로 한 후 중괄호 안에 구현하고자 했던 메서드를 구현!

Comments