Packages and Compilation Units
A package is a name for a group of related classes and interfaces. In Chapter 3, we discussed how Java uses package names to locate classes during compilation and at runtime. In this sense, packages are somewhat like libraries; they organize and manage sets of classes. Packages provide more than just source-code-level organization though. They also create an additional level of scope for their classes and the variables and methods within them. We’ll talk about the visibility of classes later in this section. In the next section, we’ll discuss the effect that packages have on access to variables and methods among classes.
Compilation Units
The source code for a Java class is organized into
compilation units. A simple compilation unit
contains a single class definition and is named for that class. The
definition of a class named MyClass, for instance,
would appear in a
file named
MyClass.java. For most of us, a compilation unit
is just a file with a .java extension, but in an
integrated development environment, it could be an arbitrary entity.
For brevity here, we’ll refer to a compilation unit simply as a
file.
The division of classes into their own compilation units is important because the Java compiler assumes much of the responsibility of a make utility. The compiler relies on the names of source files to find and compile dependent classes. It’s possible (and common) to put more than one class definition into a single file, but there are some restrictions ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access