Variable initialized but javac presents compilation error
Remi Forax
forax at univ-mlv.fr
Tue Jun 7 13:57:12 UTC 2016
Hi Felipe,
given that setX() can be overriden in a subclass of A, your code is not safe.
But it's not what the compiler detects, the compiler only checks that the final fields are initialized in the constructor, not in methods called by the constructor.
cheers,
Rémi
----- Mail original -----
> De: "Felipe Barros Pontes" <felipepontes at copin.ufcg.edu.br>
> À: compiler-dev at openjdk.java.net
> Envoyé: Mardi 7 Juin 2016 15:48:43
> Objet: Variable initialized but javac presents compilation error
> Hi all.
> The Java Language Specification 8 presents in section 8.3.1.2 (final Fields)
> the following note: "A blank final instance variable must be definitely
> assigned at the end of every constructor of the class in which it is
> declared, or a compile-time error occurs..."
> In the following program the variable "x" is initialized at the end of the
> constructor but javac presents a compilation error.
> Program
> class A {
> final int x;
> A() {
> setX();
> }
> void setX() {
> this.x = 10;
> }
> }
> Result
> A.java:7: error: cannot assign a value to final variable x
> this.x = 10;
> ^
> 1 error
> Shouldn't it be compiled successfully?
> Best regards,
> Felipe Pontes
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/compiler-dev/attachments/20160607/f689d378/attachment-0001.html>
More information about the compiler-dev
mailing list