抽象類和抽象方法的實現
抽象類是一種特殊的基礎類,並不與具體的事物聯系。抽象類的定義使用關鍵字abstract。
在類的層次結構中,並沒有“圖形”這樣的具體事物,所以可以將“圖形”定義為抽象類,派生出“圓形”和“四邊形”這樣一些可以具體實例化的普通類,需要注意的是,抽象類不能被實例化,他只能作為其他類的基礎類。將Shape類定位為抽象類代碼如下:
public absract class shape
{
.....
}
在抽象類中也可以使用關鍵字absract定義抽象方法,要求所有的派生非抽象類都要重載實現抽象方法,引入抽象方法的原因在於抽象類本身是一種抽象概念,有的方法並不需要具體實現,而是留下來讓派生類重載實現。Shape類中GetArea方法本身並無具體意義,而只有到了派生類Cricle和Reatangular才可以計算具體面積。
抽象方法為:
public absract double GetArea();
則派生類重載實現為:
public override double GetArea();
{
......
}
下面我們用具體的工程案例講解:---------------------------------------->
首先我們在工程文件中添加一個類 Shape類-------Shape.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace Application27 7 { 8 //定義基類Shape 9 public abstract class Shape 10 { 11 protected string Color; 12 public Shape() { ;} //構造函數 13 public Shape(string Color) { this.Color = Color; } 14 public string GetColor() { return Color; } 15 public abstract double GetArea(); //抽象類 16 } 17 //定義Cirle類,從Shape類中派生 18 public class Circle : Shape 19 { 20 private double Radius; 21 public Circle(string Color, double Radius) 22 { 23 this.Color = Color; 24 this.Radius = Radius; 25 } 26 public override double GetArea() 27 { 28 return System.Math.PI * Radius * Radius; 29 } 30 31 } 32 //派生類Rectangular,從Shape類中派生 33 public class Retangular : Shape 34 { 35 protected double Length, Width; 36 public Retangular(string Color, double Length, double Width) 37 { 38 this.Color = Color; 39 this.Length = Length; 40 this.Width = Width; 41 } 42 public override double GetArea() 43 { 44 return (Length*Width); 45 } 46 47 public double PerimeterIs() 48 { 49 return (2 * (Length * Width)); 50 51 } 54 } 55 //派生類Square,從Retangular類中派生 56 public class Square : Retangular 57 { 58 public Square(string Color,double Side):base(Color,Side,Side) { ;} 59 60 61 } 65 }
這里我們用了abstract定以Shape , 即抽象類
然后我們在主程序中設置
-----------------------Program.cs------------------------------------
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace Application27 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 Circle Cir = new Circle("Orange", 3.0); 13 Console.WriteLine("Circle area is{1}",Cir.GetColor(),Cir.GetArea()); 14 Retangular Rect = new Retangular("Red",13.0,2.0); 15 Console.WriteLine("Retangular Color is {0},Rectangualr area is {1},Rectangualr Perimeter is {2}", 16 Rect.GetColor(),Rect.GetArea(),Rect.PerimeterIs()); 17 Square Squ = new Square("qreen",5.0); 18 Console.WriteLine("Square Color is {0},Square Area is {1},Square Perimeter is {2}",Squ.GetColor(),Squ.GetArea(),Squ.PerimeterIs()); 19 } 20 } 21 }
結果顯示如下: