What You'll Learn
You'll learn which access modifiers are actually allowed on top-level classes and what each choice means for your class's visibility.
The Rules for Class Access Modifiers
While fields and methods can use all four access levels (private, package-private, protected, and public), top-level classes have only two options:
public– The class is accessible from anywhere- Package-private (default) – The class is only accessible within its own package
You cannot make a top-level class private or protected. Those modifiers only apply to members and nested classes.
Public Classes
public class BankAccount {
private double balance;
// Anyone, anywhere can use this class
}
A public class can be instantiated and used by code in any package. This is the class you want others to rely on—your public API. Important constraint: A public class must be in a file with the same name (BankAccount.java in this example).
Package-Private Classes
class AccountValidator {
// Only classes in this package can see this
}
When you omit the public keyword, the class becomes package-private. It's invisible outside its package—perfect for internal helper classes that support your public classes but shouldn't be directly accessed by external code.
Why the Restriction?
Think of packages as modules or departments in a company. public classes are your customer-facing services—anyone can interact with them. Package-private classes are internal staff—they help get work done but don't deal with outsiders. There's no sensible use case for a completely private top-level class (it would be unusable) or a protected one (that concept only makes sense with inheritance hierarchies).
Key Takeaway: Top-level classes can only be public (visible everywhere) or package-private (visible only within their package). Use public for your API; use package-private for internal helpers.