Understanding Java Class Declaration Rules
The Problem
If you already know why the following code fails to compile, then you don’t need to continue reading!
|
|
The Rule
The above code fails to compile because there are two public classes declared in a single file. In Java, you can only have one public top-level class per file.
The Solution
If you need to define multiple classes in a single file, you must declare only one public top-level class. For example, this code will successfully compile:
|
|
Understanding the History
The ability to support multiple top-level classes in one file was introduced to maintain compatibility with version 1.0 before nested classes were introduced.
Best Practice
Instead of declaring multiple top-level classes in one file, you can:
- Have one public top-level class
- Use inner classes for support functionality
- Combine the main public class with its related functionality
For more information about inner classes, visit the Java documentation.