S
S
Shady10102017-04-09 19:30:22
Java
Shady1010, 2017-04-09 19:30:22

What is dynamic dispatch?

Hello. I want to learn about dynamic method dispatching and understand if I understood the topic correctly.
Dynamic dispatch is when we set a reference variable of a superclass to a reference to a subclass and call an overridden method.
For example:
A a; //Superclass
B b = new B(); //subclass
C c = new C(); //subclass
a = b;
a.callme();
a = c;
a.callme();
This is understandable.
And an example of non-dynamic dispatch:
B b = new B();
C c = new C();
b.callme();
c.callme();
Now the questions themselves:
1) Did I understand correctly that with dynamic dispatch, an object is accessed at run time, and not at compilation time?
2) What advantage does this give, does it affect performance, RAM? It seems to me that it will only affect the speed of compilation.
3) I correctly understood that it is more correct to always use Dynamic Dispatching, since in this way we correctly implement polymorphism, or there is no right and wrong, and everyone does as he pleases.
The questions may seem silly to some, but I cannot proceed to the next chapter until I understand the topic well and find the answers to my questions. I didn’t find anything worthwhile on Google - it’s mostly touched upon superficially, and on the forums I only meet holivars with insults. Schildt's book (The Complete Guide) has little to say about this. I would be grateful for an intelligible answer.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-04-09
@Shady1010

1. And how do you imagine accessing an object at compile time, when this object does not even exist? Well this is absurd. Of course, it happens at runtime, when these objects are instantiated and exist.
2. It doesn't matter what it affects as long as it's the right approach. It's better to lose a percentage on performance than to break encapsulation and polymorphism and write shitty code.
3. Yes, in 99% you need to use it, because it is a native for many languages ​​​​implementation of the Barbara Liskov Substitution Principle from SOLID patterns .
You think correctly, many people forget about this understanding, and then they shit with all sorts of switch instanceof .
In general, in a good OOP design, when you meet a stack of behavioral ifs, more than 5-7 pieces, switches, and so on, then at this point you should think about using dispatching, because they, in the vast majority of cases, are replaced in in favor of a more flexible and adequate OOP design. But, it's not fanatical to change everything, of course =)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question