你这个问题提的非常好,我专门写了个程序验证了下:
父类是这样的:package coms;
public class fu implements Comparable<fu> {
String name;
fu(String name){
this.name = name;
}
public int compareTo(fu o) {
// TODO Auto-generated method stub
System.out.println("fu compare "+this.name+"..."+o.name);
return this.name.compareTo(o.name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
第一种情况的子类:package coms;
public class zi extends fu{
int age;
zi(String name,int age) {
super(name);
this.age = age;
// TODO Auto-generated constructor stub
}
/* public int compareTo(fu o) {
// TODO Auto-generated method stub
System.out.println("zi compare "+this.name+"..."+o.name);
return this.name.compareTo(o.name);
// return new Integer(this.age).compareTo(new Integer(z.age));
}*/
public int compareTo(zi1 o) {
// TODO Auto-generated method stub
System.out.println("zi compare "+this.name+"..."+o.name);
// return this.name.compareTo(o.name);
return new Integer(this.age).compareTo(new Integer(o.age));
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
第二种情况的子类:
package coms;
public class zi1 extends fu {
int age;
zi1(String name,int age) {
super(name);
this.age = age;
// TODO Auto-generated constructor stub
}
public int compareTo(zi1 o) {
// TODO Auto-generated method stub
System.out.println("zi compare "+this.name+"..."+o.name);
// return this.name.compareTo(o.name);
return new Integer(this.age).compareTo(new Integer(o.age));
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
测试类:
package coms;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeSet;
import com.TreeSet.Student;
public class test2 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Collection<fu> c = new TreeSet<fu>();
c.add(new fu("aa"));
c.add(new fu("bb"));
c.add(new zi("aba",10));
c.add(new zi("ccb",20));
Iterator<fu> it=c.iterator();
while(it.hasNext())
{
fu f=it.next(); //向下转型
System.out.println(f.getName());
}
}
}
得出结论:
子类和父类比较的时候,
如果子类可以实现和父类的“交叉”比较,则调用子类的比较方法。
如果子类不可以实现和父类的“交叉”比较,就直接调用父类的比较,这时候因为多态的存在,父类是肯定可以实现和子类的比较出结果的。 |