方案1
class B
{
public void m1(int x)
{
System.out.println("Super class");
}
}
class A extends B
{
public void m1(int... x)
{
System.out.println("Sub class");
}
}
class test1
{
public static void main(String args[])
{
B b1 = new B();
b1.m1(10);
A a = new A();
a.m1(10);
B b2 = new A();
b2.m1(10);
}
}
输出 :
- 超一流
- 超类(无法理解为什么是超类?!)
- 超类(无法理解为什么是超类?!)
方案2:
class B
{
public void m1(int... x)
{
System.out.println("Super class");
}
}
class A extends B
{
public void m1(int x)
{
System.out.println("Sub class");
}
}
class test1
{
public static void main(String args[])
{
B b1 = new B();
b1.m1(10);
A a = new A();
a.m1(10);
B b2 = new A();
b2.m1(10);
}
}
Output:
- 超一流
- 子类(无法理解为什么要子类?!)
- 超类(无法理解为什么是超类?!)
大家好,有人可以解释一下输出中是否存在覆盖/重载吗?
没有压倒性的在这个问题中,只是超载. 压倒一切将涉及A
定义一个方法相同的签名作为相应的方法B
(例如,如果他们都有m1(int)
)。在这两个示例中您都没有这样做,因为参数类型不同(int
vs. int...
).
方法签名解析的机制(选择要使用的重载)包含在JLS §15.12.2:编译时步骤 2:确定方法签名。 Java编译器会选择最具体的方法它可以在定义的接口上根据参考文献的类型(在您的情况下,变量的类型)如果有任何歧义。
请注意,重要的是引用的类型,而不是引用所引用的对象的类型。引用的类型(您的情况下的变量)定义了界面你必须到对象。 (这是一般 OOP 意义上的“接口”,而不是以其命名的 Java 特定事物。)编译器只能从该接口中可用的方法中进行选择。
有了这样的背景,原因就很明显了:
方案一:
-
超一流- 因为
b1
属于类型B
, and B
只有m1(int)
, and m1(10)
匹配它。
-
超一流- 因为
a
属于类型A
; A
两者都有m1(int)
(from B
)以及它自己的m1(int...)
;前者是更具体, so B
's m1(int)
用来。
-
超一流- 因为
b2
属于类型B
and B
只有m1(int)
.
方案2:
-
超一流- 因为
b1
属于类型B
, and B
只有m1(int...)
, not m1(int)
.
-
子类- 因为
a
属于类型A
, and A
两者都有m1(int...)
(from B
)以及它自己的m1(int)
;后者更具体,所以A
's m1(int)
用来。
-
超一流- 因为
b2
属于类型B
, and B
只有m1(int...)
, not m1(int)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)