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

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

To some extent, I understand why it is important to know what (for example, the fact that generic funds are statically allowed helps to explain what you can and cannot do, etc.).

I don’t understand why the choice was made one way or another - for example, Java uses static binding for overloaded methods and dynamic binding for overridden ones. Why is this? Is this a design choice, is it obvious and inevitable for people who understand the deep functioning of Java, or is it something that needs to be studied (rather than understood)?

+7
java language-design
source share
3 answers

The question is how the compiler can find out which method to call at compile time if overridden. You must understand this

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

Now suppose the getAList() method can return any of several List implementations based on some criteria. So how can the compiler know which implementation is returning? and which add() method to call. As you can see, this can only be solved at runtime. While overloading is not the case, and at compile time everything is clear. I hope you understand this now.

[Edited]

Bringing the discussion into a comment on the actual answer.

It may not be known until complete. Understanding this, the creation of a particular class depends on the argument provided by the user. Now tell me how the compiler finds out which argument the user will pass, and apparently which class should instantiate. Or even simpler, answer this question, how will the compiler know if the stream will be passed to the if block or else ? Or why do you think we have checks and runtime exceptions? Take the divide-by-zero case; for example n/m , where m becomes 0 as a result of some calculation. In this case, it is obvious that the compiler will not be able to say what will be an ArithmeticException , because m not immediately known. Since all this information is not available at compile time, thus, the compiler likewise does not know which method will override.

+3
source share

Dynamic binding is when you redefine methods, because at runtime it will be necessary to decide which method (code) to execute based on the type of runtime of the object. With an overloaded method that you do not need to decide at runtime, you can determine the compilation time that the method will invoke. This will lead to faster execution.

+1
source share

For me, I think this is for a good reason ... Overloading is what complicates understanding during complication, and redefinition is late binding or runtime. Understanding the concept of OOP can help you.

0
source share

All Articles