Java Reference
In-Depth Information
With these import declarations in place, we can use List to mean the
java.util.List interface. If we actually need to use the java.awt.List class, we
can still do so as long as we include its package name. There are no other naming
conflicts between java.util and java.awt , and their types will be imported “on
demand” when we use them without a package name.
Importing Static Members
As well as types, you can import the static members of types using the keywords
import static . (Static members are explained in Chapter 3 . If you are not already
familiar with them, you may want to come back to this section later.) Like type
import declarations, these static import declarations come in two forms: single static
member import and on-demand static member import. Suppose, for example, that
you are writing a text-based program that sends a lot of output to System.out . In
this case, you might use this single static member import to save yourself typing:
import static java . lang . System . out ;
With this import in place, you can then use out.println() instead of Sys
tem.out.println() . Or suppose you are writing a program that uses many of the
trigonometric and other functions of the Math class. In a program that is clearly
focused on numerical methods like this, having to repeatedly type the class name
“Math” does not add clarity to your code; it just gets in the way. In this case, an on-
demand static member import may be appropriate:
import static java . lang . Math .*
With this import declaration, you are free to write concise expressions like
sqrt(abs(sin(x))) without having to prefix the name of each static method with
the class name Math .
Another important use of import static declarations is to import the names of
constants into your code. This works particularly well with enumerated types (see
Chapter 4 ). Suppose, for example, that you want to use the values of this enumer‐
ated type in code you are writing:
package climate . temperate ;
enum Seasons { WINTER , SPRING , SUMMER , AUTUMN };
You could import the type climate.temperate.Seasons and then prefix the con‐
stants with the type name: Seasons.SPRING . For more concise code, you could
import the enumerated values themselves:
import static climate . temperate . Seasons .*;
Using static member import declarations for constants is generally a better techni‐
que than implementing an interface that defines the constants.
Search WWH ::

Custom Search