Java Reference
In-Depth Information
statement at the top of the file, even before any
import
statements or the class's
header. A package declaration has the following syntax:
package
<name>
;
For example, to specify that the class
CardGame
belongs to the
homework4
pack-
age, you would write the following statement at the top of the
CardGame.java
file:
package homework4;
import java.io.*;
import java.util.*;
// This class represents the main card game logic.
public class CardGame {
...
}
Packages may be nested, indicated by dots. The packages in the Java class
libraries are nested at least two levels deep, such as
java.util
or
java.awt.event
.
For example, to specify that a graphical user interface file for Homework 4 belongs
to the
gui
subpackage within the
homework4
package, you would write the following
statement:
package homework4.gui;
...
Packages are reflected by the directory structure of the files in your Java project.
For example, if a file claims to belong to the
homework4
package, it must be placed
in the
homework4/
directory relative to the root directory of your project. A file in
the
homework.gui
package must be in the
homework4/gui
directory relative to the
project's root.
If you write classes that are part of different packages and a class from one pack-
age wants to use a class from another, you must use an import statement for the com-
piler to find the classes. Remember that packages are not nested, so importing the
homework4
package does not automatically import
homework4.gui
and vice versa.
package general;
import homework.*;
import homework.gui.*;
...
Packages are generally not necessary for small projects, though some editors add
them to the top of all files automatically. Users of basic Java IDEs or text editors
Search WWH ::
Custom Search