继承(八):abstract和override实现继承的多态性

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

namespace AbstractDemo
{
    
    public abstract class Sharp
    {
        //1.抽象方法,不含主体
        //2.必须由派生类以override方式实现此方法
        //3.抽象方法所在类必须为抽象类
        public abstract void GetArea();

    }
    public class Circle : Sharp
    {
        private double r;
        public Circle(double r)
        {
            this.r = r;
        }
        public override void GetArea()
        {
            Console.WriteLine("圆形面积是:{0}", Math.PI * Math.Pow(r, 2));
        }
    }
    public class Square : Sharp
    {
        private double a;
        public Square(double a)
        {
            this.a = a;
        }
        public override void GetArea()
        {          
            Console.WriteLine("正方形面积是:{0}", Math.Pow(a, 2));
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Sharp[] sharps=new Sharp[2];
            sharps[0]= new Square(2);
            sharps[1] = new Circle(4);
            for (int i = 0; i < sharps.Length; i++)
            {
                sharps[i].GetArea();
            }          
            Console.ReadKey();
        }
    }
}

posted @ 2011-03-10 14:58  焦涛  阅读(313)  评论(0)    收藏  举报