Search code examples
javainitializationfinal

Is there a difference between directly assigning a final variable and assigning a final variable in the constructor?


is there a difference between these two initializations of the final variable value?

class Test {
    final int value = 7;
    Test() {}
}

and

class Test {
    final int value;
    Test() {
        value = 7;
    }
}

--

EDIT: A more complex example, involving subclasses. "0" is printed to stdout in this case, but 7 is printed if i assign the value directly.

import javax.swing.*;
import java.beans.PropertyChangeListener;

class TestBox extends JCheckBox {

    final int value;

    public TestBox() {
        value = 7;
    }

    public void addPropertyChangeListener(PropertyChangeListener l) {
        System.out.println(value);
        super.addPropertyChangeListener(l); 
    }

    public static void main(String... args) {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        frame.setContentPane(panel);
        panel.add(new TestBox());
        frame.pack();
        frame.setVisible(true);
    }
}

Solution

  • Tried with a very simple example and yes, when value is accessed in the parent's constructor it is unitialized (as it should be), unless it's final and initialized when declared. The process is that described by EJP, but with a #0 step: finals are initialized with the specified value, if any.