重写在多态中的应用

来源:互联网 发布:java开发中间件 编辑:程序博客网 时间:2024/04/30 10:39

多态:
对于相同的事件,不同的对象表现出了不同的行为
重写:
子类重写父类的方法,使父类在引用中使用子类的方法

多态和重写的结合应用:

Class:Animal

using System.Windows.Forms;

namespace Test
{
    class Animal
    {
        public virtual void Sound()
        {
            MessageBox.Show("bujiao");
        }
    }
}


Class:Dog

using System.Windows.Forms;

namespace Test
{
    class Dog:Animal
    {
        //重写Sound
        public override void Sound()
        {
            MessageBox.Show("wangwang");
        }
    }
}


Class:Cat

using System.Windows.Forms;

namespace Test
{
    class Cat:Animal
    {
        public void Sound()
        {
            MessageBox.Show("miaomiao");
        }
    }
}

再在一个窗体上放个命令按钮事件中分别写出下面的代码,查看执行结果
        //猫叫结果为"bujiao"
      
        private void button_Click(object sender, EventArgs e)
        {
            Animal animal = new Cat();
          //执行未被重写的代码           
            animal.Sound();
        }


       //狗叫结果为"wangwang"
        private void button_Click(object sender, EventArgs e)
        {
            //执行被重写过的代码
            Animal animal = new Dog();
            animal.Sound();
        }

       //若想要让猫叫结果为"miaomiao"必须写成下面那种形式

        private void button_Click(object sender, EventArgs e)
        {
            Cat cat = new Cat();
            Animal animal = cat;
            Cat newcat = (Cat)animal;
            newcat.Sound();
        }

可见重写能让多态的应用变得很加简洁明了.

初写博客,写的不全的希望大家补充一下,不足的地方请指出一下,谢谢

 

原创粉丝点击