黑马程序员技术交流社区
标题:
请教有关构造函数的问题?
[打印本页]
作者:
qly2046
时间:
2013-12-22 14:27
标题:
请教有关构造函数的问题?
本帖最后由 qly2046 于 2013-12-23 21:48 编辑
定义
父亲类 Father (姓firstName,财产wealth,血型blood),
儿子类 Son (玩游戏PlayGame),
女儿类 Daughter (跳舞Dance),
调用父类构造函数给子类字段赋值。
我不太明白这道题的意思?求大神指点?谢谢
作者:
邢换换
时间:
2013-12-22 14:41
类的继承——子类构造函数
概述:子类默认情况下会调用父类的的无参数构造函数
如果父类写了有参数的构造函数,子类未调用父类的有参数的构造函数,则需要显示的写出父类的无参数构造函
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;
}
}
}
作者:
曹华
时间:
2013-12-22 19:24
我看了楼上的的,大概也是在子类构造方法时,使用base()语句,调用父类构造方法。但有一个问题是
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;
}
我发现使用了base()语句,那么构造函数体中前3句都是无用了,属于重复复制。可以屏蔽掉base(),也可以屏蔽掉前3条语句。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2