I am always very lazy recently. I don't want to start reading books. I know that programming is not enough, so I still need to stick to the demo to the end ~
As we know before, the execution sequence of constructors in the inheritance relationship is as follows: first, the constructors of the base class are executed, and then the class itself to be instantiated. Of course, the base class here is a recursive process. That is to say, as long as there is an inheritance relationship, it will always be recursive until system. object.
In fact, this layer of relationship writes two classes with inheritance relationships, then writes this constructor, instantiates this inheritance class, And the execution process of the constructor can be clearly seen in single-step debugging. here, if both classes use the default constructor, the relationship is naturally invisible.
Here I want to talk about the execution of constructors with parameters. For example, we will write some common attributes into the base class. when instantiating the inherited class, these attributes (base class) are often initialized in the constructor. At this time, the base keyword is required. In addition, the execution sequence of the constructor still follows the preceding sequence.
Demo: Using System;
Using System. Collections. Generic;
Using System. text;
Namespace Constructordemo
{
Class Program
{
Static Void Main ( String [] ARGs)
{
Littlebird lb = New Littlebird ( " Lbname " , 4 );
Console. writeline (Lb. Name + " --- " + LB. Num );
LB. showname ();
Animal ain = New Bird ( " Birdname " );
Console. writeline (AIN. Name );
Ain. showname ();
}
}
Abstract Class Animal
{
Private String Name;
Public String Name
{
Get {ReturnName ;}
Set {Name=Value ;}
}
Public Animal ( String Name)
{
This. Name=Name;
}
Public Abstract Void Showname ();
}
Class BIRD: Animal
{
Public Bird ( String Bird_name)
: Base (Bird_name) // Passing parameters to the base class Constructor
{
}
Public Override Void Showname ()
{
Console. writeline ("Hi, this is Bird: {0}", Name );
}
}
Class Littlebird: Bird
{
Private Int Num;
Public Int Num
{
Get
{
ReturnNum;
}
Set
{
Num=Value;
}
}
Public Littlebird ( String Lb_name, Int Lb_num)
: Base (Lb_name) // Passing parameters to the base class Constructor
{
This. Num=Lb_num;//Execute the constructor itself
}
Public Override Void Showname ()
{
Base. Showname ();//Call the base class Method
Console. writeline ("Hi, this is Little Bird: {0}", Name );
}
}
}
Note the usage of the base Keyword:
1. Call the base class constructor and pass the parameter.
2. Call the base class method (of course called in the override method)