class Program
{
static void Main(string[] args)
{
Cow cow = new Cow("牛牛");
cow.EatFood();
cow.Breed();
cow.Moo();
cow.SupplyMilk();
Console.WriteLine();
Chicken chicken = new Chicken("咕咕");
chicken.EatFood();
chicken.Breed();
chicken.Cluck();
chicken.LayEgg();
}
}
//动物类
class Animal
{
protected string name = "";
public Animal(string name)
{
this.name = name;
}
public void EatFood() //吃东西
{
Console.WriteLine(this.name + "会吃东西");
}
public void Breed() //繁殖后代
{
Console.WriteLine( this.name + "能繁殖后代");
}
}
class Cow:Animal
{
public Cow(string name): base(name)
{ }
public void Moo() //牛叫
{
Console.WriteLine( "我的名字叫" + name + " 哞");
}
public void SupplyMilk() //提供牛奶
{
Console.WriteLine( "我的名字叫" + name + " 我能提供牛奶");
}
}
class Chicken : Animal
{
public Chicken(string name):base(name)
{ }
public void Cluck() //鸡叫
{
Console.WriteLine("我的名字叫" + name + " 咯咯咯");
}
public void LayEgg() //下蛋
{
Console.WriteLine("我的名字叫" + name + " 我能下蛋");
}
}
继承的缺点:如果父类改变,那么子类就不得不变。继承会破坏包装,父类实现细节暴露给子类,增大了两个类之间的耦合性。
原文地址:http://blog.csdn.net/ry513705618/article/details/26075653