Abstract Class Versus Interface

Abstract Class vs. Interface

這篇介紹Abstract Class和Interface兩者資料結構的特性以及使用時機。

兩者比較

1
2
3
4
Abstract Class	Interface
可以寫方法內容 只能宣告方法
可以有各種方法 只宣告public方法
單一繼承 多重繼承

使用時機

上方兩者比較除了在繼承輸給Interface之外,Abstract Class還是彈性大。
Abstract Class可以寫預設的方法,又可以讓子類別overwrite。

1
2
3
4
5
6
7
8
9
I.  is a : 用繼承。ex:狗是一種動物
public abstract class Animal{
...
}
public class Dog : Animal{
...
}
II. has a : 用介面。是一種...
III.can do : 用介面。可以....

結論

如果無法判斷使用哪一個資料結構,建議使用Abstract Class。
favor defining classes over interfaces.
use abstract classes instead of interfaces to decouple the contract from implementations.
Abstract classes, if designed correctly, allow for the same degree of decoupling between contract and implementation.
何時使用interface呢? 當需要提供一個多功能value type

1
2
3
public struct Int32 : Icomparable, IFormattable, IConvertible{
...
}