Dynamic and Static Binding

I enjoy understanding not only programming language syntactics, but also the way the programming language works internally.

Let’s say I have some Java classes and method such as below:

class Animal {
public void walk() {
// Do something.
}
}

class Dog extends Animal {
public void walk() {
// Do something slightly different.
}
}

void action(Animal a) {
a.walk();
}

Dog d = new Dog();

Ok, now let’s do something with d:

action(d);

Did you see the amazing behind the scenes process going on there? It isn’t too obvious and I will spell it out for you below:

The Dog class as its own walk method which (more than likely) is different from the Animal class’ walk method. The action method accepts the Animal type, so it does not know for sure if it was an upcasted Dog specifically or just an Animal that was passed to it. However when you run the application, the correct walk is achieved! Why does this happen?

The reason this happens is because of Dynamic Binding. Dynamic Binding occurs when the compiler can’t resolve the calls and this results in the bindings happening during runtime. Yes you guessed it, binding is to do with inheritence. The method call binds are actually based off the actual object type and not the declared type.

Static Binding is to do with bindings that can be determined during compilation, for example member variables.

One comment

  1. Oscar Mayer Coupons says:

    Can I just say how nice it is to find someone who actually knows what they’re speaking about on the web. Lots of people need to read this post and understand this. I’m surprised that this website is not more popualar.

Leave a Reply

Your email address will not be published.

*