Which two reasons should you use interfaces instead of abstract classes?



A. You expect that classes that implement your interfaces have many common methods or fields, or require access modifiers other than public.
B. You expect that unrelated classes would implement your interfaces.
C. You want to share code among several closely related classes.
D. You want to declare non-static on non-final fields.
E. You want to take advantage of multiple inheritance of type.

題解

選項A,介面定義的成員一定是public可見度,所以這不是正確答案。

選項B,如果說A繼承B是「A是B(A is B)」的關係,那麼A實作B可以說是「A能做到B能做的事(A is capable of doing what B can do)」。也就是說,介面比較像是提供物件功能方面的描述,例如有個介面叫作「Walkable」(能走),定義了「walk」(走路)的方法,然後有個「Human」(人)這個類別,實作了「Walkable」介面。「Human」和「Walkable」並沒有什麼直接的關係,任何類別都可以實作這個介面來表示類別能做到走路這個動作。因此這個選項的敘述是正確的。

選項C,介面除了特殊的預設方法和靜態方法用法之外,是沒辦法共享程式實作的。

選項D,介面的欄位一定會使用public static final來進行修飾。

選項E,一個類別可以實作多個介面。