Why is dynamic binding necessary?

Harry

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?

Piotr Praszmo

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related