Java Reference
In-Depth Information
You are using version 1
But if a developer were to change the value of
VERSION
to 2 by modifying
Foo.java
and subsequently recompile
Foo.java
,while failing to recompile
Bar.java
,the software
would incorrectly print
You are using version 1
Although recompiling
Bar.java
solves this problem, a better solution is available.
Compliant Solution
According to §13.4.9, “
final
Fields and Constants,” of the JLS [JLS 2013],
Other than for true mathematical constants, we recommend that source code make
very sparing use of class variables that are declared
static
and
final
. If the read-
only nature of
final
is required, a better choice is to declare a
private static
variable and a suitable accessor method to get its value.
Inthiscompliantsolution,the
version
fieldin
Foo.java
isdeclared
private static
and accessed by the
getVersion()
method:
class Foo {
private static int version = 1;
public static final int getVersion() {
return version;
}
// ...
}
The
Bar
class in
Bar.java
is modified to invoke the
getVersion()
accessor method
to retrieve the
version
field from
Foo.java
:
class Bar {
public static void main(String[] args) {
System.out.println(
"You are using version " + Foo.getVersion()
);