问题描述
我正在尝试覆盖 pojo 的 toEquals 方法。但是我不确定如何比较父类属性,因为 super() 向我抛出了一个错误。
我正在尝试这样的事情:
@Override
public boolean equals(Object o) {
return super.equals(o.super()); // it mentions that the abstract parent class is not an inner class
}
我如何比较父抽象类字段的相等性?子属性有可能相似,但父属性总是不同的。
解决方法
@Override
public boolean equals(Object o) {
// compare local fields and return false if some of them are not equal
// if all fields are equal in the current class,then delegate work to the parent class.
// You should not care what it does,just call it and retrieve the result
return super.equals(o);
}
P.S.如果您使用像 IDEA 这样的 IDE,您可以自动生成 equals()
和 hashCode()
。作为另一种选择,您可以使用 Project Lombok
。