Java Reference
In-Depth Information
A static import declaration also comes in two flavors: single-static import and static-import-on-demand. A single-
static import declaration imports one static member from a type. A static-import-on-demand declaration imports all
static members of a type. The general syntax of static import declaration is as follows:
Single-static-import declaration:
import static <<package name>>.<<type name>>.<<static member name>>;
Static-import-on-demand declaration:
import static <<package name>>.<<type name>>.*;
You have been printing messages in the standard output using the
System.out.println()
method.
System
is a
class in
java.lang
package that has a
static
variable named
out
. When you use
System.out
, you are referring to that
static
variable
out
of the
System
class. You can use a
static
import declaration to import the
out static
variable
from the
System
class as follows:
import static java.lang.System.out;
Your program now does not need to qualify the
out
variable with the
System
class name as
System.out
. Rather,
it can use the name
out
to mean
System.out
in your program. The compiler will use the
static
import declaration to
resolve the name
out
to
System.out
.
Listing 6-5 demonstrates how to use a static import declaration. It imports the
out static
variable of the
System
class. Note that the
main()
method uses
out.println()
method, not
System.out.println()
. The compiler will
replace the
out.println()
call with the
System.out.println()
call.
Listing 6-5.
Using Static Import Declarations
// StaticImportTest.java
package com.jdojo.cls;
import static java.lang.System.out;
public class StaticImportTest {
public static void main(String[] args) {
out.println("Hello static import!");
}
}
Hello static import!
■
an import declaration imports a type name and it lets you use the type's simple name in your program. What an
import declaration does with a type, a
static
import declaration does with a
static
member of a type. a
static
import
declaration lets you use the name of a
static
member (
static
variable/method) of a type without qualifying it with the
type name.
Tip