看代码看到
public Runnable r = new Runnable() { @Override public void run() { ... } }
接口不能new ,不过可以生成一个匿名类,省略了写一个具体类实现接口的开销。
public class Main { public static void main(String[] args) { String a=new CustomerImpl().sayHello("hongda"); System.out.println(a); String b=new Customer(){ public String sayHello(String name){ return "Hello2 "+name; } }.sayHello("hongdada"); System.out.println(b); } } interface Customer { public String sayHello(String name); } class CustomerImpl implements Customer { @Override public String sayHello(String name) { return "Hello, " + name; } }
Hello, hongda
Hello2 hongdada
如果接口内有多个方法呢?
public class Main { public static void main(String[] args) { String a=new CustomerImpl().sayHello("hongda"); System.out.println(a); String b=new Customer(){ public String sayHello(String name){ return "Hello2 "+name; } }.sayHello("hongdada"); System.out.println(b); } } interface Customer { public String sayHello(String name); public int Add(int a ,int b); } class CustomerImpl implements Customer { @Override public String sayHello(String name) { return "Hello, " + name; } @Override public int Add(int a ,int b){ return a+b; } }
Error:(8, 32) java: <匿名com.company.Main$1>不是抽象的, 并且未覆盖com.company.Customer中的抽象方法Add(int,int)
匿名类内部实现接口全部方法:
public class Main { public static void main(String[] args) { String a=new CustomerImpl().sayHello("hongda"); System.out.println(a); String b=new Customer(){ public String sayHello(String name){ return "Hello2 "+name; } public int Add(int a ,int b){ return a+b; } }.sayHello("hongdada"); System.out.println(b); } } interface Customer { public String sayHello(String name); public int Add(int a ,int b); } class CustomerImpl implements Customer { @Override public String sayHello(String name) { return "Hello, " + name; } @Override public int Add(int a ,int b){ return a+b; } }
Hello, hongda
Hello2 hongdada
这种实现接口方式其实就是一个实现一个继承接口的匿名类。