以下是调用的代码:
Circle circle = new Circle();
circle.R = 20;
Square square = new Square();
square.Edge = 10;
Rectangle rectangle = new Rectangle();
rectangle.Width = 20;
rectangle.Height = 30;
// 把子类赋给父类,能更好的体现多态性
IList<Shape> shapeList = new List<Shape>();
shapeList.Add(circle);
shapeList.Add(square);
shapeList.Add(rectangle);
foreach (var shape in shapeList)
{
shape.PrintPerimeter(shape.CalculatePerimeter());
shape.PrintArea(shape.CalculateArea());
}
在此例子中,输出形状的周长和面积的方法没有太大作用,是因为方法的具体实现比较简单,如果是复杂的方法时会有很大作用。比如说想要实现拖拽功能,每个形状都是可以拖拽的,而且每个形状拖拽的方法都会是一样的,但是想要实现拖拽功能可不像输出这么简单,这时候子类可以继承父类的方法,直接调用。










