Search code examples
javainheritancelate-binding

Why is Late Binding not working as i expected?


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.


Solution

  • That's what happens:

    obj is of declared type A, so only methods that are defined inside A are taken into account. And the only method that A has is int m(C c). Only this method and its overridden versions are going to be candidates for the binding. The methods declared in H are overloaded versions of this method, so they are not accessible when you make a method call inside main.