I have an abstract class in C#:
public void activation()
{
activated = true;
on_Activation();
}
protected abstract void on_Activation();
Scenario:
Assume I've made a child of the abstract class and made an implementation of the method, on_Activation()
.
Questions:
Activation()
in the child class? on_Activation()
use the implementation of on_Activation
in the child class? Yes. It's a virtual method (implicitly, because it's abstract) so its "most overridden" version will be called. The fact that the call originates in a method defined on the base class makes no difference.
Yes. And you have just discovered polymorphism . Polymorphism means that you just call a method like on_Activation
on an object (whether the current object called this
, or any other object) and you do not need to specify which version of on_Activation
you mean. It is the actual type of the object at runtime that decides which version of on_Activation
actually gets called.
As Thomas noted, methods which behave this way are called virtual . All abstract methods are virtual in C#. So a virtual method is a name, a symbol, that can polymorphically refer to different things (different method bodies ) at runtime.
If you are curious and want to know what kind of magic is involved, you can check the details at Virtual method table . Essentially every virtual method name like on_Activation
is translated as an index like n
, that is the n
th virtual method of this class. Every non-abstract class provides a table in which all its virtual methods bodies are specified. So, a call to on_Activation
on an object is translated as a call to the n
th entry in the virtual method table of the class of that object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.