为什么抽象类可以强制覆盖具体方法? [英] Why can an abstract class force a concrete method to be overridden?

查看:105
本文介绍了为什么抽象类可以强制覆盖具体方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个库,其中的抽象类使用抽象方法覆盖从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被广泛用于定位对象,则使Aequals方法抽象成为强制您在任何情况下提供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(因为equalshashCode的协定要求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()).

这篇关于为什么抽象类可以强制覆盖具体方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆