A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© qly2046 中级黑马   /  2013-12-22 14:27  /  1122 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 qly2046 于 2013-12-23 21:48 编辑

定义
父亲类  Father  (姓firstName,财产wealth,血型blood),
儿子类    Son    (玩游戏PlayGame),
女儿类   Daughter     (跳舞Dance),
调用父类构造函数给子类字段赋值。


我不太明白这道题的意思?求大神指点?谢谢

2 个回复

倒序浏览
类的继承——子类构造函数




概述:子类默认情况下会调用父类的的无参数构造函数

      如果父类写了有参数的构造函数,子类未调用父类的有参数的构造函数,则需要显示的写出父类的无参数构造函


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;

        }

    }

}

评分

参与人数 1技术分 +1 收起 理由
陈福军 + 1

查看全部评分

回复 使用道具 举报
我看了楼上的的,大概也是在子类构造方法时,使用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条语句。
回复 使用道具 举报 1 0
您需要登录后才可以回帖 登录 | 加入黑马