I know that once a final variable has a value assigned to it, it cannot be changed. However I just have a couple of questions regarding this:
When I have a field, say static final JButton button;
outside a class, and then in the main
method, try to assign it a value, button = new JButton("OK");
, I get an error telling me to remove the final modifier? However since the original button
variable does not yet reference an object I was under the impression I could assign it once?
Secondly, if I completely remove reference to the button
so I just have static final JButton button;
outside the class, my IDE claims "The blank final field button may not have been initialised." Does this mean that all final fields must be initialised? And if so, must they be initialised there and then as I can't seem to initialise it later.
Also, silly question, but my initial assumption that when a final variable is referenced to an instance or data type it can not be assigned to anything else is correct, right?
This code is not complete but is provided to illustrate my point:
public class FinalVarTester {
static final JButton button;
public static void main(String[] args) {
JFrame frame = new JFrame();
Container container = frame.getContentPane();
container.setLayout(new BorderLayout());
button = new JButton("OK");
container.add(button, BorderLayout.SOUTH);
}
}
In Java, the final keyword is used to denote constants. It can be used with variables, methods, and classes. Once any entity (variable, method or class) is declared final , it can be assigned only once. That is, the final variable cannot be reinitialized with another value.
You can declare a variable in any scope to be final. . The value of a final variable cannot change after it has been initialized. Such variables are similar to constants in other programming languages.
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only.
You should initialize a static final variable either in a static initializer, or directly. So either
static final JButton button = new JButton();
or
static final JButton button;
static {
button = new JButton();
}
The Java language specification has some more documentation about it: the section about final variables specifies why you get the compile error:
It is a compile-time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.
and chapter 16 talks about the definite assignment
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With