Variable initialized but javac presents compilation error
Shafi Ahmad
shafi.s.ahmad at oracle.com
Wed Jun 8 05:20:59 UTC 2016
Hi Felip,
I am not a java language expert but trying to answer your query.
It seems to me that the javac compiler error is perfectly correct.
“instance variable must be definitely assigned at the end of every constructor of the class in which it is declared”
It should be assigned directly or through the instance initialization block only not indirectly through method call.
Suppose the compiler compiles your code successfully, in that case how compiler restrict that your method setX() is getting called exactly once otherwise attribute final will lose its meaning.
To avoid such ambiguity the compiler doesn’t allow final variable initialization inside method and even inside try block within a constructor.
import java.io.*;
import java.util.*;
public class ObjIn {
final int x;
public ObjIn() {
ObjectInputStream s = null;
// x = 10; // No error
try {
x = 10; // Error
FileInputStream f = new FileInputStream ("date.ser");
s = new ObjectInputStream (f);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main (String args[]) {
new ObjIn();
}
}
Regards,
Shafi
From: Felipe Barros Pontes [mailto:felipepontes at copin.ufcg.edu.br]
Sent: Tuesday, June 07, 2016 7:19 PM
To: compiler-dev at openjdk.java.net
Subject: 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/c08385df/attachment.html>
More information about the compiler-dev
mailing list