I use a library where an abstract class overrides a concrete method inherited from Object with an abstract method:
public abstract class A {
@Override
public abstract boolean equals(Object obj);
}
To extend this class, I have to implement the equals method:
public class B extends A {
@Override
public boolean equals(Object obj) {
return obj != null && obj.getClass() == B.class;
}
}
Why can an abstract method (A::equals) override a concrete method (Object::equals)? I don't see the goal of this.
In this specific example it makes perfect sense. If sub-classes of A are meant to be used in Collections, where
equalsis widely used to locate objects, makingA'sequalsmethod abstract forces you to give non-default implementation ofequalsin any sub-classes ofA(instead of using the default implementation of the Object class which only compares instance references).Of course, your suggested implementation of
equalsin B makes little sense. You should be comparing the properties of the 2 B instances to determine if they are equal.This is a more suitable implementation :
In addition, remember to override
hashCodewhenever you overrideequals(since the contract ofequalsandhashCoderequires that ifa.equals(b) == truethena.hashCode() == b.hashCode()).