多态意义

来源:互联网 发布:国家数据库安全 编辑:程序博客网 时间:2024/05/22 04:23
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
   /// <summary>
   /// 多态的意义:允许派生类修改其父类的行为(方法),派生类比父类更具有个性,在代码跑起来的时候,跟JS很类似,子类覆盖掉了父类的一些方法
   /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            animal[] a = new animal[3];
            a[0] = new animal();
            a[1] = new fish();
            a[0].sleep();
            a[1].sleep();
            Console.ReadLine();
        }

    }
    public class animal
    {
        public virtual void sleep()
        {
            Console.WriteLine("animal all need sleep");
        }
    }

    public class fish : animal
    {
        public override void sleep()
        {
            Console.WriteLine("fish sleeping with eye_open");
        }
    }

    public class dog : animal
    {
        public override void sleep()
        {
            Console.WriteLine("dog sleeping with eye_closed");
        }
    }

}


原创粉丝点击