Computer Science Department, Bucknell University
Packages in Java
CSCI 479 Computer Science Design
Fall, 2009
In Java, a package is a collection of classes. They are used to
organize a large collection of classes into hierarchical groups. By
specifying the package name, you can avoid conflicts when classes
have the same name.
If you intent to share your Java classes with the world, it is
suggested that you use your host's domain name in reverse as the start
of your package name. For example, "edu.bucknell.hyde".
Reference: pages 346-352 in Java: How to Program by Deitel
and Deitel, 8th edition, Prentice Hall, 2009 (pages 402-408 in 7th edition).
- To create a small personal library in a package, include a
"package" statement before any imports in each of the library classes.
package edu.bucknell.hyde;
// imports
public class Node {
// ...
}
- Create a directory structure that matches the package name.
Assume we are in working directory WORK. Under WORK, we would have the
following directory structure.
WORK
edu
bucknell
hyde
- Compile each of your library programs in the WORK directory using -d
option. The period means to use the current directory.
javac -d . Node.java
This will place all the .class files in "hyde" directory.
- To use the classes in your new personal library. Add the
following import statement which includes your package name and the
class name.
import edu.bucknell.hyde.Node;
public class LinkedList {
Node p, q, r;
// ...
}
- Compile and run the program in the WORK directory.
javac LinkedList.java
java LinkedList
Page maintained by Dan Hyde, hyde at bucknell.edu Last update
October 4, 2009
Back to
CSCI 479's home page.