標籤:code write href other com 多態 read static 證明
C#與Java多態方面的文法差異
2016-11-29
Java代碼:
public static void main(String[] args) { Mother mother=new Mother(); mother.showName(); Mother human=new Son(); human.showName(); Son sona=new Son(); sona.showName();} public class Mother { public void showName(){ System.out.println("媽媽"); }}public class Son extends Mother { public void showName(){ System.out.println("兒子"); } }
結果:
媽媽兒子兒子
C#代碼:
class Program { public static void Main() { Mother mother = new Mother(); mother.ShowName(); Mother human = new Son(); human.ShowName(); Son sona = new Son(); sona.ShowName(); Console.Read(); } } public class Mother { public virtual void ShowName() { Console.WriteLine("媽媽"); } } public class Son : Mother { public override void ShowName() { Console.WriteLine("兒子"); } }
結果:
媽媽兒子兒子
但如果把override去了,將會出現一行警告,但編譯器不會報錯:
警告 1 “ConsoleApplication1.Son.ShowName()”隱藏了繼承的成員“ConsoleApplication1.Mother.ShowName()”。如果是有意隱藏,請使用關鍵字 new
結果為:
媽媽媽媽兒子
結論:
由此證明,C#預設情況下是不支援多態的,子類預設情況下有個new關鍵字。C#若要實現多台需要在方法前添加virtual和override
另外,多態指的是方法,詳情見 只有多態方法,沒有多態執行個體欄位
C#與Java多態方面的文法差異