overriding equals method when dealing with inheritance

后端 未结 3 1789
北恋
北恋 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:53

    The simplest approach is to extend equals() in both the concrete and the abstract classes.

    public class ConcreteClassTwo extends ConcreteClassOne {
        public boolean equals(Object other) {
            boolean rv = super.equals( other );
            if ( other instanceof ConcreteClassTwo ) {
               rv = rv && (this.trackingNo == ((ConcreteClassTwo) other).trackingNo);
            }
            return rv;
        }
    }
    

提交回复
热议问题