雁过请留痕...
代码改变世界

java匿名类

2016-09-07 16:23  xiashengwang  阅读(305)  评论(0编辑  收藏  举报

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