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