一般情况下,我们需要声明一个类去继承一个接口,然后再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#进步。

相关文章:

  • 2022-12-23
  • 2021-11-28
  • 2021-08-29
  • 2021-10-16
  • 2021-07-17
  • 2021-09-28
  • 2021-06-20
猜你喜欢
  • 2021-08-30
  • 2022-01-18
  • 2022-12-23
相关资源
相似解决方案