Why should a blank final variable be explicitly initialized in all Java constructors?

JavaObject Oriented ProgrammingProgramming

A final variable which is left without initialization is known as blank final variable.

Generally, we initialize instance variables in the constructor. If we miss out they will be initialized by the constructors by default values. But, the final blank variables will not be initialized with default values. So if you try to use a blank final variable without initializing in the constructor, a compile time error will be generated.

Example

 Live Demo

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();
   }
}

Compile time error

On compiling, this program generates the following error.

Student.java:3: error: variable name not initialized in the default constructor
   private final String name;
                        ^
1 error

Therefore, it is mandatory to initialize final variables once you declare them. If more than one constructor is provided in the class, you need to initialize the blank final variable in all the constructors.

Example

 Live Demo

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();
   }
}

Output

Name of the Student: Raju
Name of the Student: Radha
raja
Published on 15-Oct-2019 06:33:03
Advertisements