这次的多态很简单,没什么知识点 。
直接贴代码了:
1 public abstract class Animal //建立一个抽象类 2 { 3 private bool m_sex; 4 private string m_sound; 5 public bool Sex 6 { 7 get { return m_sex; } 8 set { m_sex = value;} 9 } 10 public string Sound 11 { 12 get { return m_sound; } 13 set { m_sound = value; } 14 } 15 public Animal() 16 { 17 Sex = false; 18 Sound = "Howl..."; 19 } 20 public abstract string Roar(); 21 } 22 public class Dog:Animal 23 { 24 bool Sex=true; 25 string Sound = "Wow.."; 26 public override string Roar() 27 { 28 return ("Dog:" + Sound); 29 } 30 } 31 public class Cat : Animal 32 { 33 bool Sex = true; 34 string Sound = "Miaow.."; 35 public override string Roar() 36 { 37 return ("Cat:" + Sound); 38 } 39 } 40 public class Cow : Animal 41 { 42 bool Sex = true; 43 string Sound = "Moooo.."; 44 public override string Roar() 45 { 46 return ("Cow:" + Sound); 47 } 48 }
主函数的代码:
Animal animal; Dog dog = new Dog(); Cat cat = new Cat(); Cow cow = new Cow(); animal = dog; animal = cat; animal = cow; Console.WriteLine(dog.Roar()); Console.WriteLine(cat.Roar()); Console.WriteLine(cow.Roar()); Console.ReadKey();
再来个图片: