Answer the question
In order to leave comments, you need to log in
What is the difference between overriding, from overriding (new), an inherited method?
Good day!
Condition:
I have parent and child methods, I need to change the functionality of the inherited method, for which I can either redefine an existing method or override the original one with a new one.
Questions
Answer the question
In order to leave comments, you need to log in
Let me answer the third question first.
To understand the difference between overriding and overriding, you need to understand how a program chooses which version of a method to call based on the actual type of the object.
The compiler creates a table of all virtual methods of the class (including overridden ones, because they are also virtual) and indicates in which type they are designated. When a virtual method is called, the real type of the object is taken and the desired method implementation option is selected. If you specify a method with the new
keyword in a derived class, then this method ceases to be an override of the base class method, and this method is not added to that override table. This means that when a method is called, the search by object type will not find the method marked new (it is not in the table), and will try to find the closest method.
Please note that the new overridden method can also be specified with the virtual key method, that is, it will also fall into the virtual method table, but as if in a different table, thereby creating a new hierarchy of implementations.
2. When to use override and when to override?
Usually you need an override, rarely someone needs an overlap. If you need a separate implementation for a specific successor, then (sometimes) you can make a method with a different name, and call it directly, and not through a call to virtual methods. If it is still necessary (to override the method), then you need to understand that calling such a method through a reference to the base class will not work (without casting to the desired type).
Interestingly, in Java, all methods are virtual, and there is no way to override (but not override) the base method, as it is possible in c#.
1. How can these approaches be visualized?
This question is not clear. In a graphical description of the class hierarchy? In UML, as far as I remember, virtual methods are written in italics. This means that the overridden method will be in regular, non-italic font.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question