using System; public class DrawingObject { public virtual void Draw() { Console.WriteLine("I'm just a generic drawing object."); } }
說明
清單9-1 定義了DrawingObject類。這是個可以讓其他對象繼承的基類。該類有一個名為Draw()的方法。Draw()方法帶有一個virtual修飾符,該修飾符表明:該基類的派生類可以重載該方法。DrawingObject類的 Draw()方法完成如下事情:輸出語句"I'm just a generic drawing object."到控制台。
2.清單9-2. 帶有重載方法的派生類:Line.cs, Circle.cs, and Square.cs
using System; public class Line : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Line."); } }
public class Circle : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Circle."); } }
public class Square : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Square."); } }
using System; public class DrawDemo { public static int Main(string[] args) { DrawingObject[] dObj = new DrawingObject[4]; dObj[0] = new Line(); dObj[1] = new Circle(); dObj[2] = new Square(); dObj[3] = new DrawingObject(); foreach (DrawingObject drawObj in dObj) { drawObj.Draw(); } return 0; } }