java匿名类

时间:2021-06-09 10:02:55

一般情况下,我们需要声明一个类去继承一个接口,然后再new这个类,赋值给接口。但有时后这个类只会被调用一次,为了调用方便,那么就可以用匿名类来简化这个步骤。

interface IKey{
void open();
}

public class Ex21 {
public static void main(String[] args){
IKey instance= new IKey(){
public void open(){
System.out.println("this is shot");
}
};
openDoor(instance);
} private static void openDoor(IKey key){
key.open();
}
}

感觉很方便,还可以进一步简化

public class Ex21 {
public static void main(String[] args){
openDoor(new IKey(){
public void open(){
System.out.println("this is shot");
}
});
} private static void openDoor(IKey key){
key.open();
}
}

直接new了一个接口,然后实现,这点比C#进步。