Java Reference
In-Depth Information
Putting a class in a package has two important side effects that you need to know
for the exam:
1. The fully qualified name of a class or interface changes when it is in a package. The
package name becomes a prefix for the class name. For example, the fully qualified
name of the Employee class shown earlier is com.sybex.payroll.Employee .
2. The compiled bytecode file must appear in a directory structure on your file system
that matches the package name. For example, a .class file for any class or interface
in the com.sybex.payroll package must appear in a directory structure matching
\com\sybex\payroll\ . You can either create this directory structure yourself or use
the -d flag during compilation and the compiler will create the necessary directory
structure for you. We discuss the -d flag in detail later in this section.
The fully qualifi ed name of the Employee class is com.sybex.payroll.Employee . Other
classes that want to use the Employee class need to refer to it by its fully qualifi ed name.
For example, the following program creates an instance of the Employee class:
public class CreateEmployee {
public static void main(String [] args) {
com.sybex.payroll.Employee e =
new com.sybex.payroll.Employee();
}
}
Here's the output of the CreateEmployee program:
Constructing a com.sybex.payroll.Employee
The Unnamed Package
If a class is not specifi cally declared in a package, then that class belongs to the unnamed
package . Classes and interfaces in the unnamed package cannot be imported into a
source fi le. You should only use the unnamed package when writing simple classes and
interfaces that are not being used in a production application. In the real world, you will
rarely write a Java class or interface that is not declared in a package. Your classes will
appear in a package name that contains your company's Internet domain name, which
the next section discusses.
The import Keyword
As you can see by the CreateEmployee program, using the fully qualifi ed name of a class
can be tedious and makes for a lot of typing! The import keyword makes your life as
a coder easier by allowing you to refer to a class in a source fi le without using its fully
qualifi ed name.
Search WWH ::




Custom Search