Reputation: 9134
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.)
Upvotes: 0
Views: 603
Reputation: 243
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
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
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
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