派生等于基数不违反合同吗?
我的理解正确吗?
Base objBase = new Base();
Derived objDer = new Derived();
System.out.println(objBase.equals(objDer)); // shall be always false?
System.out.println(objDer.equals(objBase)); // can be true: derived is a base!
P.S。我想到了这一点,因为我感到奇怪的是,Apache Commons EqualsBuilder sample code仅使用一行代码就不使用instanceof检查null和兼容类型:
public boolean equals(Object obj) {
if (obj == null) { return false; } // why not use instanceof here... ?
if (obj == this) { return true; }
if (obj.getClass() != getClass()) { // ...and here... ?
return false;
}
MyClass rhs = (MyClass) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(field1, rhs.field1)
.append(field2, rhs.field2)
.append(field3, rhs.field3)
.isEquals();
}