问题描述
我使用一个库,其中的抽象类使用抽象方法覆盖从Object
继承的具体方法:
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);
}
要扩展此类,我必须实现equals
方法:
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;
}
}
为什么抽象方法(A::equals
)会覆盖具体方法(Object::equals
)?我看不到这个目标.
Why can an abstract method (A::equals
) override a concrete method (Object::equals
)? I don't see the goal of this.
推荐答案
在此特定示例中,这很有意义.如果打算在集合中使用A的子类,而equals
被广泛用于定位对象,则使A
的equals
方法抽象成为强制您在任何情况下提供equals
的非默认实现A
的子类(而不是使用仅比较实例引用的Object类的默认实现).
In this specific example it makes perfect sense. If sub-classes of A are meant to be used in Collections, where equals
is widely used to locate objects, making A
's equals
method abstract forces you to give non-default implementation of equals
in any sub-classes of A
(instead of using the default implementation of the Object class which only compares instance references).
当然,您建议的B中equals
实施建议毫无意义.您应该比较2个B实例的属性,以确定它们是否相等.
Of course, your suggested implementation of equals
in 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 :
public class B extends A {
@Override
public boolean equals(Object obj) {
if (!(obj instanceof B))
return false;
B other = (B) obj;
return this.someProperty.equals(other.someProperty) && this.secondProperty.equals(other.secondProperty);
}
}
此外,切记每次覆盖equals
时都要覆盖hashCode
(因为equals
和hashCode
的协定要求a.equals(b) == true
然后a.hashCode() == b.hashCode()
).
In addition, remember to override hashCode
whenever you override equals
(since the contract of equals
and hashCode
requires that if a.equals(b) == true
then a.hashCode() == b.hashCode()
).
这篇关于为什么抽象类可以强制覆盖具体方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!