Java Reference
In-Depth Information
Classroom Q & A
Q: You said every class is in a package. What package are all the
classes we have written so far in?
A: Good question. You use the package keyword to declare a class in
a package, and I haven't shown you how to do this yet. If you do
not explicitly declare a class in a package, the class belongs to the
default package . The default package contains every Java class
ever written that does not use the package keyword, and that
includes every class we have written so far.
Q: Is there something wrong with having a class in the default package?
A: It's not the end of the world, but I will say this: If you write a Java
class for a real-world application (as opposed to code you are just
playing around with or learning with), you will declare the class in
a package. Packages are a fundamental but essential part of the
Java language.
Q: Why are packages necessary? What if I have a small program that
is only a dozen classes?
A: Packages are more than just a mechanism for organizing your
classes. A more important aspect of packages is the namespace
they create. For example, suppose that your small program contains
a class named Vehicle. What if I wrote a Vehicle class as well? How
would you be able to tell them apart? What if someone wanted to
use my Vehicle class and your Vehicle class in their program?
Q: I have seen this problem before. Why don't you change the names
of the classes, such as Vehicle1 and Vehicle2?
A: No thanks. I would have to rewrite and recompile a bunch of code,
and with packages I don't have to worry about it. If the two Vehi-
cle classes are in different packages (which they will be, see the
sidebar on package names), my Java program can distinguish the
two Vehicle classes. I will discuss the namespace feature of pack-
ages in detail after I show you how to create a package and put
classes in it.
Adding a Class to a Package
A class is added to a package using the package keyword. The package state-
ment must be the first statement in your source code file (except for comments).
For example, suppose we wanted to create a package named payroll for the
Employee, Salary, and Hourly classes used in our program to pay employees.
Search WWH ::




Custom Search