I cannot figure out why do we need dynamic binding (late binding). Let's say we have Class A and Class B and lets say that class B extends class A, now we can write stuff like "A var= new B();" Now let's say that both classes contain method with the same signature, for example method "cry()" now I can write something like "var.cry()", now based solely on the Type of "var" compiler cannot bind the right Method to the Instance "var" during compilation, but the compiler has to check if the following statement is legal "A var= new B();" now since it has to check if that statement is legal it has to know that "var" will be referencing an instance of class B, now if it knows this, compiler has to be able to bind the right method at compile time?
Asked
Active
Viewed 121 times
0
-
1Compiler checks that when you assign it’s valid and when you call a method it’s valid. There is no way, in the general case, to remove the split between those two checks. Hence late binding. – Boris the Spider Oct 19 '19 at 19:13
2 Answers
2
Just assume you have
void foo(A someA) {
someA.cry()
}
What now? Nobody can tell you upfront whether that incoming A is an A or a B!
In other words, there are plenty of ways to not reliably know the exact nature of some object at compile time!

GhostCat
- 137,827
- 25
- 176
- 248
1
This is not possible in general case. For example here:
A var;
if(x) {
var = new A();
} else {
var = new B();
}
var.cry();
in last line it's unknown, if var is referencing an instance of A or B.

Piotr Praszmo
- 17,928
- 1
- 57
- 65