选择具有多个选项的覆盖方法Java [英] Selecting overriding method java with multiple options
问题描述
要澄清-据我了解,以下方法都是Object.equals
的 override .他们是不是超载,而我对此理解不正确?
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?
我正在运行以下代码:
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");
}
}
AA类没有equals
方法
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:
- 由于类AA没有
equals
方法,我想在 编译时,编译器要从Object
运行equals
课. - 在运行时,编译器发现a2实际上是BB对象
因此具有
equals
方法,这些方法会覆盖来自Object
.
- 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
.
但是,我不清楚的是,如果定义了发送对象并且实际上是BB对象,为什么选择第二种方法(Object ob)
而不是第一种方法(BB ob)
.
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.
非常感谢您的反馈!
推荐答案
调用a.equals(b)
时,编译器将查看AA中的equals
方法.如果它在那里找到合适的,它将使用它.在这种情况下,AA没有称为等于"的方法.因此,它加强了继承链,并再次进行了查找.这次,它正在查看Object,并找到了Object.equals(Object)
.在运行时,它会找到最被覆盖的版本并将其调用.
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.
所以,如果它仍然只是在寻找一种称为等于"的方法,为什么它在运行时找不到更具体的版本equals(BB)
?
BB.equals(BB)
不是 被视为对Object.equals(Object)
的替代.它具有更具体的参数,并且不能处理普通对象.想象一下类型是名称的一部分:
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
编译器选择了equals_Object
方法,因此在运行时JVM将不会找到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.
这篇关于选择具有多个选项的覆盖方法Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!