What is a Virtual Method?
Category Programming Techniques
Content
A virtual method can have an implementation body. If an instance method declaration contains the virtual modifier, it is called a virtual method. After using the virtual modifier, it is not allowed to have static, abstract, or override modifiers.
Example of a virtual method in a simple factory pattern code:
// For the result after calculation
public virtual double GetResult()
{
double result = 0;
return result;
}
It can be seen that there is a method called GetResult() in this class, which contains a virtual modifier. This modifier indicates that the derived classes of this base class can override this method. The function of the GetResult() method is to output the statement "This is a virtual method!" to the console.
The implementation of a virtual method can be replaced by a derived class. The process of replacing the implementation of an inherited virtual method is called overriding the method; in a virtual method call, the type of the instance at runtime determines which implementation of the method is to be called.
The Difference Between Abstract Methods and Virtual Methods
- A virtual method must have an implementation part, while an abstract method does not provide an implementation part. An abstract method is a method that forces derived classes to override it; otherwise, the derived class cannot be instantiated.
- An abstract method can only be declared in an abstract class, not a virtual method. If a class contains an abstract method, then the class is also abstract and must be declared as such.
- An abstract method must be overridden in the derived class, similar to an interface, while a virtual method does not need to be overridden in the derived class.
In simple terms, an abstract method is one that needs to be implemented by the subclass. A virtual method is already implemented and can be overridden by the subclass, or it can be left unoverridden, depending on the requirements.
Both abstract and virtual methods can be overridden by derived classes.
Summary
In general, a virtual method is a method whose declaration contains the virtual modifier. This is a preliminary understanding for now, and I will supplement it with a deeper understanding later, and also welcome everyone to share their own understanding.
** Click to Share Notes
-
-
-