Java Reference
In-Depth Information
31. Do not apply public final to constants whose value might change in
later releases
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 JLS [JLS 2013] allows implement-
ations 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 dif-
ferent 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 recom-
piled.
A related error can arise when a programmer declares a static final reference to
a mutable object; see Guideline 73 , Never confuse the immutability of a reference with
that of the referenced object , ” for additional information.
Noncompliant Code Example
In this noncompliant code example, class Foo in Foo.java declares a field whose value
represents the version of the software:
Click here to view code image
class Foo {
public static final int VERSION = 1;
// ...
}
The field is subsequently accessed by class Bar from a separate compilation unit
( Bar.java) :
Click here to view code image
class Bar {
public static void main(String[] args) {
System.out.println("You are using version " + Foo.VERSION);
}
}
When compiled and run, the software correctly prints
Search WWH ::




Custom Search