C#面向对象基础(六) 继承
继承
描述的是is a kind of 的关系.
比如:Animal类 wolf类. Wolf类是Animal类的子类,Animal类是父类.Wolf类从Animal类派生,Wolf类继承了Animal类
Wolf是一种Animal.
失败的设计:
1publicclassWolf
2{
3publicstringname;
4publicintage;
5publicboolishungry;
6privateintweight;
7publicvoidSleep()
8{
9Console.WriteLine("睡觉...");
10}
11publicvoidEat()
12{
13Console.WriteLine("吃羊...");
14}
15}
16publicclassGoat
17{
18publicstringname;
19publicintage;
20publicboolishungry;
21privateintweight;
22publicvoidSleep()
23{
24Console.WriteLine("睡觉...");
25}
26publicvoidEat()
27{
28Console.WriteLine("吃草...");
29}
30}
用到了继承很好的设计!
classAnimal
{
publicstringname;
publicintage;
publicboolishungry;
privateintweight;
publicvoidSleep()
{
Console.WriteLine("睡觉...");
}
}
publicclassWolf:Animal
{
publicvoidEat()
{
Console.WriteLine("吃羊...");
}
}
publicclassGoat:Animal
{
publicvoidEat()
{
Console.WriteLine("吃草...");
}
}
访问控制修饰符
public 公开的,谁想访问都可以.
private 私有的,类内部访问
proteced 受保护的,子类可以访问.
默认private
密封类
sealed!
publicclassAnimal
{
publicstringname;
publicintage;
publicboolishungry;
protectedintweight;
publicAnimal(stringn,inta)
{
name=n;
age=a;
Console.WriteLine("Animal构造方法");
}
publicvoidSleep()
{
Console.WriteLine("睡觉...");
}
}
publicclassWolf:Animal
{
publicWolf():base("noname",1)
{}
publicWolf(stringn):base(n,1)
{
}
publicWolf(stringn,inta):base(n,a)
{
Console.WriteLine("Wolf构造方法");
}
publicnewvoidSleep()
{
Console.WriteLine("Wolf睡觉...");
}
publicvoidEat()
{
Console.WriteLine("吃羊...");
base.Sleep();
}
}
描述的是is a kind of 的关系.
比如:Animal类 wolf类. Wolf类是Animal类的子类,Animal类是父类.Wolf类从Animal类派生,Wolf类继承了Animal类
Wolf是一种Animal.
失败的设计:
1publicclassWolf
2{
3publicstringname;
4publicintage;
5publicboolishungry;
6privateintweight;
7publicvoidSleep()
8{
9Console.WriteLine("睡觉...");
10}
11publicvoidEat()
12{
13Console.WriteLine("吃羊...");
14}
15}
16publicclassGoat
17{
18publicstringname;
19publicintage;
20publicboolishungry;
21privateintweight;
22publicvoidSleep()
23{
24Console.WriteLine("睡觉...");
25}
26publicvoidEat()
27{
28Console.WriteLine("吃草...");
29}
30}
用到了继承很好的设计!
classAnimal
{
publicstringname;
publicintage;
publicboolishungry;
privateintweight;
publicvoidSleep()
{
Console.WriteLine("睡觉...");
}
}
publicclassWolf:Animal
{
publicvoidEat()
{
Console.WriteLine("吃羊...");
}
}
publicclassGoat:Animal
{
publicvoidEat()
{
Console.WriteLine("吃草...");
}
}
访问控制修饰符
public 公开的,谁想访问都可以.
private 私有的,类内部访问
proteced 受保护的,子类可以访问.
默认private
密封类
sealed!
publicclassAnimal
{
publicstringname;
publicintage;
publicboolishungry;
protectedintweight;
publicAnimal(stringn,inta)
{
name=n;
age=a;
Console.WriteLine("Animal构造方法");
}
publicvoidSleep()
{
Console.WriteLine("睡觉...");
}
}
publicclassWolf:Animal
{
publicWolf():base("noname",1)
{}
publicWolf(stringn):base(n,1)
{
}
publicWolf(stringn,inta):base(n,a)
{
Console.WriteLine("Wolf构造方法");
}
publicnewvoidSleep()
{
Console.WriteLine("Wolf睡觉...");
}
publicvoidEat()
{
Console.WriteLine("吃羊...");
base.Sleep();
}
}