Inherited
First, let's take a look at the role of inheritance: Removing redundant code from a class
Here is the code show:
We first build a main function, a parent class (EXEC) and two subclasses (PM,CM)
Public classExec { Public intId {Get;Set; } Numbering Public stringName {Get;Set; } Name Public intAge {Get;Set; } Age PublicExec ()//non-parametric construction {} PublicExec (intIdstringNameintAge )//have a reference structure { This. Id =ID; This. Name =name; This. Age =Age ; } Public voidsay ()//Create Say () method {Console.WriteLine ("I am the say method of the parent class, I am {0}, I am {1 years old}"); } }
Public classcm:exec { PublicCM () {} PublicCM (intIdstringNameintAge):Base(id,name,age)//base (id,name,age) invokes the parameter construct of the parent class {
} Public voidsay () {Console.WriteLine ("I am the say method of the parent class, I am {0}, I am {1} years old", Name, age); } }
public class pm:exec { public PM () {} int id,string name,base (id,name,age) { public void Say () {Console.wri Teline ( I am the say method of the parent class, I am {0}, I am {1} years old. ,name,age); } }
classProgram {Static voidMain (string[] args) {PM PM=NewPM (001,"Manager", $);//Create a Manager Object Pm.say ();//Call the Say () method of the PM () subclass cm cm=NewCM (002,"Employees", -);//Create an Employee object Cm.say ();//Call the Say () method of the CM () subclass Console.readkey ();//Make Screen Stop}}
Complete
Polymorphic
The role of polymorphism: solving problems caused by inheritance
Let's start with a piece of code to understand the use of polymorphism, first we want to create a main function, a parent class (person), three subclasses (Korea,chinese,american)
public class person { public int age; public virtual void Hello () {}}
public class American:person { public override void Hello () {Console.WriteLine ( Span> hello " ); } }
public class Chinese:person { public override void Hello () {Console . WriteLine ( hello " ); } }
Public class Korea:person { publicvoid Hello () { base. age=; Console.WriteLine (" Kim Hee Sun greeting "); } }
classProgram {Static voidMain (string[] args) {Chinese Chinese=NewChinese (); American American=NewAmerican (); Korea Korea=NewKorea (); Polymorphic call person[] Pers={Chinese,american,korea}; foreach(Person iteminchpers)//Loop through {item. Hello (); } console.readline (); } }
Complete
The use of the override, and the Virtal keyword is a common method of polymorphism inside
The Virtal keyword decoration method is called a virtual method. The virtual method syntax is as follows
Grammar
Access modifier virtual return type method name ()
{
Method body
}
The override keyword is used to modify the method, which is called a method rewrite. virtual methods can be overridden.
Grammar
Access modifier override return type method name ()
{
Method name
}
The brocade set of inheritance and polymorphism