declaring uninitialised final attributes
When creating an immutable object with final member variables which are uninitialised, IntelliJ regards this as an error and generates a compile error.
Is this a feature which is configurable? I need to create threadsafe versions of objects and currently can't do this if I can't declare a final variable without initialising it.
Thanks
Please sign in to leave a comment.
Hello Steve,
This is a restriction of the Java language. You won't be able to compile
this code outside of IntelliJ either.
--
Dmitry Jemerov
Development Lead
JetBrains, Inc.
http://www.jetbrains.com/
"Develop with Pleasure!"
No, that's not true.
This will compile using plain ol' javac
public class test {
private final String x;
public test() {
x = "hello";
}
public String getValue() { return x;
}
public static void main(String []args) {
System.out.println(new test().getValue());
}
}
It won't in IntelliJ.
There are loads of code snippets on the web with examples on creating Immutable objects like this.
The Sun Java Certification also covers questions on this.
Regards
Hello Steve,
OK, I misunderstood what you mean. This code is of course valid, and my IntelliJ
doesn't highlight any errors in it. Which error specifically does it show
on your machine?
--
Dmitry Jemerov
Development Lead
JetBrains, Inc.
http://www.jetbrains.com/
"Develop with Pleasure!"
On Tue, 15 Mar 2011 16:59:19 MSK, Steve Lum <no_reply@jetbrains.com>
wrote, quoted or indirectly quoted someone who said :
>When creating an immutable object with final member variables which are uninitialised, IntelliJ regards this as an error and generates a compile error.
>Is this a feature which is configurable? I need to create threadsafe versions of objects and currently can't do this if I can't declare a final variable without initialising it.
I do this all the time. You must initialise them in the constructor or
in an init block in a way that you can weasel around the init code.
I think you will need to provide a SSCCE to demonstrate the
circumstances under which IntelliJ considers there is an error and
JavaC does not.
see http://mindprod.com/jgloss/sscce.html
--
Roedy Green Canadian Mind Products
http://mindprod.com
Refactor early. If you procrastinate, you will have
even more code to adjust based on the faulty design.
.
You're right, I had a little play and yes the errors are generated when the
variables are initilalised outside the constructor.
I was under the impression a compile error was only generated after the variable was assigned the first time, I guess that was wrong or changed.