Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The final keyword can be used to specify constant values (that is, values that cannot change during program execution). However, constants that can change over the lifetime of a program should not be declared public final. The Java Language Specification (JLS) [JLS 2013] allows implementations to insert the value of any public final field inline in any compilation unit that reads the field. Consequently, if the declaring class is edited so that the new version gives a different value for the field, compilation units that read the public final field could still see the old value until they are recompiled. This problem may occur, for example, when a third-party library is updated to the latest version but the referencing code is not recompiled.

A related error can arise when a programmer declares a static final reference to a mutable object ; (see OBJ50-J. Never confuse the immutability of a reference with that of the referenced object for additional information).

Noncompliant Code Example

...

In this compliant solution, the version field in Foo.java is declared private static and accessed by the getVersion() method:

...

Declaring a value that changes over the lifetime of the software as final may lead to unexpected results.

According to §9.3, "Field (Constant) Declarations," of the JLS [JLS 2013], "Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields." Therefore, this guideline does not apply to fields defined in interfaces. Clearly, if the value of a field in an interface changes, every class that implements or uses the interface must be recompiled . See (see MSC53-J. Carefully design interfaces before releasing them for more information).

Constants declared using the enum type are permitted to violate this guideline.

Constants whose value never changes throughout the entire lifetime of the software may be declared as final. For instance, the JLS recommends that mathematical constants be declared final.

Bibliography

...