[英]method overriding with wrapper class
public class A
{
public void display(int i)
{
System.out.println("Inside A");
}
}
public class B extends A
{
public void display(Integer i)
{
System.out.println("Inside B");
}
}
public class starter
{
public static void main (String args[])
{
A a = new B();
a.display(5);
System.out.println("So now you know or not");
}
}
Output : Inside A 输出:A内部
Can somebody explain this output? 有人可以解释这个输出吗? Normally child method should be called. 通常应调用子方法。 How does Java behave here when we have a wrapper class and a primitive class using inheritance? 当我们有一个包装类和一个使用继承的原始类时,Java在这里的表现如何?
B#display
does not override A#display
, as the signature is different. B#display
不重写A#display
,作为签名是不同的。
The fact int
s can be boxed into Integer
s is not relevant here. 可以将int
装箱到Integer
的事实在这里无关紧要。
You could easily verify this by using the @Override
annotation. 您可以使用@Override
批注轻松地验证这一点。
Since the reference type of a
is A
, the method is resolved with the exact match for a literal integer (your given 5
argument), which is int
, therefore A#display
is invoked. 由于引用类型a
是A
,该方法与用于文字整数(您给出的精确匹配解决5
参数),这是int
,因此A#display
被调用。
You can still force the invocation of B#display
by using this idiom (not for production code): 您仍然可以使用以下惯用语来强制调用B#display
(不适用于生产代码):
((B)a).display(new Integer(5));
This casts your a
variable as a B
type, hence allowing visibility of B
's display
method within context. 这就引起你的a
变量作为B
型,因此允许的能见度B
的display
范围内的方法。
It also passes an Integer
rather than an int
, thus employing the signature of B
's display
method and allowing resolution to that method. 它还传递一个Integer
而不是一个int
,从而采用B
的display
方法的签名并允许对该方法进行解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.