एक ब्लैंक फाइनल वेरिएबल वह final वेरिएबल है जिसे घोषणा पर आरंभ नहीं किया गया है। इसे प्रत्येक कंस्ट्रक्टर में स्पष्ट रूप से आरंभ किया जाना चाहिए क्योंकि:
- कंपाइलर ब्लैंक फाइनल के लिए डिफ़ॉल्ट मान प्रदान नहीं करता।
- प्रत्येक कंस्ट्रक्टर पथ को मान असाइन करना होगा।
- चूकने पर संकलन त्रुटि: "variable might not have been initialized"
उदाहरण: त्रुटि
public class Student {
public final String name; // ब्लैंक फाइनल
public void display() {
System.out.println("Name: " + this.name);
}
public static void main(String args[]) {
new Student().display(); // संकलन त्रुटि
}
}संकलन त्रुटि
Student.java:3: error: variable name not initialized in the default constructor
public final String name;
^सही: सभी कंस्ट्रक्टर में आरंभीकरण
public class Student {
public final String name;
public Student() {
this.name = "Raju"; // कंस्ट्रक्टर 1
}
public Student(String name) {
this.name = name; // कंस्ट्रक्टर 2
}
public void display() {
System.out.println("Name: " + 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
सर्वोत्तम अभ्यास
- संभव हो तो घोषणा पर आरंभ करें।
- एकाधिक कंस्ट्रक्टर के लिए, सामान्य आरंभीकरण के लिए एक निजी हेल्पर विधि या
this()चेनिंग का उपयोग करें।