在java中,直接对接口不能实例化。但在匿名化类中,可以new一个接口,里边跟上对接口函数的实现。
代码示例:
// 定义一个接口
package com.thb;
public interface Another {
String name();
}
// 定义一个类
package com.thb;
public class Test1 {
public static void main(String[] args) {
/*
* 表面看起来是针对接口实例化,但因为里边跟上对接口函数的实现,
* 其实这个是一个匿名类
*/
Another another = new Another() {
@Override
public String name() {
return "hello";
}
};
// 如果下面代码的注释去掉就会出错,因为不能对一个接口实例化
//Another two = new Another();
}
}