.net和JAVA面向对象,继承有趣的细节

原型是同事间讨论的一道面试题。估计这题秒杀了不少人,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

posted @ 2014-02-28 21:38  cclient  阅读(1045)  评论(8编辑  收藏  举报