Java toEquals() 覆盖以包含父类属性

问题描述

我正在尝试覆盖 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...