-2

I checked all over the internet if you could reassign final variables in the constructor in java, and everywhere it said it were possible. Yet for me, in eclipse June 2019, it gives me an error when trying to do so:

Here what it gives me

Thank you for your help!

Here is the same code, as text:

public class FinalClass {
  final int n = 5;
}

class InheritedClass extends FinalClass {
    {
        n = 6;
    }
}

which when compiled from command line produces this error:

C:\stuff>javac FinalClass.java
FinalClass.java:7: error: cannot assign a value to final variable n
        n = 6;
        ^
1 error

1 Answers1

3

if you could reassign final variables in the constructor in java, and everywhere it said it were possible

They do say that you can (actually: must) assign to a final field exactly once from the class's own constructor.

They do not say you can reassign a final field, and they do not say you can do it from a subclass constructor. They don't say that, because you cannot.

If you want the value to be optionally specified by a subclass, you need a protected constructor that subclasses can call. And since you cannot reassign a value, you need to write a no-arg constructor to set the default value.

public class FinalClass {
    final int num;

    public FinalClass() {
        this.num = 5; // or: this(5);
    }

    protected FinalClass(int num) {
        this.num = num;
    }
}

public class InheritedClass extends FinalClass {
    public InheritedClass() {
        super(6);
    }
}
Andreas
  • 147,606
  • 10
  • 133
  • 220