How to understand whether behvior will use static or dynamic binding in Java?
I understand at a low level what static (compile time) and dynamic (run time) bindings are
I understand in a way why it's important to know this (for example, the fact that generic drugs are solved in imitation helps to explain what you can and don't do, etc.)
I don't understand why the choice is made in one way or another - for example, Java uses static binding for overloaded methods and dynamic binding for rewritten methods Why? Is it a design option? For those who understand the deep functions of Java, is it obvious and inevitable, or something to learn (rather than understand)?
Solution
The question is, in the case of rewriting, how does the compiler know which method to call during compilation You have to understand that,
List list = list.getAList(); list.add(whatever);
Now, suppose that the GetList () method can return any number of list implementations based on certain conditions So how does the compiler know what implementation is returned? And the add () method to call As you can see, this can only be determined at run time However, when overloading is not the case, everything is clear at compile time I hope you understand it now
Post
Introduce the discussion in the comments into practical answers
It is not known until runtime Understanding it this way, the instantiation of a particular class depends on user - supplied parameters Now tell me how the compiler will know which parameter the user will pass and the class to instantiate Or, more easily, to answer this question, how will the compiler know if the stream will be passed to if or blocked? Or why do you think we check and run-time exceptions? Take the case of division by zero as an example; For example, N / m, where m becomes 0 due to some calculations In this case, it is obvious that the compiler cannot say that an arithmeticexception will occur because m is unknown Since all this information is not available at compile time, the compiler similarly does not know which method will override which