Must the accessibility of any other top-level class in the same .java file be either private
or protected
?
Obviously not, as your questions compilation error has already told you that private
is not valid for a top-level class.
The Java Language Specification 7.6 Top Level Type Declarations answers your question:
In the absence of an access modifier, a top level type has package access: it is accessible only within compilation units of the package in which it is declared (§6.6.1). A type may be declared public
to grant access to the type from code in other packages.
It is a compile-time error if a top level type declaration contains any one of the following access modifiers: protected
, private
, or static
.
So, neither private
nor protected
is even allowed for top-level classes.
The specification goes on to say:
If and only if packages are stored in a file system (§7.2), 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 Java compiler to find a named class within a package. In practice, many programmers choose to put each class or interface type in its own compilation unit, whether or not it is public or is referred to by code in other compilation units.
As you can see, a public
top-level class must be named the same as the source file. There can then of course only be one public
top-level class per file.
Any non-public
top-level classes must be what is commonly referred to as package-private, i.e. it must not have an access modifier.
Access modifiers are defined in Chapter 6. Names:
In the absence of an access modifier, most declarations have package access, allowing access anywhere within the package that contains its declaration; other possibilities are public
, protected
, and private
.