ตัวแปรสุดท้ายที่เหลือโดยไม่มีการเริ่มต้นเรียกว่า ตัวแปรสุดท้ายที่ว่างเปล่า .
โดยทั่วไป เราเริ่มต้นตัวแปรอินสแตนซ์ในตัวสร้าง หากเราพลาด คอนสตรัคเตอร์จะถูกเริ่มต้นโดยค่าเริ่มต้น แต่ตัวแปรว่างสุดท้ายจะไม่ถูกเริ่มต้นด้วยค่าเริ่มต้น ดังนั้น หากคุณพยายามใช้ตัวแปรสุดท้ายที่ว่างเปล่าโดยไม่ได้กำหนดค่าเริ่มต้นในตัวสร้าง จะเกิดข้อผิดพลาดในการคอมไพล์ขึ้น
ตัวอย่าง
public class Student {
public final String name;
public void display() {
System.out.println("Name of the Student: "+this.name);
}
public static void main(String args[]) {
new Student().display();
}
} ข้อผิดพลาดในการคอมไพล์เวลา
ในการคอมไพล์ โปรแกรมนี้สร้างข้อผิดพลาดดังต่อไปนี้
Student.java:3: error: variable name not initialized in the default constructor private final String name; ^ 1 error
ดังนั้นจึงจำเป็นต้องเริ่มต้นตัวแปรสุดท้ายเมื่อคุณประกาศ หากมีตัวสร้างมากกว่าหนึ่งตัวในคลาส คุณจะต้องเริ่มต้นตัวแปรสุดท้ายที่ว่างเปล่าในตัวสร้างทั้งหมด
ตัวอย่าง
public class Student {
public final String name;
public Student() {
this.name = "Raju";
}
public Student(String name) {
this.name = name;
}
public void display() {
System.out.println("Name of the Student: "+this.name);
}
public static void main(String args[]) {
new Student().display();
new Student("Radha").display();
}
} ผลลัพธ์
Name of the Student: Raju Name of the Student: Radha