孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

密封类和方法对继承和多态进行限制。在希望别人不能改变代码又希望自己使用时,可以在代码中使用密封的类和方法:使用sealed关键字来表示类或方法为密封

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
         public class MotorVehicle
        {
            public string make;
            public string model;

            public MotorVehicle(string make, string model)
            {
                this.make = make;
                this.model = model;
            }
            public virtual void Accelerate()
            {
                Console.WriteLine("In MotorVehicle Accelerate() method");
                Console.WriteLine(model + " accelerating");
            }
        }

        public class Car : MotorVehicle
        {
            public Car(string make, string model)
                : base(make, model)
            {
                //do nothing
            }

            sealed public override void Accelerate()
            {
                Console.WriteLine("In Car Accelerate() method");
                Console.WriteLine(model + " accelerating");
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Creating a Car object");
            Car myCar = new Car("Toyota","MR2");

            Console.WriteLine("Calling myCar.Accelerate()");
            myCar.Accelerate();
            string i = System.Console.ReadLine();
        }
    }
}

posted on 2011-05-03 19:50  孤独的猫  阅读(242)  评论(0编辑  收藏  举报