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

Time:04-16

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);
    }
}

CodePudding user response:

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.

CodePudding user response:

@federico To give you correct answer some details,

equals and hashCode is method from Object class which is parent of all class. equals and hashCode use to define that particular class object is different than other object from same class and find hash value.(which called by other Java collection classes if you using it to store these objects). Generally we create child class if you have different behavior or fields on top of Parent class. So, child class should have more fields, better to implement equals and hashCode in child class.

There will be no error if you don't implement equals and hashCode in child class.

CodePudding user response:

Let's assume that a product's hashcode is derived from properties unique to a product. We'll also assume that 2 objects are equal if they have the same hashcode. In this scenario:

public abstract class BaseEntity {

  public abstract int hashCode();

  @Override
  public boolean equals(Object object) {
      return this.hashCode() == object.hashCode();
  }
}

public class Product extends BaseEntity {

  @Override
  public int hashCode() {
    return someValueDerivedFromProductProperties;
  }
}

This means that all classes that extend the BaseEntity must define an implementation of hashCode and are considered equal if the returned hashcode values are equal

  • Related