Possibly a dumb question, but I don’t want to screw this up. Let’s say I have two Java classes, Class1 and Class2, where Class2 extends Class1. I want to override Object.hashcode() using Guava for both classes. For the superclass, I’ve got
@Override
public int hashCode() {
return Objects.hashcode(mField1, mField2);
}
For Class2, what’s the right way to implement hashcode() that takes the members of Class1 into consideration? Is it like this?
@Override
public int hashcode() {
return Objects.hashcode(super.hashcode(), mField3, mField4);
}
That SEEMS right to me, but I’m looking for some validation. Joshua Bloch doesn’t address this situation in Effective Java, and the Guava docs don’t either.
Yes, that looks correct. It would be the same if you had
Objects.hashCode(f1, f2, f3, f4). If you look at the implementation, it’s something likeresult += 31 * result + hashcodeOfCurrentObject. Which means that your result will be 31 + the super hashcode, which is not exactly the same, but would not be a problem.