Autoboxing and overloading
public class JavaMain {
public static void main(String[] args) {
JavaA a = new JavaB();
a.m1(5);
a.m1(new Integer(5));
}
}
class JavaA{
public void m1(Integer i){
System.out.println(2);
}
}
class JavaB extends JavaA{
public void m1(int i){
System.out.println(1);
}
}
Output: 2 2
As I understand it, the output will be "1 2".
1) When I call method a.m1 (5) from main method. According to the concept of overloading, a JavaB method class must be executed. but it won't.
Please help me understand the concept of overloading + autoboxing.
source to share
JavaA a = new JavaB();
a.m1(5);
a.m1(new Integer(5));
- static type
a
isJavaA
-
JavaA
declares only one methodm1
- this method takes
Integer
- it is applicable to both calls
Method signature is allowed at compile time. The compiler only considers signatures declared in the static type of the target expression ( JavaA
in your case).
source to share
The decision to choose an overloaded method is made at compile time based on the methods available for the compile-time type. Your variable a
is of a compile type JavaA
and JavaA
has only one method m1
, so there is only one method that you can choose.
m1
class JavaB
cannot be a candidate even though the runtime type a
is JavaB
.
So you get the output
2 2
source to share
You just call JavaB.m1
twice, since your object is only ever an instance JavaB
. Here's an example that will do what you want.
public static void main(String[] args) {
JavaA a = new JavaA();
JavaA b = new JavaB();
a.m1(5);
b.m1(new Integer(5));
//output will be
//2
//1
}
Both objects can act as JavaA type objects due to polymorphism, but the instance can be of any subclass JavaA
. An oversized implementation of m1 will be called when the actual type matters JavaB
. The initial implementation will be called when the type is instance JavaA
.
source to share
In Java int
and Integer
are not the same types when it comes to overrides. This means that the m1
from method JavaB
does not override m1
from JavaA
. You can check it with annotation @Override
- it just doesn't work here. At compile time, these two methods are overloaded rather than overridden, so when in your method main()
you want to handle a
like the type JavaA
here: JavaA a = new JavaB();
then there is no choice but to call from method JavaA
- polymorphism is useless here.
source to share