The following code outputs 7:
public class GuessTheAnswer {
public static void main(String[] args) {
A obj = new H();
int jj;
jj = obj.m(new E());
System.out.println(jj);
}
}
class A {
public int m(C c) { return 8; }
}
class B extends A {
public int m(C c) { return 7; }
public int m(D c) { return 6; }
public int m(E c) { return 5; }
}
class C {}
class D extends C {}
class E extends D {}
interface I {
public int m(I obj);
}
class H extends B implements I{
public int m(I c) { return 12; }
public int m(D c) { return 13; }
public int m(E c) { return 14; }
}
I would have expected obj.m(new E()) to refer to the method m(E c) defined in class H, but for some reason i don't understand the method in class B is called instead.
That's what happens:
objis of declared typeA, so only methods that are defined insideAare taken into account. And the only method thatAhas isint m(C c). Only this method and its overridden versions are going to be candidates for the binding. The methods declared inHare overloaded versions of this method, so they are not accessible when you make a method call inside main.