Search code examples
javahashcode

hashCode implementation in java


I have a class Dog extends Animal.

Then I call the hashCode() method as follows.

Animal animal  = new Dog(200);
System.out.println(animal.hashCode());

Here,
If I've overridden the hashCode() in the Dog class it will be returned. Else if I've overridden the hashCode() in the Dog class it will be returned. Else some integer returned.

I wanna know...

  • Why does it call the hashCode() of the super class when it is not overriden in the Dog class? How and what the 'some integer' generated

  • When the hashCode is not generated in anywhere. (I have heard that it is the memory location of the object but not sure.)


Solution

  • This is referred to as method overriding. The hashCode method is defined in java.lang.Object, basically the top of the object heirarchy, so it is always available to any Object defined in Java. If the method is not overriden in your specific subclass or one of its parents, the default behavior defined in java.lang.Object will be invoked.

    You typically should not worry about what the internal implementation of a hash code is in a parent object, but the default implementation does use the internal address of the Object. Note that this internal address is precisely that - an interpreted address that the JVM uses internally, that should not be depended upon by an application to be anything particularly meaningful.

    You can read more about how overriding works in the Java Language Specification - Section 8.4.8.