namalfernandolk
namalfernandolk

Reputation: 9134

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...

Upvotes: 0

Views: 603

Answers (4)

Harshil
Harshil

Reputation: 243

  1. First In java every class, if not explitcitly mentioned, will have Object class as its parent class
  2. Java doesn't generate hashCode(), i.e. This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language. Most classes (especially if you are going to use it in any of the Collection API) specially in hashcontainer(HashSet and HashMap) should implement their own HashCode (and by contract their own equals method).

If you are interested to know when to implement hashCode() and equals() you can visit this site http://www.javabeat.net/2007/08/hashcode-and-equals-methods/

Upvotes: 0

Perception
Perception

Reputation: 80633

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.

Upvotes: 4

Isuru
Isuru

Reputation: 8193

hasCode() is form parent class object so if you haven't override it then parent method will be called. I think what you refer to as some integer is the hashCode generated at the super parent Object. Which suggest you haven't override the hashCode in Animal class.

In general if a super class method is not overridden then the immediate parent's method will be called.

Upvotes: 0

ejb_guy
ejb_guy

Reputation: 1125

In java every class, if not explitcitly mentioned, will have Object class as its parent class. As Object class defines the hashcode method this is avilable even if you don't define in your class. And yes, in java the default hashcode implemention is to return the memory location of the object. In a way this looks correct way as if two object are at same memory location than they must be same.

Upvotes: 0

Related Questions