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
Although Bozho's suggestion is valid, I prefer this approach:
@Override
public int hashCode() {
return Objects.hashcode(mField1, getParentField1(), getParentField2());
}
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 like result += 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.
Effective Java does address this situation...by saying that you shouldn't do it. Item 8:
It turns out that this is a fundamental problem of equivalence relations in object-oriented languages. There is no way to extend an instantiable class and add a value component while preserving the equals contract, unless you are willing to forgo the benefits of object-oriented abstraction.
(Corollary: the same reasoning applies to hashCode().)