Java Reference
In-Depth Information
The
import
keyword is used to import a single class or, when used with the wildcard (*),
an entire package. A source fi le can have any number of
import
statements, and they must
appear after the
package
declaration and before the
class
declaration. Importing classes
and packages tells the compiler that you are not going to use fully qualifi ed names for
classes. The compiler searches your list of imports to determine the fully qualifi ed names of
the classes referenced in the source fi le.
Here is the
CreateEmployee
program again, except this time the
com.sybex.payroll
.Employee
class is imported, allowing the
Employee
class to be referred to without using its
fully qualifi ed name:
import com.sybex.payroll.Employee;
public class CreateEmployee2 {
public static void main(String [] args) {
Employee e = new Employee();
}
}
The output is the same as before:
Constructing a com.sybex.payroll.Employee
In fact, the compiled bytecode fi les
CreateEmployee.class
and
CreateEmployee2.class
are completely identical (except for the number
2
that appears in
CreateEmployee2.class
).
The
import
statement does not affect the compiled code. Behind the scenes, the compiler
removes the
import
statement and replaces each occurrence of
Employee
with
com.sybex
.payroll.Employee
.
What Does Import Mean?
The term
import
sounds like something is being brought into your source fi le, but nothing
is physically added to your source code by importing a class or package. An
import
state-
ment is strictly to make your life as a programmer easier. The Java compiler removes all
import
statements and replaces all the class names in your source code with their fully
qualifi ed names. For this reason, you never need to use
import
statements. Instead, you
can use fully qualifi ed names throughout your source fi les. However, you will quickly
discover the benefi t of
import
statements, especially when you work with long package
names.
The
CreateEmployee
and
CreateEmployee2
programs both refer to the
String
class.
String
is defi ned in the
java.lang
package, but this package was not imported. The
java
.lang
package is unique in that the compiler automatically imports all the public classes and
Search WWH ::
Custom Search