类的继承——子类构造函数
概述:子类默认情况下会调用父类的的无参数构造函数
如果父类写了有参数的构造函数,子类未调用父类的有参数的构造函数,则需要显示的写出父类的无参数构造函
namespace 类的继承_子类构造函数
{
class Program
{
//3、 定义父亲类Father(姓firstName,财产wealth,血型blood),儿子Son类(玩游戏PlayGame),女儿Daughter类(跳舞Dance),
// 调用父类构造函数给子类字段赋值。
static void Main(string[] args)
{
Son son = new Son("Green", 20000, "O", "Good"); //实例化一个儿子的对象
Console.WriteLine(son.firstName);
son.PlayGame("lol"); //调用儿子的方法
Console.ReadKey();
}
}
class Father
{
public string firstName;
public int wealth;
public string blood;
public Father() { } //如果子类写了一个造函数,此造函数没有调用父类带参数的构造函数,此时就要显示的写出父类的无参数构造函数
public Father(string f, int w, string b) //定于父类带参数的构造函数
{
this.firstName = f;
this.wealth = w;
this.blood = b;
}
}
class Son : Father
{
public string health; //自己写的一个字段
public void PlayGame(string Game) //将儿子玩游戏写成一个方法
{
Console.WriteLine("我玩{0},哈哈哈哈哈;", Game);
}
public Son(string f, int w, string b, string h)
: base(f, w, b) //利用base调用父类的构造函数
{
this.firstName = f;
this.wealth = w;
this.blood = b;
this.health = h;
}
}
class Daughter : Father
{
public int age; //自己写的一个字段
public void Dance() //将女儿跳舞写成一个方法
{
Console.WriteLine("我跳拉丁,呵呵");
}
public Daughter(string f, int w, string b, int a)
: base(f, w, b) //利用base调用父类的构造函数
{
this.firstName = f;
this.wealth = w;
this.blood = b;
this.age = a;
}
}
} |