Reputation: 33
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
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?
Upvotes: 1
Views: 1594
Reputation: 48404
B#display
does not override A#display
, as the signature is different.
The fact int
s can be boxed into Integer
s is not relevant here.
You could easily verify this by using the @Override
annotation.
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.
You can still force the invocation of B#display
by using this idiom (not for production code):
((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.
It also passes an Integer
rather than an int
, thus employing the signature of B
's display
method and allowing resolution to that method.
Upvotes: 4