Java接口与实例化

时间:2023-03-08 16:10:14

看代码看到

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

这种实现接口方式其实就是一个实现一个继承接口的匿名类。

http://blog.sina.com.cn/s/blog_70441c8e0101sgnf.html