คำสำคัญ this ใน Java ใช้เป็นอ้างอิงไปยัง ออบเจ็กต์ปัจจุบัน (current object) ภายใน instance method หรือ constructor ใช้เข้าถึงสมาชิกของคลาส: constructor, ตัวแปร, เมธอด
กำหนด Reference ให้ this ได้หรือไม่?
ไม่ได้ ตามนิยาม this เป็นคีย์เวิร์ด (keyword) ไม่ใช่ตัวแปร ค่าของมัน คงที่ (fixed) ชี้ไปที่ออบเจ็กต์ปัจจุบันเสมอ จึง ไม่สามารถกำหนดค่าใหม่ได้
ถ้าพยายามกำหนด จะเกิด Compile-time Error
ตัวอย่างที่ทำให้ Compile Error
public class ExampleClass {
private String name;
private int age;
public ExampleClass(String name, int age) {
this.name = name; // OK: this.name = field
this.age = age;
}
public void display() {
this = new ExampleClass("krishna", 23); // COMPILE ERROR!
}
}
Error Message
ExampleClass.java:14: error: cannot assign a value to final variable this
this = new ExampleClass("krishna", 23);
^
1 error
การใช้งาน this ที่ถูกต้อง
- this.field - อ้างอิง instance variable (แยกจาก parameter)
- this.method() - เรียก instance method
- this() - เรียก constructor อื่นในคลาสเดียว (constructor chaining)
- return this - คืนออบเจ็กต์ปัจจุบัน (method chaining)
- synchronized(this) - lock บนออบเจ็กต์ปัจจุบัน
สรุป
this เป็น final reference ไม่สามารถเปลี่ยนค่าได้ มันชี้ไปที่ออบเจ็กต์ที่กำลังทำงานอยู่เสมอ