Reputation: 1711
Runtime binding
happens at runtime because compiler cannot decide which function to execute at compile time
but why compiler cannot decide at compile time ?
class Animal{
void eat(){ System.out.println("animal is eating..."); }
}
class Dog extends Animal{
@Override
void eat(){ System.out.println("dog is eating..."); }
}
class Cat extends Animal{
@Override
void eat(){ System.out.println("cat is eating..."); }
}
class Example {
public static void main(String args[]){
Animal a = new Dog();
a.eat();
Animal b = new Cat();
b.eat();
}
}
Output:
dog is eating...
cat is eating...
These question does not answer my Question
Upvotes: 1
Views: 592
Reputation: 718698
Runtime binding happens at runtime because compiler cannot decide which function to execute at compile time ...
This is incorrect, at least in the case of Java.
Runtime binding in Java is not a result of short-comings of the Java compiler. It is by design.
Runtime binding in Java has many advantages:
It means that you don't have to compile and link all of your code at the same time whenever you make a change to the code base. This makes development faster.
It means that you don't have to compile and link against a specific version of the Java runtime. In short, it enables "write once, run everywhere"1.
It means that your application can make used of plugins provided by 3rd parties.
Indeed, the application can can load different versions of things to deal with platform differences and so on.
And the nice thing is that Java does this while maintaining runtime type-safety.
... but why compiler cannot decide at compile time ?
Well, they could have designed Java so that the compiler (or linker) could have bound everything at compile time. But Java would be a very different language if they did.
But given that they designed Java the way that they did, it is actually not possible to determine certain things at compile time that seem obvious to a reader2. Often this apparent shortcoming is because the reader is not taking into account of things like:
Joachim's comment gives a nice example:
"Imagine for a second that instead of
Animal a = new Dog()
the initialization wasAnimal a = SomeClassFromALibrary.getAnAnimalBasedOnSomeConfiguration()
. Now the compiler has no way of knowing what type a will actually end up referencing. It could beDog
orCat
or evenCow
(which may have been declared in some other library). In short: the compiler doesn't necessarily have a complete view of the program that will end up executing. It only sees a small subset and must act accordingly."
1 - That is ... to the extent that "write once, run everywhere" is reality rather than marketing hype.
2 - As far as I can tell, your example does not illustrate this.
Upvotes: 4