G
Gabriel Belingueres
Hi,
I wanted to know why the following example works the way it works:
class A {}
class B extends A {}
public class OverloadingTest {
public void method(A a) {
System.out.println("A.method");
}
public void method(B b) {
System.out.println("B.method");
}
public static void main(String[] args) {
OverloadingTest o = new OverloadingTest();
A p = new B();
o.method(p);
o.method(new B());
final A p2 = new B();
o.method(p2);
}
}
It prints:
A.method
B.method
A.method
Now, the question is:
Why the third method call is calling method(A) when the _final_
modifier is present in the local variable. I mean, since the local
variable is marked final, the compiler ALREADY KNOW, that for this
specific method call, we want to call the method with a B instance, not
an A instance. AFAIK, it is impossible to change the dynamic data type
of the p2 variable at runtime because it is marked final.
I can guess that this would introduce tricky rules to the language, but
I consider it as a nice to have feature for some future version of
Java.
Regards,
Gabriel
I wanted to know why the following example works the way it works:
class A {}
class B extends A {}
public class OverloadingTest {
public void method(A a) {
System.out.println("A.method");
}
public void method(B b) {
System.out.println("B.method");
}
public static void main(String[] args) {
OverloadingTest o = new OverloadingTest();
A p = new B();
o.method(p);
o.method(new B());
final A p2 = new B();
o.method(p2);
}
}
It prints:
A.method
B.method
A.method
Now, the question is:
Why the third method call is calling method(A) when the _final_
modifier is present in the local variable. I mean, since the local
variable is marked final, the compiler ALREADY KNOW, that for this
specific method call, we want to call the method with a B instance, not
an A instance. AFAIK, it is impossible to change the dynamic data type
of the p2 variable at runtime because it is marked final.
I can guess that this would introduce tricky rules to the language, but
I consider it as a nice to have feature for some future version of
Java.
Regards,
Gabriel