익명 내부 클래스 클래스 이름 없이 선언된 내부 클래스입니다. 조금도. 즉, 이름이 없는 내부 클래스를 익명 내부 클래스라고 합니다. . 이름이 없으므로 생성자 를 가질 수 없습니다. 생성자 이름이 클래스 이름과 동일하다는 것을 알고 있기 때문입니다.
익명 내부 클래스를 정의할 수 있습니다. new 를 사용하여 개체를 만듭니다. 한 단계에서 동시에 연산자.
구문
new(argument-list){
// Anonymous class body
} 자바의 익명 내부 클래스 유형
- 클래스를 확장하는 익명의 내부 클래스
- 인터페이스를 구현하는 익명의 내부 클래스
- 인수로서의 익명 내부 클래스
클래스를 확장하는 익명의 내부 클래스
새로운 키워드는 익명 내부 클래스의 개체를 만드는 데 사용됩니다. 상위 클래스 유형에 대한 참조가 있습니다.
예
class Car {
public void engineType() {
System.out.println("Turbo Engine");
}
}
public class AnonymousClassDemo {
public static void main(String args[]) {
Car c1 = new Car();
c1.engineType();
Car c2 = new Car() {
@Override
public void engineType() {
System.out.println("V2 Engine");
}
};
c2.engineType();
}
} 출력
Turbo Engine V2 Engine
인터페이스를 구현하는 익명의 내부 클래스
새로운 키워드는 익명 내부 클래스의 개체를 만드는 데 사용됩니다. 인터페이스 유형에 대한 참조가 있습니다.
예
interface Software {
public void develop();
}
public class AnonymousClassDemo1 {
public static void main(String args[]) {
Software s = new Software() {
@Override
public void develop() {
System.out.println("Software Developed in Java");
}
};
s.develop();
System.out.println(s.getClass().getName());
}
} 출력
Software Developed in Java AnonymousClassDemo1$1
인수로서의 익명 내부 클래스
익명 내부 클래스를 사용할 수 있습니다. 메서드나 생성자에 전달할 수 있도록 인수로 사용합니다.
예
abstract class Engine {
public abstract void engineType();
}
class Vehicle {
public void transport(Engine e) {
e.engineType();
}
}
public class AnonymousInnerClassDemo2 {
public static void main(String args[]) {
Vehicle v = new Vehicle();
v.transport(new Engine() {
@Override
public void engineType() {
System.out.println("Turbo Engine");
}
});
}
} 출력
Turbo Engine