Below are important Question & Answers taken from the Q&A discussions in this section.
Q1. Having issues initializing the final variable in the constructor. As you see below, I have declared the final variable at the top and then was initializing it in the constructor but getting below error? Can you help what i am missing here? Thanks!
class Student {
private static int idInitializer = 1000;
private final int id;
private String name;
private String gender = "male";
//char[] grade;
private static int studentCount;
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
// getter method to return Student Count
public static int getStudentCount () {
return studentCount;
}
//constructors
public Student (String name, String gender) {
this(name); // Initializing the constructor. This initialization should always be the first line.
this.gender = gender;
id = ++idInitializer;
studentCount++;
System.out.println("ID of " + name + "is" + id);
}
public Student (String name) {
this.name = name;
}
boolean updateProfile(String name) {
this.name = name;
return true;
}
}ERROR --->
Answer:
Interesting case. In this case, we must use an instance initializer block as follows and also remove id = ++idInitializer; from constructor.
{
id = ++idInitializer;
}With the way your code is what happens if an object is created using only second constructor. In that case id is not getting initialized. But, if you add 'id = ++idInitializer;' to second constructor, then if object is created using first constructor, then id gets incremented second time (wrong as id is final and its value much not change once initialized), i.e., first once in second constructor (as there is this() invocation) and then again in first constructor. So, only option is to do it that way. But, we also know that instance initializer code gets copied to the beginning of every constructor. So, that means the above instance initializer code should get copied into both the constructors, leaving us with the same issue of id getting incremented the second time. But, the thing is when there is a this() invocation, compiler does not copy the instance initializer code into that constructor. So, in your code, compiler copies instance initializer code only into second constructor. If there was no this() invocation statement, then it would copy into both constructors. I also verified this by looking at byte code.