Search code examples
javaequalshashcode

Do I need to define equals and hashCode methods for inheritedClass and Base Class?


I am wondering if I should define equals and hashCode methods in the Product class as shown below?

public abstract class BaseEntity {

    // properties 

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        return super.equals(other);
    }
}
public class Product extends BaseEntity {

    // properties   

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        return super.equals(other);
    }
}

Solution

  • It is not useful to define equals and hashcode methods calling their super implementation. Not defining them at all will use the super implementation. In that case, they will use the Object implementation of hashcode and equals in either case (defining them calling super.equals or super.hashCode or not defining them at all).

    Remember to make your implementation of hashcode and equals if you need to use them. The method equals is used to check if two objects are logically the same object checking their content. Can be used directly, or not directly when you search for an object in a collection for example. The hashcode is used for the keys of an HashMap and values of an HashSet.

    Modern ide helps you creating a correct implementation of those methods depending on the fields that are useful in your context.