原型是同事間討論的一道面試題。估計這題秒殺了不少人,LZ也被秒了。
但這個題里隱藏了一個很有趣的細節,這個細節不說清楚,不少人會其實死的冤枉。
這是C#的代碼。
class Program { static void Main(string[] args) { Father s1 =new Son1(); Son1 s2 =new Son1(); s1.Say(); s2.Say(); Console.Read(); } } public class Father { public void Say() { Console.WriteLine("This is Father's method"); } } public class Son1 : Father { public void Say() { Console.WriteLine("This is Son1's method"); } }
執行結果是 This is Father's method
This is Son1's method
不知大家有沒有答對,LZ想也沒想直覺就是
This is Son1's method
This is Son1's method
因為之前看過JAVA的內容。
這是原貼:http://blog.csdn.net/zhengzhb/article/details/7496949
仔細想了下.NET算是想通了。但這事就有趣了。
因為JAVA的結果和.NET完全兩樣。(LZ學設計模式什么的都是照着JAVA學的,之前一直感覺也相信着兩者在面向對象方面是一個模子)。
這是JAVA的代碼
class Father { public void Say(){ System.out.println("This is Father's method"); } } class Son1 extends Father{ public void Say(){ System.out.println("This is Son1's method"); } } public class FF { public static void main(String[] args){ Father s1 = new Son1(); Son1 s2=new Son1(); s1.Say(); s2.Say(); } }
結果是
This is Son1's method
This is Son1's method