在面向对象编程领域中,多态性(Polymorphism)是对象或者方法根据类的不同而作出不同行为的能力。在下面这个例子中,抽象类Shape有一个getArea()方法,针对不同的形状(圆形、正方形或者长方形)它具有不同的功能。
下面是代码:
public abstract class Shape {
protected string color;
public Shape(string color) {
this.color = color;
}
public string getColor() {
return color;
}
public abstract double getArea();
}
public class Circle : Shape {
private double radius;
public Circle(string color, double radius) : base(color) {
this.radius = radius;
}
public override double getArea() {
return System.Math.PI * radius * radius;
}
}
public class Square : Shape {
private double sideLen;
public Square(string color, double sideLen) : base(color) {
this.sideLen = sideLen;
}
public override double getArea() {
return sideLen * sideLen;
}
}
/*
public class Rectangle : Shape
...略...
*/
public class Example3
{
static void Main()
{
Shape myCircle = new Circle("orange", 3);
Shape myRectangle = new Rectangle("red", 8, 4);
Shape mySquare = new Square("green", 4);
System.Console.WriteLine("圆的颜色是" + myCircle.getColor()
+ "它的面积是" + myCircle.getArea() + ".");
System.Console.WriteLine("长方形的颜色是" + myRectangle.getColor()
+ "它的面积是" + myRectangle.getArea() + ".");
System.Console.WriteLine("正方形的颜色是" + mySquare.getColor()
+ "它的面积是" + mySquare.getArea() + ".");
}
}