Jizhou Zhang
Jizhou Zhang

Reputation: 87

How to write hashCode() for subClass

I have a question about hashCode. For example:

class A{
   String name;
   int age;

   @Override
   public int hashCode(){
       int hash = 0;
       hash = age;
       hash = 31*hash + name.hashCode();
   }
}
class B extends A{
}
class C extends A{
}    

My question is, if I instantiate one B object and one C object with the same name and age. Then the hashCode() for A and B are the same as well. Is it correct for hashCode()? if not, what should I do to modify my code?

Upvotes: 1

Views: 280

Answers (1)

Andreas
Andreas

Reputation: 159135

Sure, that's ok for hashCode() to do that.

Of course, if B or C adds any new fields (which would be common), then they should override hashCode(), call super.hashCode() and "extend" the value as well.

Also, as @bradimus hinted in a comment to question, when you override hashCode(), you should very likely also override equals().

Upvotes: 2

Related Questions