java_抽象类中的方法(似乎)没有被全部重写,是怎么回事?(举例:Comparator)

在这里插入图片描述
defualt方法(默认方法,可以不重写)
接口中的方法默认都是public

Comparator接口有两个抽象方法,一个是compare,另一个是equals方法,而写这个匿名内部类时,怎么没有重写equals方法呢,也没有报错。
为什么没有重写equals方法还不报错呢?后来想了想明白了,原因是所有类都继承Object类,而Object类里有实现equals方法,那么那个系统生成的实现类肯定也有这个equals方法啊,所以也就是重写了Comparator接口的equals方法
在jdk1.8下,匿名内部类的写法必须重写接口所有抽象方法,系统创建的实现类不会自动创建所有抽象方法。
现在把所有代码贴在下面,供大家测试
import java.util.*;
public class MyTest{
public static void main (String[] args){
List<Student> list = new ArrayList<Student>();
list.add(new Student(1,"aa"));
list.add(new Student(2,"bb"));
list.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getNum().compareTo(o2.getNum());
}
});
//匿名内部类写法,只重写test1,未重写test2,报错
method1(new MyInterface(){
@Override
public int test1(){
System.out.println("aaaaaa");
return 2;
}
});
}
public static void method1(MyInterface myInterface){
System.out.println("1231231321");
}
}
//自定义的接口,有两个抽象方法
interface MyInterface{
int test1();
void test2();
}
class Student{
private Integer num;
private String name;
Student(){}
Student(Integer num,String name){
this.num = num;
this.name = name;
}
public void setNum( Integer num){
this.num = num;
}
public Integer getNum(){
return this.num;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
posted @   xuchaoxin1375  阅读(5)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-04-07 python@内置的排序方法@sort@sorted@本文文件内容排序
点击右上角即可分享
微信分享提示