Java Reference
In-Depth Information
2.9. Importing Static Member Names
Static members should generally be referenced using the name of the
class to which the static member belongs, as in System.out or Math.sqrt .
This is usually the best practice because it makes clear what your code is
referring to. But using the name of the class every time you reference a
static field or method can sometimes make your code cluttered and more
difficult to understand. For example, suppose you needed to define the
mathematical function to calculate the hyperbolic tangent ( tanh ). [3] This
can be calculated using the Math.exp function:
[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 im-
port 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 exp see " The Meanings of Names " on page 178 ) . Now we
can rewrite our example more clearly as:
 
 
Search WWH ::




Custom Search