Java – static final vs an instance final when and why? Java interview question


Suppose we have

final double pi = 3.14159
  • Should we make above statement static or not?

  • When we'd want static final vs an instance final?

Best Solution

  1. You should make it static final yes. Possibly public or private... but that's another discussion
  2. In general static finals should be constants or threadsafe objects (such as immutables) that you will construct only once and use across multiple instances of classes.
  3. Instance finals are if you are using it only in that instance, but (wisely) prefer to reduce your state mutability as much as possible.
  4. The two are not necessarily contradictory. For example, you might have a PasswordComplexityPolicy class. This takes a constructor of a bunch of options, all of which are private final instance. But at the top of the class we also have a final public static PasswordComplexityPolicy DEFAULT_POLICY=new PasswordComplexityPolicy(all the stuff needed to construct). Because it's threadsafe, other consumers may choose to use this preconstructed policy rather than build their own. Good for them!