Harry
Harry

Reputation: 101

Why is dynamic binding necessary?

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?

Upvotes: 0

Views: 257

Answers (2)

GhostCat
GhostCat

Reputation: 140417

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!

Upvotes: 2

Piotr Praszmo
Piotr Praszmo

Reputation: 18320

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.

Upvotes: 1

Related Questions