Java Reference
In-Depth Information
public static void main(String[] args) {
if (Flags.debug)
System.out.println("debug is true");
}
}
is compiled and executed, it produces the output:
debug is true
Suppose that a new version of class
Flags
is produced:
class Flags { static final boolean debug = false; }
If
Flags
is recompiled but not
Test
, then running the new binary with the existing binary
of
Test
produces the output:
debug is true
because the value of
debug
was a compile-time constant expression, and could have
been used in compiling
Test
without making a reference to the class
Flags
.
This behavior would not change if
Flags
were changed to be an interface, as in the
modified example:
interface Flags { boolean debug = true; }
class Test {
public static void main(String[] args) {
if (Flags.debug)
System.out.println("debug is true");
}
}
The best way to avoid problems with “inconstant constants” in widely-distributed code is
to declare as compile-time constants only values which truly are unlikely ever to change.
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 meth-
od to get its value.
Thus we recommend:
private static int N;
public static int getN() { return N; }
rather than: