Java Reference
In-Depth Information
Using Packages
You've been using packages all along in this topic. Every time you use the import com-
mand, and every time you refer to a class by its full package name
( java.util.StringTokenizer , for example), you are using packages.
To use a class contained in a package, you can use one of three techniques:
If the class you want to use is in the package java.lang (for example, System or
Date ), you can simply use the class name to refer to that class. The java.lang
classes are automatically available to you in all your programs.
n
If the class you want to use is in some other package, you can refer to that class by
its full name, including any package names (for example, java.awt.Font ).
n
For classes that you use frequently from other packages, you can import individual
classes or a whole package of classes. After a class or a package has been
imported, you can refer to that class by its class name.
n
If you don't declare that your class belongs to a package, it is put into an unnamed
default package. You can refer to that class and any other unpackaged class simply by its
class name from anywhere in other classes.
Full Package and Class Names
To refer to a class in another package, use its full name: the class name preceded by its
package. You do not have to import the class or the package to use it in this manner, as
in this example:
java.awt.Font text = new java.awt.Font()
For classes that you use only once or twice in your program, using the full name makes
sense. If you use a class multiple times, you can import the class to save yourself some
typing.
When you begin creating your own packages, you'll place all files in a package in the
same folder. Each element of a package name corresponds to its own subfolder.
Consider the example of a BookShipper class that is part of the org.cadenhead.library
package.
The following line should be the first statement in the source code of the class, which
declares the name of the package to which it belongs:
package org.cadenhead.library;
After you compile the BookShipper class, you must store it in a folder that corresponds
with the package name. The JDK and other Java tools will look for the org.cadenhead.
library.BookShipper.class file in several different places:
 
Search WWH ::




Custom Search