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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
  • 2022-12-23
  • 2018-04-18
  • 2022-12-23
猜你喜欢
  • 2021-07-01
  • 2021-11-19
  • 2022-12-23
  • 2021-09-06
  • 2022-12-23
  • 2022-12-23
  • 2021-12-20
相关资源
相似解决方案