1.字类无参实例化时,必须要有父类提供的一个默认方法。在字类实例化的时候,系统会调用子类的构造方法
2. base能够显式调用父类当中的一些非私有的字段,属性和方法
Console Demo:
1.Mammal:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InherienceDemo { class Mammal { // public string name; private string name; public Mammal() { } // (若子类执行默认构造函数时必须提供) public Mammal( string name) { this.name = name; } public string GetName() { return name; } public void Breath() { Console.WriteLine(name+ " ,正在呼吸 "); } public void SuckleYoung() { Console.WriteLine(name+ " ,正在哺乳 "); } } }
2.Horse:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InherienceDemo { class Horse:Mammal { public Horse( string name) : base(name) { } public void Trot() { Console.WriteLine(GetName()+ " ,正在奔跑 "); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InherienceDemo { class Whale:Mammal { // public void Swim() // { // Console.WriteLine(name+",正在游水"); // } // base能够显式调用父类当中的一些非私有的字段,属性和方法,若是base里不加name则是调用Mammal里的默认构造方法 public Whale( string name): base(name) { } public void Swim() { Console.WriteLine(GetName()+ " ,正在游水 "); } } }
4.Program:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace InherienceDemo { class Program { static void Main( string[] args) { Horse horse = new Horse( " 马 "); horse.Breath(); horse.SuckleYoung(); horse.Trot(); Whale whale = new Whale( " 鲸鱼 "); whale.Breath(); whale.SuckleYoung(); whale.Swim(); // Mammal mammal = new Mammal(); // mammal.name = "哺乳动物"; // mammal.Breath(); // mammal.SuckleYoung(); // Horse horse = new Horse(); // horse.name = "马"; // horse.Breath(); // horse.SuckleYoung(); // horse.Trot(); // Whale whale = new Whale(); // whale.name = "鲸鱼"; // whale.Breath(); // whale.SuckleYoung(); // whale.Swim(); } } }