Nested class là class được khai báo bên trong body của 1 class, interface… khác
Nested class có thể static hoặc không, trường hợp không static thì còn được gọi là inner class.
Có 3 kiểu inner class
- Inner member class: có thể hiểu là 1 member của class hiện tại (xem lại: https://www.udemy.com/course/java-se-11-developer-1z0-819-ocp-course-part-1/learn/lecture/17189392#overview )
- Local (inner) class được define trong 1 block code (thường là trong body của method) và không phải là member của class hiện tại
- Anonymous class
Đối với static nested class
- Không thể dùng field non-static của top-level class trong nested class (kể cả method, block của nested class là non-static)
- Static nested class có thể khởi tạo instance, không khác gì class bình thường
- Để truy cập member của static nested class, phải sử dụng instance của nested class hoặc thông qua class name với field hoặc methó static của nested class.
- Có thể khai báo Enum, Interface bên trong non-static nested class
Đối với non-static nested class
- Có thể khởi tạo nested class thông qua instance của top-level class
- Có thể dùng field của top-level bên trong nested class. Trường hợp trùng field nếu muốn dùng field của top-level thì cần sử dung TênClass.this.field
- Để sử dụng inner class trong top-level class, phải khai báo field ở top-level class có kiểu là nested class
- Không thể sử dụng static member trong non-static nested class trừ khi là final, kiểu dữ liệu nguyên thuỷ hoặc String (Kiểu wapper cũng không được: Integer, Short, Float…)
- Không thể khai báo Enum, Interface bên trong non-static nested class
- Các class extend top-level class mà có inner class thì được sử dụng lại inner class của top-level class mà không cần thông qua instance của top-level class (trừ block và method static)
- Top-level class không thể extend public inner của top-level class khác.
- inner của top-level class này có thể extend inner của top-level class khác, với điều kiện 2 top-level là parent-child