can we create an object of an interface?

本文解释了Java中使用匿名类实现Comparator接口以进行对象排序的过程,详细介绍了类的匿名性、接口实现及排序逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Definitely, the answer is no!
But look at the code below:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class EmployeeSort {

static Comparator<Employee> NAMESORT = new Comparator<Employee>(){

public int compare(Employee e1,Employee e2){
return e1.name.compareTo(e2.name);
}


};

public static void print(List<Employee> empList){
for (Employee o :empList){
System.out.println(o.name);
}
}

public static void main(String[] args) {
List<Employee> empList = new ArrayList<Employee>();
Employee e = new Employee("anil");
Employee e1 = new Employee("babe");
Employee e2 = new Employee("akhil");

empList=Arrays.asList(e,e1,e2);

print(empList);

Collections.sort(empList,NAMESORT);
print(empList);


}

}


How do you explain the code snippet below?

static Comparator<Employee> NAMESORT = new Comparator<Employee>(){

public int compare(Employee e1,Employee e2){
return e1.name.compareTo(e2.name);
}


};


Actually this expression instantiates a new object from an unnamed and previously undefined class, which automatically implements the interface named [b]Comparator[/b], and automatically extends the class named Object. The class can explicitly implement one, and only one interface, and cannot extend any class other than Object. Once again, the body of the new class is given by classBody.

I got answer from stackoverflow: [url]http://stackoverflow.com/questions/2978849/can-anybody-explain-the-working-of-following-code?rq=1[/url]

More detailed information you can refer to the original article: [url]http://www.developer.com/java/other/article.php/3300881/The-Essence-of-OOP-using-Java-Anonymous-Classes.htm[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值