Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand whether a behvior will use static or dynamic binding in Java?

I understand at a low level what static (compile time) and dynamic (runtime) bindings are.

I understand to some extent why it's important to know that (e.g., the fact that generics are resolved statically helps explain what you can and cannot do, etc).

What I don't understand is why the choices were made one way or another - e.g., Java uses static binding for overloaded methods, and dynamic binding for overridden ones. Why is that? Is it a design choice, is it something that is obvious and unavoidable for people that understand the deep functioning of Java, or is it something one needs to learn (rather than understand)?

like image 866
JDelage Avatar asked Dec 06 '10 05:12

JDelage


1 Answers

The question is, how can the compiler know which method to call during compile time, in the case of overriding. You must understand this,

List list = list.getAList();
list.add(whatever);

Now, suppose getAList() method can return any of the several List implementations based on some criteria. Thereby, how can a compiler know, that what implementation is returned? and which add() method to call. As you can see, this can only be decided on runtime. Whereas, in overloading its not the case and everything is clear on compile time. I hope you understand the thing now.

[Edited]

Bringing the discussion going on in the comments to the actual answer.

It can't be known until runtime. Understand it this way, the instantiation of a particular class is dependent on the argument provided by user. Now tell me how the compiler will know which argument user will pass, and apparently what class to instantiate. Or easier still, answer this question that how the compiler will know whether the flow will be passed to if block or else block? Or why do you think we have checked and runtime exceptions? Take the case of divide-by-zero; for example n/m, where m becomes 0 as result of some calculation. In this case, its obvious that the compiler wouldn't be able to say that there would be a ArithmeticException because m is not known right away. As all these information are not available at compile time, thus compiler, similarly, doesn't know which method will override which.

like image 197
Adeel Ansari Avatar answered Sep 28 '22 05:09

Adeel Ansari