Content
A virtual method can have an implementation body. If the declaration of an instance method contains the virtual modifier, the method is called a virtual method. Once the virtual modifier is used, no further static, abstract, or override modifiers are allowed.
Virtual method code in the Simple Factory pattern:
It can be seen that the class has a GetResult() method. The GetResult() method contains a virtual modifier, which indicates that derived classes of the base class can override this method. The purpose of the GetResult() method: 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 that method. In a virtual method call, the runtime type of the instance involved in the call determines which implementation of the method is actually invoked.
The difference between abstract methods and virtual methods
- 1. Virtual methods must have an implementation part; abstract methods do 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.
- 2. Abstract methods can only be declared in abstract classes; virtual methods are not. If a class contains an abstract method, then the class is also abstract, and it must also be declared as abstract.
- 3. Abstract methods must be overridden in derived classes, which is similar to interfaces. Virtual methods do not need to be overridden in derived classes.
In simple terms, abstract methods need to be implemented by subclasses. Virtual methods are already implemented and can be overridden by subclasses, or not overridden, depending on requirements.
Both abstract methods and virtual methods can be overridden by derived classes.
Summary
Overall, a virtual method is a method whose declaration contains the virtual modifier. For now, this is the only way to understand it. If I gain a deeper understanding later, I will add more. Everyone is welcome to share your understanding.