> For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt.

# Java Interview Question

## 1. Interface vs Abstract Class (Java 11+)

Key difference

| Tiêu chí               | Interface                                              | Abstract Class                              |
| ---------------------- | ------------------------------------------------------ | ------------------------------------------- |
| Đa kế thừa             | Implement multi interface                              |                                             |
| State (instance field) | Chỉ `public static final`                              | Có thể giữ state                            |
| Constructor            | Không có                                               | Có                                          |
| Methods                | `abstract`, `default`, `static` và `private` (java 9+) | `abstract`, concrete, `static`, `final`     |
| Access Modifier        | Luôn public                                            | `public`, `protected`, `private`, `default` |
| Mục đích               | Contract/capability ("can-do")                         | Partial implementation/template (is-a)      |

> Note: Interface không thể giữ state - abstract class thì có. Vì sau java 8 interface có `default` và `static` methods.

### 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 `protected` methods

### 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.
- `private` method 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 `static` method 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.

```
Có shared state không?
├── Có  → Abstract class (hoặc abstract + interface nếu cần đa type)
└── Không
    ├── Chỉ cần contract?  → Interface
    └── Có shared behavior? → Default method trong interface
```
