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!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// File: MyClass.java
public class MyClass {
    // field, constructor, and
    // method declarations
}

public class MyClass2 {
    // field, constructor, and
    // method declarations
}

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// File: MyClass.java
public class MyClass {
    // field, constructor, and
    // method declarations
}

class MyClass2 {
    // field, constructor, and
    // method declarations
}

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:

  1. Have one public top-level class
  2. Use inner classes for support functionality
  3. Combine the main public class with its related functionality

For more information about inner classes, visit the Java documentation.