问题
To clarify- To my understanding, the methods below are all override of Object.equals
. Are they overloading instead and I am not understanding this correctly?
I'm running this code:
public class AA
{
private int _val=0;
public AA()
{
_val=5;
}
}
public class BB extends AA
{
public BB()
{
....
}
public boolean equals(BB ob)
{
return false;
}
public boolean equals(Object ob)
{
return true;
}
public boolean equals(AA ob)
{
return true;
}
public static void main(String args[])
{
AA a2=new BB();
BB b1=new BB();
if((a2.equals(b1)))
System.out.println("hi");
}
}
Class AA does not have an equals
method
I'm trying to figure out with the second method is triggered and not the first one. My understanding is:
- Since class AA does not have an
equals
method, I suppose that at compile-time the compiler wants to run theequals
fromObject
class. - At run time the compiler finds out that a2 is actually a BB object
and therefore has
equals
methods that override the method fromObject
.
However, what is not clear to me is why the second method (Object ob)
is chosen instead of the first (BB ob)
, if the sent object is defined and actually is a BB object.
Would appreciate your feedback!
回答1:
When you call a.equals(b)
, the compiler looks at the equals
methods in AA. If it found an appropriate one there, it would use it. In this case, AA has no methods called 'equals'. So it steps up the inheritance chain, and looks again. This time, it is looking at Object, and it finds Object.equals(Object)
. At runtime, it finds the most overridden version and calls it.
So if it's still just looking for a method called 'equals', why doesn't it find the more specific version equals(BB)
at runtime?
BB.equals(BB)
is not considered an override of Object.equals(Object)
. It has a more specific parameter, and can't handle a plain Object. Imagine the types are part of the name:
- equals_Object
- equals_BB
The compiler picked the equals_Object
method, so at runtime the JVM will not find the equals_BB
method, because it isn't looking for it.
回答2:
Overloads are not chosen at runtime, they're chosen at compile time, when the compiler only knows that the object is an AA
. Only overrides are chosen at runtime, based on the actual runtime type of the object, but the overload selected at compile time is still used.
来源:https://stackoverflow.com/questions/35488361/selecting-overriding-method-java-with-multiple-options