在Java中使用继承等同有什么问题?

cpx*_*cpx 7 java inheritance equals

在我正在阅读的" 核心Java卷1 " 一书中,它说平等不应该与继承一起使用.所以,我有以下示例,似乎有一些错误:

public class Main {

    public static void main(String[] args) {

        C c = new C("Test", 10);
        D d = new D("Test", 10);

        if (c.equals(d))
            System.out.println("Equal");
        else
            System.out.println("Unequal");

        if (d.equals(c))
            System.out.println("Equal");
        else
            System.out.println("Unequal");
    }
}


class C
{
    C(String cstr, int cnum) {
        str = cstr;
        num = cnum;
    }

    @Override
    public boolean equals(Object otherObject) {

        // A quick test to see if the objects are identical.
        if (this == otherObject) {
            return true;
        }

        // Must return false if the explicit parameter is null
        if (otherObject == null)
        {
            return false;
        }

        if (!(otherObject instanceof C))
            return false;

        // Now we know otherObject is a non-null Employee
        C other = (C) otherObject;

        // Test whether the fields have identical values
        return str.equals(other.str) && num == other.num;
    }

    private String str;
    private int num;
}

class D extends C {

    D(String cstr, int cnum) {
        super(cstr, cnum);
    }
}
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/PhFBwG

对于两个对称比较,它返回"等于",这可能是不应该的.它是否缺少equals派生类'D'中的另一种方法?如果是这样,那么上面的示例代码可能会出现什么问题,如果我根本不使用其他代码那么equals

T.J*_*der 4

该代码有效,因为正如您所说,D不会覆盖equals. 我预计这本书的要点是D 应该重写equals(并且它们都应该重写hashCode),因为D实例不应该等于C实例,因为它们是不同的(尽管相关)类型。

请记住,合同equals关键方面之一是对称性。对于和的任何非null值,如果为真,则必须为真(反之亦然)。虽然在您当前的代码中确实如此,但可能不应该如此,因为和是不同的类型。如果一个实例确实相当于一个实例,为什么还要有?cdc.equals(d)d.equals(c)DCDCD