[继承]2.虚方法

Posted on 2009-10-08 14:19  Relax Active  阅读(115)  评论(0)    收藏  举报

Animal的虚方法场景示例:
//Animal.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Inherit
{
    public class Animal    //声明一个Animal类!
    {
        public virtual void bite()      //用关键字virtual声明为虚方法! 
        {
            Console.WriteLine("I want to bite you!");
        }

    }
    public class Tiger : Animal    //tiger类继承Animal类!
    {
        public override void bite()    //用关键字override重写bite方法!
        {
            Console.WriteLine("我是老虎,我咬死你!哈哈");
        }
    }
    public class Lion : Animal     //Lion类继承Animal类!
    {
        public override void bite()    //用关键字override重写bite方法!
        {
            Console.WriteLine("我狮子大开口!");
        }
    }
}

//Engine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Inherit
{
    class Engine    //声明一个Engine类
    {
        public void Play(Animal animal)    //声明一个Play方法,并把Animal类名+animal变量名传进来!
        {
            animal.bite();  //用变量animal调用bite方法!
        }
    }
}

//Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Inherit
{
    class Program
    {
       
        static void Main(string[] args)
        {
            Engine eng = new Engine();   //创建一个Engine类的实例eng!
            eng.Play(new Tiger());     //eng调用Play方法,Play方法传入Tiger类的实例!
            Console.WriteLine(eng);    //输出结果为"我是老虎,我咬死你!哈哈"!


        }
    }
}

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3