Java Reference
In-Depth Information
sqrt
(line 9) and
ceil
(line 10)
without
preceding the field names or method names with
class name
Math
and a dot.
Common Programming Error 8.7
A compilation error occurs if a program attempts to import two or more classes'
static
methods that have the same signature or
static
fields that have the same name.
1
// Fig. 8.14: StaticImportTest.java
2
// Static import of Math class methods.
3
4
5
import static
java.lang.Math.*;
public class
StaticImportTest
6
{
7
public static void
main(String[] args)
8
{
9
System.out.printf(
"sqrt(900.0) = %.1f%n"
,
sqrt(
900.0
)
ceil(
-9.8
)
);
10
System.out.printf(
"ceil(-9.8) = %.1f%n"
,
);
11
System.out.printf(
"E = %f%n"
,
E
);
12
System.out.printf(
"PI = %f%n"
,
PI
);
13
}
14
}
// end class StaticImportTest
sqrt(900.0) = 30.0
ceil(-9.8) = -9.0
E = 2.718282
PI = 3.141593
Fig. 8.14
|
static
import of
Math
class methods.
The
principle of least privilege
is fundamental to good software engineering. In the con-
text of an app's code, it states that code should be granted only the amount of privilege
and access that it needs to accomplish its designated task, but no more. This makes your
programs more robust by preventing code from accidentally (or maliciously) modifying
variable values and calling methods that should
not
be accessible.
Let's see how this principle applies to instance variables. Some of them need to be
modifiable
and some do not. You can use the keyword
final
to specify that a variable is
not
modifiable (i.e., it's a
constant
) and that any attempt to modify it is an error. For
example,
private final int
INCREMENT
;
declares a
final
(constant) instance variable
INCREMENT
of type
int
. Such variables can be
initialized when they're declared. If they're not, they
must
be initialized in every construc-
tor of the class. Initializing constants in constructors enables each object of the class to have
a different value for the constant. If a
final
variable is
not
initialized in its declaration or
in every constructor, a compilation error occurs.