3 回答

TA贡献1895条经验 获得超7个赞
有关的澄清obj.getClass() != getClass()。
这句话是equals()继承不友好的结果。该JLS(Java语言规范)规定,如果A.equals(B) == true那么B.equals(A)也必须返回true。如果省略该语句,则继承覆盖equals()(并更改其行为)的类将破坏此规范。
请考虑以下示例,省略语句时会发生什么:
class A {
int field1;
A(int field1) {
this.field1 = field1;
}
public boolean equals(Object other) {
return (other != null && other instanceof A && ((A) other).field1 == field1);
}
}
class B extends A {
int field2;
B(int field1, int field2) {
super(field1);
this.field2 = field2;
}
public boolean equals(Object other) {
return (other != null && other instanceof B && ((B)other).field2 == field2 && super.equals(other));
}
}
这样做new A(1).equals(new A(1))同时,new B(1,1).equals(new B(1,1))导致发出真实的,因为它应该。
这看起来非常好,但看看如果我们尝试使用这两个类会发生什么:
A a = new A(1);
B b = new B(1,1);
a.equals(b) == true;
b.equals(a) == false;
显然,这是错误的。
如果要确保对称条件。a = b如果b = a且Liskov替换原则super.equals(other)不仅在B实例的情况下调用,而且A例如在之后检查:
if (other instanceof B )
return (other != null && ((B)other).field2 == field2 && super.equals(other));
if (other instanceof A) return super.equals(other);
else return false;
哪个会输出:
a.equals(b) == true;
b.equals(a) == true;
在哪里,如果a不是引用B,那么它可能是一个类的引用A(因为你扩展它),在这种情况下你super.equals() 也可以调用。
添加回答
举报