final (คีย์เวิร์ด)
- ใช้จำกัด class, method, variable
- final class: ไม่สามารถ extends ได้
- final method: ไม่สามารถ override ได้
- final variable: ต้อง initialize ตอนประกาศ ไม่สามารถเปลี่ยนค่าได้
finally (บล็อก)
- บล็อกโค้ดที่ทำงาน เสมอ หลัง try/catch (แม้มี return หรือ exception)
- ใช้สำหรับ cleanup (ปิด resource, connection)
finalize (เมธอด)
- เมธอดของ Object class:
protected void finalize() throws Throwable - ถูกเรียกโดย Garbage Collector ก่อนทำลายออบเจกต์
- ใช้ทำ cleanup ทรัพยากร non-Java (file handles, native resources)
- Deprecated ตั้งแต่ Java 9 ควรใช้ try-with-resources หรือ Cleaner แทน
สรุป
| คำสำคัญ | ประเภท | วัตถุประสงค์ |
|---|---|---|
| final | Keyword | จำกัดการเปลี่ยนแปลง (class/method/variable) |
| finally | Block | รันโค้ด cleanup เสมอหลัง try/catch |
| finalize | Method | Cleanup ก่อน GC ทำลายออบเจกต์ (Deprecated) |