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 the classes don't match, they can't be equal**
//如果equals语义在子类中有所改变,就是子类的equals和父类的equals在概念上是不同的,那就用getClass来比较类
if (getClass() != otherObject.getClass()) return false;
//如果equals语义在子类中并没有发生改变,和父类是一样的,那么就用instanceof来比较类是否相同
if(!(otherObject instanceof ClassName)) return false;**
// now we know otherObject is a non-null Employee
Employee other = (Employee) otherObject;
// test whether the fields have identical values
return name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay);
}
为什么子类中的语义不同就用getClass而相同就用instanceof?我知道二者的区别,而且我觉得这个instanceof应该有点问题吧,就是比如a是父类,b是子类,且这时候子类的equals语义没有发生变化,那么a.equals(b)和b.equals(a)的结果就不一样了吧,因为子类instanceof父类是true,而父类instanceof子类就是false——这就不满足equals定义中的对称性。
大神求解