new interface() 用法

来源:百度知道 编辑:UC知道 时间:2024/05/21 07:13:58
下面代码自动 new 了Comparator() 接口一个对象,省略了声明class,这种方法应用了什么特性,有什么名字吗
Set executionDescriptors = new TreeSet(new Comparator() {
public int compare(Object o1, Object o2) {
try {
ExecutionDescriptorType ed1 = (ExecutionDescriptorType) o1;
ExecutionDescriptorType ed2 = (ExecutionDescriptorType) o2;
return ed1.getTargetDirectory().compareTo(ed2.getTargetDirectory());
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
log.logp(Level.SEVERE, this.getClass().getName(), "runTdf", "That is sure surprising - Exception thrown in Comparator: " + sw.toString());
}
return -1;
}
});

这是JAVA中匿名内部类的用法.从你所给出的程序中第一个{到最后的},此部分就是匿名内部类,它没有类名,却是实现了Comparator接口。
你给的这个例子,是应用在语句中的匿名内部类,JAVA语法对这种用法的格式要求是:
new 接口或抽象父类名(){//匿名内部类的定义部分}

更详细的内容建议你搜索“JAVA 内部类”。

方法如下:
1.接口一般定义的是常量和一些抽象方法。

2.接口的引用指向实现的对象,尽量定义为接口或父类的引用;

3.接口只能定义抽象方法而且默认为是Public,常量用public static
final 修饰;

4.通过implements来引用接口;

5.多个无关类可以实现一个接口,但接口的引用必须指向实现的对象;

6.一个类可以实现多个无关的接口(这点和继承要有所区别);

7.和继承一样,接口与实现类之间存在多态性;

8.接口可以继承其他的接口,并添加新的属性和抽象方法;

9.在类中实现接口的方法时必须加上public修饰符。

@gp_cat 说的对

检测硬盘