i am trying to understand dynamic/static binding on a deeper lever and i can say after a lot of reading and searching i got really confused about something.
Well, java uses dynamic binding for overriden methods and the reason for this is that the compiler doesn't know to which class the method belongs to, right? For example :
public class Animal{
void eat(){
}
class Dog extends Animal{
@Override
void eat(){}
}
public static void main(String[] args[]){
Dog d = new Dog();
d.eat();
}
My question is why the compiler doesn't know that the code refers to the Dog class eat() method, even though d reference is declared to be of class Dog and Dog's constructor is used to create the instance at runtime? The object is going to be created at runtime, but why the compiler doesn't understand that the code refers to Dog's method?Is it a matter of the compiler's design or am i missing something?
and the reason for this is that the compiler doesn't know to which class the method belongs to, right?
Actually, no. The compiler doesn't want to know the specific type of the target object. This allows code compiled now to work in the future with classes that don't even exist yet.
As the most obvious example consider a JDK method like Collections.sort(List)
. You can pass it an implementation of List
that you just created. You don't want to have to notify Oracle that you did it, and hope they include it in their list of "statically supported" list types.