CSI21M1 Java Programming Notes, prepared by Mr. S. Nyika, Semester I, 2019
Lecture 4: Working with Packages and Using Javadoc to document a Package
Objectives:
At the end of this lecture, students will be able to:
• explain the idea of a package
• create a new package
• add a class to a package
• delete a package
• rename a package
• move a class from one package to another
• navigate existing packages
• understand documentation using javadoc
• create a library for a package
• use a library in an application
Notes:
To make it easy to find and access classes, the Java API organizes its classes into packages. This allows
you to import just the classes and packages that an application needs.
Packages provide two main advantages. First, when a project contains a large number of classes,
packages can provide some logical structure to your application and make it easier to find the classes
that your are looking for. Secondly, packages provide a way to avoid naming conflicts between classes.
This is particularly important if you want to make your classes avaibable to other programmers.
The following shows the directories and files of the StudenApp application
Page 1 of 11
, CSI21M1 Java Programming Notes, prepared by Mr. S. Nyika, Semester I, 2019
Here the project folder, StudentSofware, which has the following directory hierararchy:
contains the subdirectories for each package. Then, each subdirectory contains the classes which define
the business objects for this application.
When you name a package, you can use any name you want. However, if you want to make sure
that the name of your package is unique, its considered a good practice to start the name of your
internet domain name in reverse. For example za.ac.wsu.snyika, so all my classes would be stored
in this package. Even if you do not follow this convention, you should avoid using a general name, for
example a package name snyika would be too general.
Once you store a class in the correct directory, you must code a package statement at the beginning of
the class. This statement consists of the package keyword followed by the name of the package. For
example as shown earlier, the statement in the Student class is package za.ac.wsu.snyika. This
statement will make sure that the folders are created when your program is compiled.
If a class is stored in a package, it cannot be accessed from classes in other packages without qualifying
it with the name of the package. As a result, you typically import the class to make it easier to refer
to. This works the same for the packages and classes that your create as it does for the classes of the
Java API such as JoptionPane.
Page 2 of 11