public Classes and One Public Class Per File Rule
You'll learn: Why Java enforces that only one public class can exist per source file and why the filename must match that class's name.
The One Public Class Rule
Java has a strict rule: a source file may contain at most one public class, and if it exists, the filename must match the public class name exactly (including case), followed by .java.
This isn't arbitrary—it's designed to make code predictable and tools efficient. When the compiler or JVM needs to find a class called Customer, it knows exactly where to look: Customer.java. This one-to-one mapping eliminates ambiguity.
Why This Matters
Imagine if Customer.java could contain public class Order. When the compiler searches for Order, where should it look? Without the rule, it would need to scan every .java file—slow and unpredictable.
The rule creates a contract: one public class = one file = filename matches class name.
What About Non-Public Classes?
A single source file can contain multiple classes, but only one may be public. The others must be package-private (no modifier). These "helper" classes are often tightly coupled to the public class and not intended for external use.
// File: Report.java
public class Report {
// This is the public class - filename MUST be Report.java
}
class ReportFormatter {
// Package-private helper class - allowed in same file
}
If you accidentally declare two public classes in one file, the compiler immediately rejects it with an error.
Key Takeaway:
Java requires exactly one public class per source file, and the filename must match that class name precisely—this ensures predictable class lookup and clean code organization.