我比較喜歡對感興趣的理論進行反覆的理解甚至理解背誦下來,接下來再複習一下什麼叫多態(哈哈哈)spa
多態:在同一粒度視圖下對相同類型的事物不作區別的統一處理code
接下來看一下接口和引擎類是如何實現多態的:對象
1、blog
一、建立了一個接口類:IWeapon繼承
1 public interface IWeapon 2 { 3 void Fire(); 4 }
二、聲明幾個類去實現這個接口(展現描述的詞語是我老師的佳做,我但是軟妹子(哈哈哈))接口
1 public class Gun : IWeapon 2 { 3 public void Fire() 4 { 5 Console.WriteLine("pa peng pa peng"); 6 } 7 } 8 9 public class Sword : IWeapon 10 { 11 public void Fire() 12 { 13 Console.WriteLine("七劍下天山"); 14 } 15 16 } 17 18 public class Tank : IWeapon 19 { 20 public void Fire() 21 { 22 Console.WriteLine("壓死你"); 23 } 24 } 25 26 public class Xiaomugun : IWeapon 27 { 28 public void Fire() 29 { 30 Console.WriteLine("扎死你"); 31 } 32 }
三、建立一個引擎類:Engine(以接口爲參數)it
1 public static void Play(IWeapon w) 2 { 3 w.Fire(); 4 }
四、在程序入口處調用引擎類,實現多態class
1 InterfaceDemo.Engine.Play(new InterfaceDemo.Gun()); 2 InterfaceDemo.Engine.Play(new InterfaceDemo.Sword()); 3 InterfaceDemo.Engine.Play(new InterfaceDemo.Tank()); 4 InterfaceDemo.Engine.Play(new InterfaceDemo.Xiaomugun());
上面調用的結果是:程序
1 pa peng pa peng 2 七劍下天山 3 壓死你 4 扎死你
順便複習一下抽象類和接口的一點小區別:static
一個類能夠去實現多個接口,表示這個類的對象能夠作什麼
一個類只能繼承一個抽象類,至關於派生類是一個抽象類的意思,從屬關係比較緊湊