final variable assignment: at declaration or in constructor?

constants, java, static, variables

Solution

If the field is a constant, make it a `static final` member of the class,

public class Foo{
    public static final int BAR = ...;
}

Otherwise, initialize the field in the constructor.

Problem

First of all this is NOT an exact duplicate of Initialize final variable before constructor in Java. It is probably related, but there aren't any answers that satisfy me. My problem is about final variables in Swing GUI's. It's about custom `Action`s in particular. I have a number of `final` variables and a number of `static final` variables. The question is: if the variable is actually a constant, what is better: initialise them at construction-time, or initialise them at declaration? The answers on the question I mentionned above generally point towards making the variable `static` as soon as you are able to assign it when you declare it. That doesn't really make sense to me, as the variables aren't used in a static context. I have a couple of Images that my form uses like icons, I made those static because an Image simply is a static thing unless your application modifies them. That makes sense. On the other hand, the `Action`s are new instances of a custom inner class. Very technically they are static too, but it just feels different. They simply mustn't be available in static context imo. So do I put: ``` private final CustomAction customAction = new CustomAction(); ``` Or do I initialise it in the constructor? Which is better? Or am I thinking the wrong way about `static`?

Original source

Related problems