Java Reference
In-Depth Information
instead of
double area = Math.PI * radius * radius;
Wildcards also work in the import static statement:
import static java.lang.Math.*;
For infrequent use, typing the complete name Math.PI is probably easier, but if
constants from another class are used extensively, then the static import feature
saves quite a bit of typing. In addition to the constants, all the many static methods
in the Math class are also available when you use the wildcard static import line
above. For example,
double logarithm = log (number);
instead of
double logarithm = Math.log (number);
Forextensive use of the mathematical functions, the static import feature is a
great addition to the Java language.
As explained in Chapter 4, constants can also be defined in interfaces, where
they are automatically static ,evenifthe static keyword is not used. An
example from Chapter 4 was
public interface MyConstants {
double G = 9.8;
double C = 2.99792458e10;
}
Prior to Java version 5.0, these constants could be accessed with either the
MyConstants.G notation as used above with the Math constants or by imple-
menting MyConstants in the class definition. However, static import also works
fine with a package, as shown here:
import static somepackage.MyConstants;
public class UsesMyConstants {
/** Calculate E = m*c-squared. **/
double calculateEnergy (double mass) {
return = mass*C*C;
}
}
We note that this technique works only if the constants interface is in a package.
That is, classes or interfaces using the default package, which is discouraged
anyway, cannot be statically imported.
It was pointed out in Chapter 4 that using an interface just to access a set
of constants is ill advised and considered bad programming style since nothing
Search WWH ::




Custom Search