Senior
@Data public class ClassA { int a; } public class ClassB extends ClassA { int b; @Override public boolean equals(Object obj) { //implementation } } @Data public class ClassA { int a; } public class ClassB extends ClassA { int b; @Override public boolean equals(Object obj) { //implementation if (this == obj) return true; if (!(obj instanceof ClassB)) return false; if (!super.equals(obj)) return false; } }
sobes.tech AI
Answer from AI
In this example, the ClassA class is annotated with @Data (Lombok), which generates equals, hashCode, toString, and other methods based on the class fields.
ClassB inherits from ClassA and overrides the equals method. In the equals implementation, it is important to:
- Check that the comparison object is not null and belongs to the same class (or compatible).
- Call super.equals(obj) to compare the parent class fields.
- Compare the fields of ClassB itself.
An example of a correct equals implementation in ClassB:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof ClassB)) return false;
if (!super.equals(obj)) return false;
ClassB other = (ClassB) obj;
return b == other.b;
}
This ensures that the comparison considers both parent and child fields, avoiding errors and violations of the equals contract.
It is also important to override hashCode similarly to maintain consistency.