/** * * @author ocq */class Parent implements Comparable { private int age = 0; public Parent(int age) { this.age = age; } public int compareTo(Object o) { System.out.println("method of 父类"); Parent o1 = (Parent) o; return age > o1.age ? 1 : age < o1.age ? -1 : 0; }}class Child extends Parent{ public Child() { super(3); } public int compareTo(Object o) { System.out.println("method of 子"); return 1; }}public class ComparableTest { /** * @param args */ public static void main(String[] args) { TreeSet set = new TreeSet(); set.add(new Parent(3)); set.add(new Child()); set.add(new Child()); set.add(new Parent(4)); System.out.println(set.size());// 测试结果:// 如果子类和父类都复写了compareTo方法那么各自调用自己的compareTo方法// 如果子类没有复写compareTo方法,那么调用的都是父类的compareTo方法 }}