Practicing some code samples and i have came across this: I have declared final variables at class level and trying to assign values from methods, lead to compile time error(code-2). But from constructor it did get assigned(code-1).
code-1:
class Immutable {
private final int age;
private final String name;
private Immutable(int age, String name) {
this.age = age;
this.name = name;
}
code-2:
class Immutable {
private final int age;
private final String name;
private void me() {
this.age = 19;
this.name = "name";
}
Of-course, they could be assigned at class level too but, not allowed to do in constructors again, since they are allowed to declare only once. But, why are final variables assigned in constructors and not from methods?
Constructors are executed once. Methods can be executed multiple times. Assignments to final variables are only permitted once - it's as simple as that. (If they could be assigned different values after construction, they wouldn't be very "final" would they? C# permits readonly variables to be set multiple times, but still only within the constructor... Java is just a bit stricter than that.)
See more on this question at Stackoverflow