Although classes are the central unit of
object-oriented design in Java, packages provide an additional
level of organizational support. Packages are used to store sets
or related classes and interfaces. (packages usually correspond
to a directory in which you store your class files). As such,
packages define relationships between classes and how they
should work together. They also protect the name space since
they provide the JVM another way to identify classes by
name. Thus, you may have two classes of the same name so long
as they reside in separate packages.
You can specifically define a package
name using the "package" keyword on the first line of a
class such as in:
package myPakage;
Another benefit of using packages is it
allows you to reference entire packages of classes using the "import"
keyword. Thus, rather than specifying a class absolutely, you
can import its package and reference it relative to its package.
Thus, you often see the line:
import java.awt.*;
In this case, you can use any class in
the awt package using only its name. Consider the following
code:
import java.applet.*;
public class myApplet extends Applet
{
.. code...
}
Without the import, you would need to
write the following:
public class myApplet extends java.applet.Applet
{
.. code...
}
Note that you
get all the classes in java.lang for free since it is
loaded automatically by the JVM
Relationships between classes are
also handled by modifiers or access specifiers. We'll talk
about this in just a minute.