How to use equals & hashcode from generic parent class in child classes?

50 Views Asked by At

I have many Entity classes in my project, and to avoid overriding the equals and hashCode methods in each one, I want to inherit them from a parent class where these methods are already implemented. Since the equals and hashCode methods of Entity classes should be based on the ID field, which is unique for each instance.

@NoArgsConstructor
@Getter
@Setter
public abstract class ParentEntity<ID> {

    private ID id;

   
    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        ParentEntity<?> that = (ParentEntity<?>) o;
        return Objects.equals(id, that.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class ChildEntity extends ParentEntity<Long> {

    private Long id;

    private String name;


}

But when i test it:

ChildEntity childEntity = new ChildEntity(4L, "Cheese");
ChildEntity childEntity1 = new ChildEntity(4L, "Bread");
ChildEntity childEntity2 = new ChildEntity(1L, "Milk");

System.out.println(childEntity.equals(childEntity1)); // output true
System.out.println(childEntity.equals(childEntity2)); // output true

In debug, I see that ParentEntity.id is null in every child entity instance but I don't understand why. Please help.

1

There are 1 best solutions below

0
Basil Bourque On

If you really need private Long id; in the subclass, name it something else other than the same name as another field in the superclass.

See Wikipedia: Variable shadowing