在本文中,咱們討論OOP中的熱點之一:抽象類。抽象類在各個編程語言中概念是一致的,可是C#稍微有些不同。本文中咱們會經過代碼來實現抽象類,並一一進行解析。編程
在微軟的MSDN中,對抽象類有以下的定義:編程語言
用abstract 關鍵字可定義抽象類,要求其子類必須實現抽象類的函數、屬性等。抽象類不可被實例化。抽象類提供了統一的定義,用於其不一樣子類直接共享數據、函數。 抽象類也可定義抽象函數。ide
在Visual Studio中添加Console程序,並命名爲「InheritanceAndPolymorphism
」,添加ClassA.cs,添加抽象類ClassA。函數
Main(=
編譯報錯:spa
Compile time error: Cannot create an instance of the abstract class or interface 'InheritanceAndPolymorphism.ClassA'code
結論:沒法用new關鍵字來實例化一個抽象類。對象
給抽象類ClassA添加一些非抽象函數的代碼:blog
Main(=
編譯,依然報錯。 抽象類不管是否有抽象、非抽象函數,均沒法經過new關鍵字來實例化。繼承
咱們把抽象類做爲基類,添加ClassB—使之繼承自ClassA。get
Main(=
編譯的結果:再也不報錯。
結論:一個類能夠繼承自abstract 修飾的抽象類,且可被new關鍵字初始化。
在ClassA中聲明YYY函數--無函數體。
Main(=
編譯,結果報錯:
Compile time error: 'InheritanceAndPolymorphism.ClassA.YYY()' must declare a body because it is not marked abstract, extern, or partial
結論是須要對YYY添加函數體,或者添加abstract的修飾符。
在ClassA的YYY前,添加abstract修飾符。
Main(=
編譯結果,報錯:
Compiler error: 'InheritanceAndPolymorphism.ClassB' does not implement inherited abstract member 'InheritanceAndPolymorphism.ClassA.YYY()'
結論:咱們在abstract 類中聲明瞭一個
abstract 的函數,可是並未在其子類ClassB中實現其內容;當使用new關鍵字初始化ClassB的時候則會報錯----沒法使用new關鍵字初始化一個
abstract類。
在子類中添加YYY的實現。
Main(=
編譯結果,報錯:
Compile time error: 'InheritanceAndPolymorphism.ClassB' does not implement inherited abstract member 'InheritanceAndPolymorphism.ClassA.YYY()' Compile time warning: 'InheritanceAndPolymorphism.ClassB.YYY()' hides inherited member 'InheritanceAndPolymorphism.ClassA.YYY()'.
結論:要使得子類繼承基類的YYY函數,須要用到override關鍵字,而後才能夠用new關鍵字實例化ClassB。
咱們再看看這些代碼:
Main(=
編譯,結果報錯:
Compiler error: 'InheritanceAndPolymorphism.ClassA.YYY()' is abstract but it is contained in non-abstract class 'InheritanceAndPolymorphism.ClassA'
結果分析:聲明abstract的函數,必須同時聲明類爲
abstract。
abstract 的函數不能同時添加static或virtual關鍵字。
Main(=
編譯,結果報錯:
Compile time error : Cannot call an abstract base member: 'InheritanceAndPolymorphism.ClassA.YYY()'
結果分析:ClassB中沒法使用base調用基類的abstract函數--由於其不存在。
最後一個問題,能否在抽象類中添加sealed關鍵字,結果是不能夠。
抽象類不能添加sealed、static類修飾符的。
經過下面幾點,概括一下本文的結論。
沒法使用new來實例化abstract 抽象類
abstract 抽象類能夠有子類,其子類實現抽象方法後,可被new實例化對象
如聲明瞭
abstract 的函數,則必須聲明
abstract 的類
當override抽象基類,沒法修改基類函數的簽名
abstract函數,沒法同時添加static、virtual關鍵字
abstract 類沒法被聲明爲sealed、static類
原文連接:Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Classes in C#)