基类描述共性,派生类给出差异

同一个 Shape 数组里放入 Circle 和 Rectangle,调用 Describe 和 Area 时由运行时类型决定具体结果。

Shape 继承树

基类变量能引用派生类对象;虚成员调用时按运行时类型分派。

对应代码

public abstract class Shape
{
    public string Color { get; init; } = "Black";
    public abstract double Area { get; }
    public virtual string Describe() => $"{Color} shape";
}

public sealed class Circle : Shape
{
    public Circle(double radius) => Radius = radius;
    public double Radius { get; }
    public override double Area => Math.PI * Radius * Radius;
    public override string Describe() => $"{Color} circle r={Radius}";
}

public sealed class Rectangle : Shape
{
    public Rectangle(double width, double height)
    {
        Width = width;
        Height = height;
    }

    public double Width { get; }
    public double Height { get; }
    public override double Area => Width * Height;
    public override string Describe() => $"{Color} rectangle {Width}x{Height}";
}