I am doing K&B mock exam today, and got stuck with this question, please let me know what you think...
Here is the caller:
Place //1 returns true which confuses me.
Since the equals() method in the code takes "Nearly" as a parameter rather than Object, so it cannot be considered as an valid overriden. So the comparison actually call the default equals(Object o) method to determine whether n1 equals n2. However, as I remember, default equals(Object o) works exactly as ==. So n1 == n2 return false ==> n1.equals(n2) should return false.
What is wrong of my understanding?
It doesn't override the equals method.Its just called the instance method of the class Nearly.The method returns true.
Without hashcode method also it returns true.Check that by comment the hashcode method.
So the comparison actually call the default equals(Object o) method to determine whether n1 equals n2. However, as I remember, default equals(Object o) works exactly as ==. So n1 == n2 return false ==> n1.equals(n2) should return false.
applies to the comparison that is done with == operator.
So, if you do a n1 == n2 check then your understanding above applies and it should return false.
But since you are doing n1.equals(n2), it is a direct method call to the equals() in your Nearly class. The equals() here is an overloaded method.
equals in Nearly is overloaded version of equals method in object. so now Nearly class has two method with same name and different argument. you are calling the method by passing Nearly object. so equals(Nearly) gets called as it matches the exact argument.
try passing an object argument. i.e, equals("string object");
Joined: Jul 02, 2011
Hi Shuba, Muneeswaran, Lokesh, Seetharaman,
Thank you for the help!
Yes, public boolean equals(Nearly n) is not an overriden method of equals(Object o), but a regular method.