您的位置:首页 > 编程语言 > Java开发

匿名内部类实现Comparator接口,没有重写所有方法,为何不报错

2017-10-11 17:01 405 查看
//接口定义

interface Comparator{

   int compare(T o1,T o2);

   boolean equals(Object obj);

}

//对象类定义

public class User{

   private String name;

   private float  chinese;

   private float  math;

   private float  english;

   public Student(){

      super();

   }

   public Student(String name,float math,float english,float english){

      super();

      this.name=name;

      this.chinese=chinese;

      this.math=math;

      this.english=english;

   }

   public String toString(){

      return "Student [name=" + name + ", chinese=" + chinese + ", math=" + math + ", english=" + english +"]";

   }

}

//测试类

public class test {

public static void main(String[] args) {

// 创建带构造器的集合对象,使用匿名对象实现Comparator接口

TreeSet treeset=new TreeSet<>(new Comparator() {

//实现接口,重写了compare()方法,具体过程看不懂可以不看,对于理解无碍

public int compare(Student o1, Student o2) {

float num=o2.getChinese()+o2.getEnglish()+o2.getMath()-o1.getChinese()-o1.getEnglish()-o1.getMath();

num=num==0?o2.getName().compareTo(o1.getName()):num;

num=num==0?o2.getChinese()-o1.getChinese():num;

num=num==0?o2.getEnglish()-o1.getEnglish():num;

num=num==0?o2.getMath()-o1.getMath():num;

return (int)num;

}

});

treeset.add(new Student("zhangsan",30,40,86));

treeset.add(new Student("zhangsan1",32,60,80));

treeset.add(new Student("zhangsan2",30,45,30));

treeset.add(new Student("zhangsan3",30,10,80));

treeset.add(new Student("zhangsan4",60,43,80));

treeset.add(new Student("zhangsan1",32,60,80));

treeset.add(new Student("zhangsan1",32,61,79));

for(Student i:treeset)

System.out.println(i);

}

}

实现接口的方法:类实现:重写接口所有方法
                抽象子类:抽象子类继承接口
有朋友问:你的匿名对象实现接口怎么实现的?怎么还能直接new接口呢?
      答:匿名对象类实现接口使用了简化写法,在使用匿名内部类时会自动创建一个实现类,其实你不是new了那
            个接口,你是new了那个实现类!
      问:你的重写方法怎么没有全部重写接口的
            还记的上面那个临时创建的实现类吗,他全部重写了接口方法,只是方法体是空的。我虽然只重写了部
            分方法,但是其他方法已经被临时类重写了只不过是空方法而已!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐