如果同时放入了父类和子类的实例对象,那比较时使用的是父类的compareTo方法,还是使用的子类的compareTo方法,还是抛异常!
放入的是父类实例用的就是父类实例的compareTo
放入的是子类实例用的就是子类实例的compareTo
这就是java里多态的具体表现形式。
/**
* 如果同时放入了父类和子类的实例对象,那比较时使用的是父类的compareTo方法,还是使用的子类的compareTo方法,还是抛异常?
* 以上问题:如果想让TreeSet同时可接收父类和其子类,TreeSet需要声明为父类新, TreeSet<父类> treeSet = new TreeSet<>();
* 比较时:子类未重写 compareTo 方法时调用父类的
* 子类重写了 compareTo 时,调用子类自身的
* 可以同时正常存放 父类、子类对象
*/
public class Demo {
/**
* 父类(动物)实现了Comparable接口
*/
static class Animal implements Comparable<Animal>
{
int weight;
String name;
public Animal(int weight, String name)
{
super();
this.weight = weight;
this.name = name;
}
@Override
public int compareTo(Animal o)
{
System.out.println( name + " 调用了父类的compareTo");
return this.weight-o.weight;
}
}
/**
* 马继承了Animal,但未重写compareTo方法
*/
static class Horse extends Animal{
public Horse(int weight, String name) {
super(weight, name);
}
}
/**
* 牛继承了Animal,并重写了compareTo方法
*/
static class Cow extends Animal {
public Cow(int weight, String name) {
super(weight, name);
}
@Override
public int compareTo(Animal o)
{
System.out.println( name + " 调用了自己重写的compareTo方法");
return this.weight-o.weight;
}
}
public static void main(String[] args) {
//定义Animal类型的TreeSet对象,对象可接收父类以及相关子类对象
TreeSet<Animal> animalTreeSet = new TreeSet<>();
//马类对象,由于Horse未重写compareTo方法,在TreeSet排序时将调用其父类的compareTo
Horse horse = new Horse(2000,"马1");
Horse horse1 = new Horse(3000,"马2");
Horse horse2 = new Horse(4000,"马3");
//牛类对象,由于Cow重写compareTo方法,在TreeSet排序时将调用其自身重写的compareTo
Cow cow = new Cow(4010,"牛1");
Cow cow1 = new Cow(4020,"牛2");
Cow cow2 = new Cow(4300,"牛3");
//父类,调用自身compareTo
Animal animal = new Animal(3010,"动物1");
Animal animal1 = new Animal(3020,"动物2");
Animal animal2 = new Animal(3030,"动物3");
animalTreeSet.add(horse);
animalTreeSet.add(horse1);
animalTreeSet.add(horse2);
animalTreeSet.add(cow);
animalTreeSet.add(cow1);
animalTreeSet.add(cow2);
animalTreeSet.add(animal);
animalTreeSet.add(animal1);
animalTreeSet.add(animal2);
animalTreeSet.forEach(e-> System.out.println("name:" + e.name + " 重量:" + e.weight));
}
}
如有帮助,请采纳!!!!