/** * * @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方法 } }