C#继承抽象类,实现抽象方法

对于平面图形(Shape),都拥有面积(Area)和周长(Circumference)这两个属性。而对于不同的图形,如圆形(Circle)、正方形(Square)、三角形(Triangle)、长方形(Rectangle)都有各自的面积和周长的计算方法。(请注意,正方形是长方形的子类!)

(1)构造一个抽象类Shape,拥有两个抽象方法:计算面积(GetArea)和计算周长(GetCircumference)

(2)完成圆形、正方形、三角形、长方形对应的类,并继承自抽象类Shape,实现抽象方法

(3)将各图形必要的参数(如长、高、半径),通过构造函数传入,保存到相应的属性中

(4)定义一个方法,参数为一个Shape实例,方法向控制台中打印该图形的面积和周长

(5)创建各个形状的实例,在控制台中打印出各种形状的面积和周长

 

using System;

namespace Shape
{
    public abstract class Shape
    {
        public abstract double GetArea();
        public abstract double GetCircumference();
    }
    public class Circle : Shape
    {
        public double x { get; set; }
        public override double GetArea()
        {
            return Math.Round(Math.PI * Math.Pow(x, 2), 4);
        }
        public override double GetCircumference()
        {
            return Math.Round(2 * x * Math.PI, 4);
        }
    }
    public class Rectangle : Shape
    {
        public double x { get; set; }
        public double y { get; set; }
        public Rectangle(double x, double y)
        {
            this.x = x;this.y = y;
        }
        public override double GetArea()
        {
            return x * y;
        }
        public override double GetCircumference()
        {
            return (x + y) * 2;
        }
    }
    public class Square : Rectangle { public Square(double x) : base(x, x) { } }

    public class Triangle : Shape
    {
        public double x { get; set; }
        public double y { get; set; }
        public double z { get; set; }
        public Triangle(double x, double y, double z)
        {
            if (x + y > z && x + z > y && y + z > x)
            {
                this.x = x;this.y = y;this.z = z;
            }
            else Console.WriteLine(x+","+y+","+z+ "无法构成三角形!");
        }
        public override double GetArea()
        {
            double p = (x + y + z) / 2;
            return Math.Round(Math.Sqrt((p * (p - x) * (p - y) * (p - z))), 4);//保留4位小数,保留位数改这里
        }
        public override double GetCircumference()
        {
            return x + y + z;
        }
    }


    class Program
    {
        public static void ShowInfo(Shape p)
        {
            Console.WriteLine(String.Format("{0,-15}{1}", "周长:" + p.GetCircumference(), "面积:" + p.GetArea()));
        }
        static void Main(string[] args)
        {
            ShowInfo(new Circle { x=5 });
            ShowInfo(new Rectangle(4, 5));
            ShowInfo(new Square(4));
            ShowInfo(new Triangle(3, 4, 5));
            Console.ReadKey();
        }
    }
}

感谢