This question already has answers here:
Any reason to prefer getClass() over instanceof when generating .equals()?
                                
                                    (11个答案)
                                
                        
                                6年前关闭。
            
                    
我已经看到了Java equals()方法的许多实现,它们遵循以下几行:

public boolean equals(Object other){
    if (this == other)
        return true;

    //this if code
    if (!(other intanceof MyClass))
        return false;
    //ends here

    otherMyClass = (MyClass)other;
    //check all the attribute of this and otherMyClass and return true or false
    //accordingly
}


从o1.equals(o2)(带有MyClass的o1对象和MyClasss的子类的o2对象)返回true的意义上说,代码是否存在问题?在大多数情况下,这不是预期的行为。

other.getClass() != this.getClass()是不是更好的比较,而不是上面的粗体?

最佳答案

o.getClass() != getClass())违反了Liskov替代原则。

引用伟人:


  Liskov替代原理说,
  一个类型还应该保留其子类型,以便任何编写的方法
  因为该类型应该在其子类型上同样有效。


本书Effective Java对此主题有更多详细信息。

关于java - Java equals方法的错误实现模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21408569/

10-12 00:29
查看更多