Packages provide a mechanism for grouping together related classes. Organizing your code into packages is somewhat similar to organizing your files in directories. Files that are related, for example assignments for a single class, are grouped together into a single directory. Classes that have a related function are grouped together into a single class. The Java platform provides several built-in packages including the following:
-
java.io - Classes in the java.io package are all related to input and output.
-
java.net - Classes in the java.net package are all related to sending and receiving messages over a network.
-
java.util - Classes in the java.util package are utilities.
It is always good practice to use package names, even for smaller programs.
Naming
Companies often use the reverse of their domain name for packages, for example
com.ibm.XXX.YYY
. The package to which a class belongs is specified as the first line of the java file. The syntax is simply
package
followed by the name:
package cs112.util;
Importing
If one class uses a class in a different package, it must either refer to the class using the
fully qualified name
, import the class, or import the entire package.
Suppose a class C in package X wanted to create an instance of the class
cs112.util.FileOutput
. Using the fully qualified name would look as follows:
cs112.util.FileOutput fo = new cs112.util.FileOutput();
To import the class, you would add the following line at the top of C.java:
import cs112.util.FileOutput;
In this case, you could then create an instance of FileOutput without using cs112.util as part of the type.
To import the entire package, you would add the following line at the top of C.java:
import cs112.util.*;
In this case, you could then use
any
class in the cs112.util package without using the fully qualified name.
Managing Files
Typically, Java source files are stored in a src directory and the compiled class files are stored in a bin directory. If a class C is in the default package, it will be stored in src/C.java. If a class FileOutput is in a package cs112.util, it will be stored in a file FileOutput.java which is stored in src/cs112/util. Similarly, the compiled class file will be stored in bin/cs112/util/FileOutput.class.