重写的equals方法不会被调用

Ang*_*ver 1 java oop inheritance overriding

考虑以下类:

public class Base {

    protected int i = 0;

    public Base(int i) {
        this.i = i;
    }

    public Base(Base b) {
        this(b.i);
    }

    public Base foo() {
        return new Base(this);
    }
}


public class Sub extends Base {

    public Sub(int i) {
        super(i);
    }

    public Sub(Sub s) {
        super(s.i * 2);
    }

    public Base foo() {
        return this;
    }

    @Override
    public boolean equals(Object o) {
        return ((Sub) o).i == this.i;
    }

    public static void main(String[] args) {
        Base b1 = new Base(1);
        Base b2 = b1;
        Base b3 = b2.foo();
        Base b4 = new Sub(1);
        Base b5 = b4.foo();

        System.out.println(b1.equals(b3));
    }
}
Run Code Online (Sandbox Code Playgroud)

打印结果是false.我注意到被覆盖的方法equals(Object o)永远不会被抓住,我当然怀疑这是问题(否则它会打印true).

这是为什么?

Jon*_*eet 10

你正在调用b1.equals(b3)- b1是一个实例Base,而不是Sub,所以你无法调用你的重写方法.

哎呀,甚至b3.equals(b1)不会打电话给任何东西Sub,因为它也是b3一个例子Base.

只有b4并且b5引用实例Sub,因此只会 b4.equals(...)b5.equals(...)将调用您的重写方法.另外,因为你无条件地在你的equals方法中进行投射,b4.equals(b1)(例如)将抛出异常而不是返回false.