Language/Java

익명 클래스 (Anonymous Class)

kimjingyu 2023. 9. 15. 18:42
728x90

추상 클래스나 인터페이스의 추상 메서드를 구현하기 위해 생성자 뒤에 중괄호가 나오고, 코드를 오버라이딩하여 구현한다.

Car car = new Car() {
    @Override
    public void a() {
        System.out.println("이름없는 객체의 a 메서드 오버라이딩");
    }
};

car.a();
public class MyRunnableExecute {
    public void execute(MyRunnable myRunnable) {
        myRunnable.run();
    }
}
MyRunnable m = new MyRunnable() {
    @Override
    public void run() {
        System.out.println("달릴 수 있다.");
    }
};

MyRunnableExecute e = new MyRunnableExecute();
e.execute(m);

 

Lambda Interface

익명 클래스를 간략화시켜서 표현한 것으로 메서드를 하나만 가지고 있어야 한다. Stream API와 같이 사용하면 편리하게 기능을 구현할 수 있다.

728x90