码迷,mamicode.com
首页 > 其他好文 > 详细

构造函数

时间:2019-07-28 00:02:31      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:info   inf   ogr   set   ali   方法   输出   this   实例化   

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,调用基类的构造函数赋值,然后调用自己的输出方法

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

构造函数

标签:info   inf   ogr   set   ali   方法   输出   this   实例化   

原文地址:https://www.cnblogs.com/luyShare/p/11257284.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!