THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
[3] This function is part of the math library so there's no need to actually do this.

static double tanh(double x) {
return (Math.exp(x) - Math.exp(-x)) /
(Math.exp(x) + Math.exp(-x));
}


The appearance of Math tHRoughout the expression is very distracting and certainly doesn't improve the
readability of the code. To alleviate this problem you can tell the compiler that whenever you refer to the
method exp, you mean the static method Math.exp. You do this with a static import statement:


import static java.lang.Math.exp;


A static import statement must appear at the start of a source file, before any class or interface declarations.
Given the previous static import statement, anywhere we invoke a method exp in our source file it will be
taken to mean Math.exp (assuming we don't hide it with another declaration of expsee "The Meanings of
Names" on page 178). Now we can rewrite our example more clearly as:


static double tanh(double x) {
return (exp(x) - exp(-x)) /
(exp(x) + exp(-x));
}


A static import statement consists of the keyword phrase importstatic , followed by the fully qualified
name of the class or interface you are importing the static member from, a dot and then the static member's
name. Like all statements it is terminated by a semicolon.


A static import on demand statement uses an asterisk (*) instead of a member name. This tells the compiler
that if it finds names that it doesn't know about, it should look at the type given by the static import on
demand statement to see if it has a static member by that name. If so, the compiler will assume that you
intended to refer to the static member. For example, if our hyperbolic tangent function were part of a class that
defined many mathematical functions and used many of the static methods and constants of the Math class,
then we might use a static import on demand statement to import all of those method and constant names:


import static java.lang.Math.*;


When names can be imported in this way it is easier for naming conflicts to occur. There are various rules
about how static import and static import on demand work with each other and with the other names used in
your program. These are explained in more detail in "The Meanings of Names" on page 178.


The use of static imports can help the readability of your code, but if misused they can also make it harder to
understand what your code is doing. When the reader sees Math.exp it is quite evident what is being
referred to, but a simple exp is not so clear. If you have multiple static import on demand statements, the
reader will have to look up each of the types to see if they have a static member named exp. As a general rule
you should use static imports to improve the readability and clarity of your code, not to save yourself some
typing.

Free download pdf