Search code examples
javahashjava-7hashcode

hashCode(): Objects.hash() And Base Class?


Let's say I have two classes

class A {

  private String aStr;

  @Override
  public int hashCode() {
    return Objects.hash(aStr);
  }

}

and

class B extends A {

  private String bStr;

  @Override
  public int hashCode() {
    return Objects.hash(bStr);
  }

}

As the fields of class A are still fields in B that need to be hashed, how do I properly include the hash code of the fields in A in B.hashCode()? Any of these?

Objects.hash(bStr) + super.hashCode();
// these generate a StackOverflowError:
Objects.hash(bStr, (A) this);
Objects.hash(bStr, A.class.cast(this));

Solution

  • I'd probably use

    Objects.hash(bStr, super.hashCode())
    

    You definitely want to combine the state you know about with the superclass implementation of hashCode(), so any solution would want to use bStr and super.hashCode()... your original idea of addition would work too, of course - it's just a different way of combining the results.