- 추상 메서드 때문에 객체 생성이 안 되는 경우, 객체 생성시 추상메서드를 즉석에서 구현하면 객체 생성이 가능.
- 추상 클래스, 인터페이스에 대하여 익명 클래스 방법으로 객체 생성이 가능.
- 객체 생성 구문의 맨 뒷부분에 중괄호({ })를 사용하고, 안에 메서드를 구현하면 된다.
public class Main {
public static void main(String[] args) {
Player player = new Player() {
@Override
public void 방어() {
System.out.println("방어");
}
};
player.공격();
player.방어();
Doctor doctor = new Doctor() {
@Override
public void heal() {
System.out.println("치료");
}
@Override
public void talk() {
System.out.println("대화");
}
};
doctor.heal();
doctor.talk();
}
}
abstract class Player {
public void 공격() {
System.out.println("공격");
}
public abstract void 방어();
}
interface Doctor {
void heal();
void talk();
}