overriding equals method when dealing with inheritance

后端 未结 3 1785
北恋
北恋 2021-01-22 18:01

I have been reading about how best to override the equals method when dealing with subclasses and here I have found quite a few posts. They recommend different ways of implement

3条回答
  •  时光说笑
    2021-01-22 18:47

    If you have equals both in ConcreteClassOne and ConcreteClassTwo then the symmetry of equals is broken:

    Object c1 = new ConcreteClassOne(),
           c2 = new ConcreteClassTwo();
    System.out.println("c1=c2? " + c1.equals(c2)");
    System.out.println("c2=c1? " + c2.equals(c1)");
    

    Now, if you implement equals the usual way, this is going to print

    true
    false
    

    because in c2.equals you have instanceof ConcreteClassTwo, which fails for c1, but in the opposite case the analogous check passes.

提交回复
热议问题