Topic description
Create a virtual method and a non-virtual method, then inherit from another class respectively, and compare the results of their invocations. (console application)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace virtual method { class class1 { //The default method is designated as private and can only be accessed in the current class, the default is private //If you need to access it in other classes, you need to specify it as public: the highest access rights, as long as you can access it within the project //virtual keyword must be before void public virtual void virtualMethod()//Virtual methods can be overridden in derived classes { Console.WriteLine("This is a virtual method"); } public void nonVirtualMethod() { Console.WriteLine("This is a non-virtual method"); } } class class2 : class1//Inherit class2 with class1 { public override void virtualMethod() { Console.WriteLine("This is a newly written virtual method"); } public new void nonVirtualMethod() { Console.WriteLine("This is a new method"); } } class Program { static void Main(string[] args) { class1 c1 = new class1();//Instantiate the class c1.virtualMethod(); c1.nonVirtualMethod(); class2 c2 = new class2(); c2.virtualMethod(); c2.nonVirtualMethod(); c1 = c2; c1.virtualMethod(); c1.nonVirtualMethod(); Console.ReadKey(); } } }
***The implementation of a non-virtual method is immutable: the implementation is the same whether the method is called on an instance of the class in which it is declared or an instance of a derived class. In contrast, the process of implementing a virtual method is called overriding the method.