using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Shape{ /** * 抽象形狀類 */ public abstract class Shape { PRivate int edge; //構造函數 public Shape(int edge) { this.edge = edge; } //抽象類實現的方法,子類可以重用 public int GetEdge() { return this.edge; } //抽象方法,子類必須重寫,并在聲明上加上override public abstract int CalcArea(); } /** * 三角形類,繼承自形狀類 */ public class Triangle : Shape { private int bottom; private int height; //構造函數,構造的同時調用父類指定構造器 public Triangle(int bottom, int height) : base(3) { this.bottom = bottom; this.height = height; } //重寫同名方法 public override int CalcArea() { return this.bottom * this.height / 2; } } /** * 矩形類,繼承自形狀類 */ public class Rectangle : Shape { private int bottom; private int height; //構造函數,構造的同時調用父類指定構造器 public Rectangle(int bottom, int height) : base(4) { this.bottom = bottom; this.height = height; } //重寫同名方法 public override int CalcArea() { return this.bottom * this.height; } } class Program { static void Main(string[] args) { //測試,可用父類映射子類 Shape triangle = new Triangle(4, 5); Console.WriteLine(triangle.GetEdge()); Console.WriteLine(triangle.CalcArea()); Shape rectangle = new Rectangle(4, 5); Console.WriteLine(rectangle.GetEdge()); Console.WriteLine(rectangle.CalcArea()); } }}新聞熱點
疑難解答