创建控制台应用程序,通过继承和虚方法来实现多态功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace DuoTai { public class Animal { public virtual void Eat() { Console.WriteLine("Animal eat"); } } public class Dog : Animal { public override void Eat() { Console.WriteLine("Dog eat"); } }
public class Cat : Animal { public override void Eat() { Console.WriteLine("Cat eat"); } }
class Program { static void Main(string[] args) { Animal[] animals = new Animal[3]; animals[0] = new Animal(); animals[1] = new Cat(); animals[2] = new Dog(); for(int i=0;i<3;i++) { animals[i].Eat(); } Console.ReadKey();
} } }
|