抽象类

抽象类密封类
使用 abstract 关键字可以创建不完整且必须在派生类中实现的类和类成员。
使用 sealed 关键字可以防止继承以前标记为 virtual 的类或某些类成员。
抽象类不能实例化。 抽象类的用途是提供一个可供多个派生类共享的通用基类定义。 例如,类库可以定义一个抽象类,将其用作多个类库函数的参数,并要求使用该库的程序员通过创建派生类来提供自己的类实现。
抽象类也可以定义抽象方法。 方法是将关键字 abstract 添加到方法的返回类型的前面。
密封类不能用作基类。 因此,它也不能是抽象类。 密封类禁止派生。 由于密封类从不用作基类,所以有些运行时优化可以略微提高密封类成员的调用速度。
在对基类的虚成员进行重写的派生类上,方法、索引器、属性或事件可以将该成员声明为密封成员。 在用于以后的派生类时,这将取消成员的虚效果。 方法是在类成员声明中将 sealed 关键字置于 override 关键字的前面。

public abstract class Shape
    {
        private string name;

        public string Id
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }

        public Shape(string s)
        {
            Id = s;
        }

        public abstract double Area
        {
            get;
        }

        public override string ToString()
        {
            return Id + " Area = " + string.Format("{0:F2}", Area); 
        }

    }

    public class Square : Shape
    {
        private int side;

        public Square(string id, int _side)
            : base(id)
        {
            this.side = _side;
        }

        public override double Area
        {
            get { return side* side; }
        }
    }

    public class Circle : Shape
    {
        private int radius;

        public Circle(string id, int _radius)
            : base(id)
        {
            this.radius = _radius;
        }

        public override double Area
        {
            get { return radius * radius * 3.14d; }
        }
    }

    public class Rectangle : Shape
    {
        private int width;
        private int length;

        public Rectangle(string id, int _width, int _length)
            :base(id)
        {
            this.width = _width;
            this.length = _length;
        }

        public override double Area
        {
            get { return width * length; }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Shape> shape = new List<Shape>(3);
            shape.Add(new Square("Square",5));
            shape.Add(new Circle("Circle",5));
            shape.Add(new Rectangle("Rectangle",5,6));

            foreach(Shape item in shape)
            {
                Console.WriteLine(item.ToString());
            }
            Console.ReadKey();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值