C# 面向对象之多态

//多态:让一个对象表现的多种状态
//实现:子类重写父类的虚方法

            Person person = new Person();
            Chinese chinese = new Chinese();
            America america = new America();

            Person[] p = { person, chinese, america };
            for (int i = 0; i < p.Length; i++)
            {
                p[i].SayHello();//多种状态的表现
            }
            Console.ReadKey();

public class Person
{
            //父类的虚方法
            public virtual void SayHello()
            {
                Console.WriteLine("我是人类");
            }
}

public class Chinese : Person
{
            //子类重写父类的虚方法
            public override void SayHello()
            {
                Console.WriteLine("我是中国人");
            }
}

public class America : Person
{
            //子类重写父类的虚方法
            public override void SayHello()
            {
                Console.WriteLine("我是美国人");
            }
}

posted @ 2017-04-21 11:42  CH|heyi  阅读(178)  评论(0编辑  收藏  举报