Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning Final variables from constructors | not allowed from methods. Why?

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?

like image 320
srikanth Avatar asked Mar 15 '26 08:03

srikanth


1 Answers

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.)

like image 148
Jon Skeet Avatar answered Mar 17 '26 20:03

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!