Override class member: the virtual function is replaced by the new keyword.
After a virtual function is overwritten, no parent variable can access the specific implementation of the virtual function.
Public Virtual void introducemyself () {...} // parent class virtual function
Public new void introducemyself () {...} // subclass overwrites the parent class virtual function
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Namespace methodoverridebynew
{
Public Enum genders {
Female = 0,
Male = 1
}
Public class person {
Protected string _ name;
Protected int _ age;
Protected genders _ gender;
/// <Summary>
/// Parent Constructor
/// </Summary>
Public Person (){
This. _ name = "defaultname ";
This. _ age = 23;
This. _ gender = genders. Male;
}
/// <Summary>
/// Define the virtual function introducemyself ()
/// </Summary>
Public Virtual void introducemyself (){
System. Console. writeline ("person. introducemyself ()");
}
/// <Summary>
/// Define the virtual function printname ()
/// </Summary>
Public Virtual void printname (){
System. Console. writeline ("person. printname ()");
}
}
Public class chineseperson: person {
/// <Summary>
/// Subclass constructor, indicating that the constructor is called from the parent class without Parameters
/// </Summary>
Public chineseperson (): Base (){
This. _ name = "defaultchinesename ";
}
/// <Summary>
/// Overwrite the parent class method introducemyself and use the new keyword to modify the virtual function
/// </Summary>
Public new void introducemyself (){
System. Console. writeline ("chineseperson. introducemyself ()");
}
/// <Summary>
/// Reload the parent class method printname and use the override keyword to modify the virtual function
/// </Summary>
Public override void printname (){
System. Console. writeline ("chineseperson. printname ()");
}
}
Class Program
{
Static void main (string [] ARGs)
{
// Define two objects, one parent object and one subclass object
Person aperson = new chineseperson ();
Chineseperson cnperson = new chineseperson ();
// Call the override method. A parent class object cannot call a method that has been overwritten by a subclass. It can only call its own virtual function method.
Aperson. introducemyself ();
Cnperson. introducemyself ();
// Call the overload method. Both the parent class object and the subclass object can call the method after the subclass is overloaded.
Aperson. printname ();
Cnperson. printname ();
System. Console. Readline ();
}
}
}
Result:
Person. introducemyself ()
Chineseperson. introducemyself ()
Chineseperson. printname ()
Chineseperson. printname ()