2.5 Java Source File Structure
The structure of a skeletal Java source file is depicted in Figure 2.2. A Java source file can have the following elements that, if present, must be specified in the following order:
declaration to specify a package
. Packages are discussed in Section 4.6.
Zero or more
declarations introduce class and interface
in the source code, they must be placed before any type declarations. The
statement is discussed in Section 4.6.
Any number of
class and interface declarations. Since these declarations belong to the same package, they are said to be defined at the
, which is the package level.
The classes and interfaces can be defined in any order. Class and interface declarations are collectively known as
. Technically, a source file need not have any such definitions, but that is hardly useful.
The Java 2 SDK imposes the restriction that at the most one
class definition per source file can be defined. If a
class is defined, the file name must match this
class. If the
class name is
, then the file name must be
Classes are discussed in Section 4.2, and interfaces are discussed in Section 6.4.
Figure 2.2. Java Source File Structure
Note that except for the
statements, all code is encapsulated in classes and interfaces. No such restriction applies to comments and white space.