构造函数

class Program
{
public class Animal
{
public string name;
public int age;

public void setInfo(string name, int age)
{
this.name = name;
this.age = age;
}

 

public Animal()//没参数的构造函数

{ }
public Animal(string name, int age)//有两个参数的构造函数
{
this.name = name;
this.age = age;
}
}

public class Dog : Animal
{
public string GetAnimalInfo()
{
return age + "岁的" + name;
}
}
public class Cat : Animal
{
public Cat(string name, int age) : base(name, age)//base
{

}
public string GetAnimalInfo()
{
return age + "岁的" + name;
}
}
static void Main(string[] args)
{
string result = string.Empty;
Dog dog = new Dog();
dog.setInfo("灰狗", 3);
Console.WriteLine(dog.GetAnimalInfo());

Cat cat = new Cat("黑猫", 2);
Console.WriteLine(cat.GetAnimalInfo());
}
}

派生类 Dog,调用基类中的赋值方法,然后调用自己的输出方法

派生类Cat,调用基类的构造函数赋值,然后调用自己的输出方法

需要注意的是,如果基类没有写构造函数,会默认生成没有参数的构造函数,如果写了,就用已定义的构造函数,派生类在实例化时,一定会调用基类的构造函数,因此构造函数不能是私有的。

posted @ 2019-07-27 23:25  luytest  阅读(162)  评论(0编辑  收藏  举报