C#基础--虚方法与重写
2021-02-06 22:14
标签:oid over col 作用 ons virtual console public code 作用:子类可以对父类重写,虚方法是对多态特征体现。 C#基础--虚方法与重写 标签:oid over col 作用 ons virtual console public code 原文地址:https://www.cnblogs.com/QueryWord/p/11407124.html 1 public class Animal
2 {
3 public string Name { get; set; }
4 public virtual void Eat()
5 {
6 Console.WriteLine("{0}正在吃草",Name);
7 }
8
9 }
10 public class Sheep : Animal
11 {
12 public Sheep(){ Name = "羊"; }
13 public override void Eat()
14 {
15 base.Eat();
16 Console.WriteLine("吃草");
17
18 }
19
20 }
21
22 public class Tigger : Animal
23 {
24 public Tigger() { Name = "老虎"; }
25 public override void Eat()
26 {
27 base.Eat();
28 Console.WriteLine("老虎吃羊");
29
30 }
31 }
Animal animal1 = new Sheep();
Animal animal2 = new Tigger();
animal1.Eat();
animal2.Eat();