After going through 2-3 hour to know, what is the difference between compile-time and run-time. Lastly, i came up with this.
Memory allocated at runtime referred to run-time/dynamic binding and allocated at compile time referred to compile-time/static binding.
and then i tried this example
class myclass {
void here() {
System.out.println("Here from myclass !!");
}
void here(int i) {
System.out.println("Here !!" + i);
}
}
class thisclass extends myclass {
void here() {
System.out.println("Here from thisclass !!");
}
}
public class poly {
public static void main(String s[]) {
myclass m= new myclass();
myclass a= new thisclass();
m.here();
m.here(12);
a.here();
a.here(13);
}
}
So, i also found that myclass a= new thisclass(); is considered to be run-time binding. Since, a is the object of myclass, but suddenly compiler found that, class mis-matched. So, it will be dynamically bind the space of thisclass object.
So, till here, i got the things. But, i found that, another common answer was overloading refer to compile time and overriding refer to run-time. I didn’t get this point.
thisclass a= new thisclass();
a.here();
Is this also called to be run-time binding. ?? Please correct me, if wrote anything wrong here.
First of all, memory allocation is not in this picture. There is no compile-time memory allocation.
The question conflates compile-time with static binding and run-time with dynamic binding.
Static binding happens at compile time; dynamic binding happens at runtime.
Now, when you write
what happens at compile-time is the resolution of the method signature: you are calling
here(int)and that choice is final. This is termed “static binding”. What happens at runtime is method dispatch: the runtime chooses ahere(int)implementation appropriate to the runtime type of the object referenced bym. There are two methods to choose from:myclass.m(int)andthisclass.m(int), and the runtime chooses the latter in this particular example. This is termed “dynamic binding”.As to your question “is overriding compulsory for dynamic binding”… The Java Language Specification prescribes the rules on choosing the correct method to invoke at runtime. These rules imply a procedure known as “dynamic binding” for the general case. But if you are asking whether any specific process always happens at runtime, the story is different: an optimizing JIT compiler can see that there is only one method to choose from and output a “monomorphic call site” which hardcodes the single choice. Further, it can also inline the entire method into the caller, thereby removing even the call itself.