C#基础-043 多态

虚方法和重写
这是一个父类:

 class Animal
    {
        public virtual void Eat()
        {
            Console.WriteLine("动物在吃饭");
        }
    }

这是子类猫,重写父类虚方法

 class Cat:Animal
    {
        public override void Eat()
        {
            Console.WriteLine("猫在吃鱼");
        }
    }

这是子类狗,重写父类虚方法

 class Dog:Animal
    {
        public override void Eat()
        {
            Console.WriteLine("狗在吃骨头");
        }
    }

主程测试:

static void Main(string[] args)
        {
            Animal[] animals = new Animal[5];
            //向上转型
            animals[0] = new Dog();
            animals[1] = new Dog();
            animals[2] = new Cat();
            animals[3] = new Cat();
            animals[4] = new Dog();
            for (int i = 0; i < animals.Length; i++)
            {
                if (animals[i] is Dog)
                {
                    //向下转型
                    ((Dog)animals[i]).Eat();
                }
                else
                {
                    ((Cat)animals[i]).Eat();
                }
                animals[i].Eat();
            }
            //重写和重载有什么区别?
            /*
             * 相同:
             * 重载和重写的方法名都一致
             * 
             * 不同点:
             * 重写是在父子类中的  重载是在同一个类中
             * 重写的参数列表一致  重载的参数列表不同
             * 重写是运行时多态    重载是编译时多态
             * 
             */
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值