在這最后一個例子中,我們來看看C#的抽象和多態性。首先我們來定義一下這兩個新的術語。抽象(Abstract)通過從多個對象提取出公共部分并把它們并入單獨的抽象類中實現。在本例中我們將創建一個抽象類Shape(形狀)。每一個形狀都擁有返回其顏色的方法,不論是正方形還是圓形、長方形,返回顏色的方法總是相同的,因此這個方法可以提取出來放入父類Shape。這樣,如果我們有10個不同的形狀需要有返回顏色的方法,現在只需在父類中創建一個方法。可以看到使用抽象使得代碼更加簡短。 在面向對象編程領域中,多態性(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() + "."); } }
|