The de-facto standard in most implementations is that a source file can only contain one top-level public
type definition. The name of the source file must be the name of that type.
A source file can contain nested types, but by definition they're not a top-level public
type.
This is recommended in, but not required by, the Java Language Specification.
When packages are stored in a file system, the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java
or .jav
) if either of the following is true:
- The type is referred to by code in other compilation units of the package in which the type is declared.
- The type is declared
public
(and therefore is potentially accessible from code in other packages).
This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class
within a package; for example, the source code for a public
type wet.sprocket.Toad
would be found in a file Toad.java
in the directory wet/sprocket
, and the corresponding object code would be found in the file Toad.class
in the same directory.
Note that final
has nothing to do with accessibility, so it's not a relevant issue in this matter.
Related questions
See also