Abstract classes和Interfaces到底差在哪?
在比較他們之前,先來了解他們到底是什麼?
本篇是John影片的筆記
Abstract Classes
定義
該class不能被instantiate,他就像是繼承他的class的藍圖,提供相同的功能與特質。(An abstract class in Java is a class marked with the abstract keyword that cannot be instantiated. It serves as a blueprint for other classes to inherit and provides common functionality or characteristics.)
目的
用來定義屬性和方法好讓subclass繼承,並同時允許subclass實作自己的abstract methods。(They are used to define common attributes or methods that subclasses can inherit while allowing individual implementations of abstract methods.)
特點
- 允許abstract或是已實作的method同時存在
- Abstract methods沒有實作的話,subclass一定要override並實作
- 被subclasses繼承的instance variables不能直接被存取,而是透過getter和setter
- 一個class只能extends一個abstact class
使用情境
- Ideal for defining shared characteristics among subclasses.
- Useful when certain methods should have a common structure but different implementations in subclasses.
例如
Interfaces
定義
用來定義abstract methods,就像是跟實作(implement)了這個interface的classes簽了契約,Methods必須被實作。(An interface in Java declares a set of methods without providing implementations. It’s a contract that specifies a behavior that implementing classes must define.)
目的
為了多重實作,一個class可以implement無限個interface
特點
- 只有method signatures,沒有method bodies
- 支援多重繼承,一個class可以implement無限個interface
- Fields declared in interfaces are by default static and final (constants).
使用情境
- 適合為不相關的classes定義common behaviour,以供他們實作
- Useful when enforcing a certain method signature across different classes
例子
相異之處
Aspect | Abstract Classes | Interfaces |
---|---|---|
Keyword | abstract class ClassName |
interface InterfaceName |
Instantiation | Cannot be instantiated directly. | Cannot be instantiated directly. |
Method Implementation | Can have both abstract and concrete methods. | Contains only method signatures, no method bodies. |
Inheritance | Supports single-class inheritance. | Supports multiple interface inheritance. |
Fields | Can have instance variables (fields). | Fields are by default static and final (constants). |
Access Modifiers | Can have different access modifiers for methods. | Methods are by default public; no other modifiers. |
Usage | Suited for sharing code among related classes. | Ideal for unrelated classes implementing a behavior. |
Flexibility | Provides more flexibility with fields and methods. | Offers less flexibility with constant-like behavior. |