1

I thought that the output of the following code would have been ABB, instead it is AAB, why does java do static binding here?

public class A {}

public class B extends A {}

public class C {

void f(A x) {
    System.out.println("A");
}

void f(B x) {
    System.out.println("B");
}

public static void main(String[] args) {
    C c = new C();
    A a1 = new A();
    A a2 = new B();
    B a3 = new B();
    c.f(a1);
    c.f(a2);
    c.f(a3);
}

}

Sorry for the mistakes I might have done, it's my first question.

Riccardo
  • 111
  • 3
  • You are declaring your `a2` object as `A`. So you get AAB as expected. Change `A a2 = new B();` to `B a2 = new B();` and you'll get ABB if I don't mistake. – Lutzi Apr 23 '18 at 16:10
  • https://stackoverflow.com/a/34866440 – Pshemo Apr 23 '18 at 16:14
  • When I call `c.f(a2)`, `a2` is a `B`! If the compiler would not decide before running the code, the output would have been ABB, because the run-time type of `a2` is `B`, or not? – Riccardo Apr 23 '18 at 16:21
  • "When I call c.f(a2), a2 is a B" no it *holds* instance of `B` but type of `a2` variable *is* `A`. That is what compiler knows for sure (it doesn't look at actual held value, because at runtime it can hold anything) and based on that (at compilation time) chooses signature `f(A x)`. – Pshemo Apr 23 '18 at 16:25
  • Thanks a lot @Pshermo for your answers...I still have a doubt, why the signature is decided by the compiler and not at run-time? I thought that Java was different from C by making all possible decisions at run-time. – Riccardo Apr 23 '18 at 16:32
  • I am not sure what you mean. Static binding happens at compilation time so compiler can't really know what will be proper value here. Lets say that we have `A a = surprise();` where `surprise()` can return instance of `A` or `B`. But compiler must chose *signature* of method which should be executed so it can choose only based on *variable type*. At runtime Java is searching for *body* of method which signature was selected at compilation time. So if we have `A a = new B(); a.foo()` and `B` overrides `foo()` then JVM at runtime will start looking for `foo` implementation (body) from `B` class. – Pshemo Apr 23 '18 at 16:50
  • Thank you very much Pshermo, it's clearer now! – Riccardo Apr 23 '18 at 18:06

0 Answers0