javaconstructorfinal

Final variables "might not have been initialized" in a multiple-constructor class


I have a class with two different final variables and two different constructors.

public class Parent {
    private final String name;
    private final String dob;

    public Parent() {
        System.out.println("no args constructor");
    }

    public Parent(String name, String dob) {
        this.name = name;
        this.dob = dob;
        System.out.println("in parent constructor");
    }
}

Trying to compile or run it throws an error like this:

Parent.java:7: error: variable name might not have been initialized
    }
    ^
1 error
error: compilation failed

Why is my program throwing this error, and how can I fix it?


Solution

  • Populate finalfields by the end of construction

    You have two constructors. One populates the final fields, the other does not. The compiler alerts you to the fact that you neglected to populate the final fields in one of the constructors.

    Being final means a value cannot be assigned later. You must populate final fields by the end of construction.

    Solutions: