I was wondering why this bit of Java yields 2, and not 3 :
public class Test {
private static class A {
int f(A a) {
return 1;
}
}
private static class B extends A {
int f(A a) {
return 2;
}
int f(B b) {
return 3;
}
}
public static void main(String[] astrArgs) {
A ab = new B();
B b = new B();
System.out.println( ab.f(b) );
}
}
I came across this in a test question, and couldn't get the logic behind it.
The compile-time type of ab
is just A
. Therefore, when the compiler sees this expression:
ab.f(b)
... it only considers method signatures declared on A
and its superclasses (just Object
in this case).
So, the compiler makes the decision to call the method with the signature f(A a)
.
Now at execution time, the VM chooses which implementation of that signature to execute based on the execution-time type of the target of the method call, which is B
.
B
overrides f(A a)
, so that overriding implementation is called - and returns 2.
Basically, overloading is determined at compile-time to work out what method signature to call based on the compile-time types of both the target of the call and the arguments, and overriding is determined at execution-time to work out the exact implementation to execute based on the execution-time type of the target object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With