Example 1:
class Temp {
final int x = getX();
Temp() {
System.out.println("Via Constructor : " + this.x);
}
int getX() {
System.out.println("Via get method : " + this.x);
return 101;
}
public static void main(String[] args) {
new Temp();
}
}
Output:
via get method : 0
Via Constructor : 101
Not clear the first line of output, As final variable can not be reinitialized, It should not show the default value, Please explain, I spent many hours but could not get the satisfied answer.
Example 2:
class Temp {
final int x;
Temp() {
System.out.println("Constructor one : " + this.x);
this.x = 10;
System.out.println("Constructor two : " + this.x);
}
public static void main(String[] args) {
new Temp();
}
}
Output:
Temp.java:5: error: variable x might not have been initialized
System.out.println("Constructor one : " + this.x);
Please compare the both example, I am satisfied with the Example 2, but Example 1 is not clear to me. Please help it would be appreciated.