Java Interview Question
1. Interface vs Abstract Class (Java 11+)
Key difference
Note: Interface không thể giữ state - abstract class thì có. Vì sau java 8 interface có
defaultvàstaticmethods.
Khi nào dùng gì?
Interface:
- Định nghĩa capability cho nhiều class không liên quan (
Comparable,AutoCloseable) - Cần đa kế thừa type
- Public API contract cho bên thứ ba implement
- Functional interface cho lambda Abstract Class:
- Các subclass chia sẻ state chung
- Template method pattern (
HttpServlet.service()→doGet/doPost) - Cần constructor để enforce invariant
- Cần
protectedmethods
Tips
- Ưu tiên Interface để decouple, chỉ dùng abstract class khi có 3 subclass chia sẻ state hoặc logic chung không đáng kể.
- Đừng quên Interface field là public static final -> vô tình expose constant.
privatemethod không phải abstract - vì subclass không thể override cái nó không thấy.- Vì sao cần private method trong interface? để tái sử dụng code giữa các default/static method mà không expose ra ngoài. trước java 9 muốn chia sẻ logic thì phải tạo
staticmethod nhưng như vậy nó thành public api.
Ví dụ với Articles, BlogPosting và NewsArticle
Khi implement seo schema cho 2 loại page thì dùng interface hay abstract class.