直播中
在面向?qū)ο缶幊填I(lǐng)域中,多態(tài)性(Polymorphism)是對象或者方法根據(jù)類的不同而作出不同行為的能力。在下面這個(gè)例子中,抽象類Shape有一個(gè)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() + ".");
}
}