您的位置:首页 > 职场人生

多态经典面试题

2016-02-18 21:37 302 查看
class A
{
public string Str = "A";

public void Show() { Console.WriteLine("Show A"); }
}

class B : A
{
public string Str = "B";

public virtual void Show() { Console.WriteLine("Show B"); }
}

class C : B
{
public override void Show() { Console.WriteLine("Show C"); }
}

class D : C
{
public string Str = "D";

public void Show() { Console.WriteLine("Show D"); }
}

class Program
{
static void Main(string[] args)
{
D d = new D();
C c = d;
B b = d;
A a = d;
Console.WriteLine(d.Str); //d
Console.WriteLine(c.Str);  //b
Console.WriteLine(b.Str);//b
Console.WriteLine(a.Str);//a
Console.WriteLine("------------");
d.Show();//d
c.Show();//c
b.Show();//c
a.Show();//a
Console.ReadLine();
}
}


new隐藏,over重写;隐藏看类型,重写只管新

override:在子类或实现类中用来重写抽象方法或虚方法。将覆盖父类的方法。

new:在子类的用new关键字修饰的方法,将会是一个新的方法,它不会覆盖父类的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多态 面试题