多态经典面试题

    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关键字修饰的方法,将会是一个新的方法,它不会覆盖父类的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值