0

I have overridden equals() and hashCode() in my ClassA.

ClassA {
   //overridden equals() and hashCode()
}

ClassB extends ClassA.

ClassB extends ClassA{
   //....
} 

Now if my code calls classBInstance.equals(classBInstanceTwo), does this call ClassA's equals method?

Thanks!

4

2 回答 2

5

Yes it does. But this can easily break the equals/hashcode contract (javadoc). For Example:

a equals b == b equals a

a equals b == a equals c == b equals c

So in the class B you shouldn't add new fields, which you want to use in equals/hashcode.

A possible solution is to use Class A as a field in Class B.

In the book Effective Java of Joshua Bloch there is a nice article about the problems with it.

于 2012-04-09T11:31:06.087 回答
1

Yes. All methods in Java are virtual by default.

于 2012-04-09T11:25:14.323 回答