C#——调用基类默认构造参数与调用基类有参数的构造函数举例详解

通过下面的例子我们可以更好的了解这两者的用法:

 

注意:在创建派生类的实例时,

(1)如果没有指定参数则系统自动调用默认构造函数

(2)如果指定了参数,则通过base关键字调用基类的相应的构造函数,初始化从基类继承的字段,而派生类的构造函数只负责对自己扩展的字段进行初始化。

 

设计界面:

C#——调用基类默认构造参数与调用基类有参数的构造函数举例详解

编写代码

 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace 继承

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void button1_Click(object sender, EventArgs e)

        {

label4.text=””;

            Dog d;

            if (textBox1.Text == "")

            {

                d = new Dog();

            }

            else

            {

                d = new Dog(textBox1 .Text ,Convert .ToInt32(textBox2 .Text ),textBox3 .Text );

            }

            label4.Text += "\n" +d.getMessage()+d.eat();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            label4.Text = "";

        }

    }

    public class Animal

    {

        protected string name;

        protected int age;

        public Animal()

        {

            this.name = "未知";

            this.age = 0;

        }

        public Animal(string name,int age)

        {

            this.name = name;

            this.age = age;

        }

        public string  eat()

        {

            return string.Format("\n{0}:吃东西",name);

        }

    }

    public class Dog : Animal

    {

        private string type;

        public Dog()   //派生类的默认构造函数,自动调用基类的默认构造函数,即不用加:base()

        {

            this.type = "未知";

        }

        public Dog(string n,int a,string type):base(n,a)

        {

            this.type = type;

        }

        public string getMessage()

        {

            return string.Format("姓名:{0}   年龄:{1}    品种:{2}",name ,age ,type );

        }

    }

}

 

运行结果

C#——调用基类默认构造参数与调用基类有参数的构造函数举例详解

C#——调用基类默认构造参数与调用基类有参数的构造函数举例详解