Java File Structure
This chapter has taken us from the smallest to the largest elements of Java syntax, from individual characters and tokens to operators, expressions, statements, and methods, and on up to classes and packages. From a practical standpoint, the unit of Java program structure you will be dealing with most often is the Java file. A Java file is the smallest unit of Java code that can be compiled by the Java compiler. A Java file consists of:
An optional
package
directiveZero or more
import
orimport static
directivesOne or more type definitions
These elements can be interspersed with comments, of course, but they
must appear in this order. This is all there is to a Java file. All
Java statements (except the package
and
import
directives, which are not true statements)
must appear within methods, and all methods must appear within a type
definition.
Java files have a couple of other
important restrictions. First, each file can contain at most one
class that is declared public
. A
public
class is one that is designed for use by
other classes in other packages. This restriction on public classes
only applies to top-level classes; a class can contain any number of
nested or inner classes that are declared public
.
We’ll see more about the public
modifier and nested classes in Chapter 3.
The
second restriction concerns the filename of a Java file. If a Java
file contains a public
class, the name of the file must be the same as the name of the class, with the extension ...
Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.