class A {
boolean f(A a) { return true; }
}
class B extends A {
boolean f(A a) { return false; } // override A.f(A)
boolean f(B b) { return true; } // overload A.f
}
void f() {
A a = new A();
A ab = new B();
B b = new B();
ab.f(a); ab.f(ab); ab.f(b); //(1) false, false, *false*
b.f(a); b.f(ab); b.f(b); //(2) false, false, true
}
Can you please explain the first line last false output, why it is not true?
can you please explain the first line last false output, why it is not true?
The compile-time type of ab
is A
, so the compiler - which is what performs overload resolution - determines that the only valid method signature is f(A a)
, so it calls that.
At execution time, that method signature is executed as B.f(A a)
because B
overrides it.
Always remember that the signature is chosen at compile time (overloading) but the implementation is chosen at execution time (overriding).