What if there are multiple classes?

QuestionsQuestions8 SkillsProYour First Java LabNov, 29 2025
0101

In Java, if you have multiple classes in a single file, the following rules apply:

  1. Public Class: Only one class in the file can be declared as public, and the name of this public class must match the file name. For example, if you have a public class named MainClass, the file must be named MainClass.java.

  2. Non-Public Classes: Other classes in the same file can be non-public (i.e., package-private by default) and do not need to match the file name. These classes can be accessed only within the same package.

Example:

// File: MainClass.java
public class MainClass {
    public static void main(String[] args) {
        System.out.println("This is the main class.");
        HelperClass helper = new HelperClass();
        helper.display();
    }
}

class HelperClass {
    void display() {
        System.out.println("This is a helper class.");
    }
}

In this example:

  • MainClass is public and must be in MainClass.java.
  • HelperClass is not public and can exist in the same file without needing to match the file name.

Summary:

  • Only one public class per file, matching the file name.
  • Multiple non-public classes can coexist in the same file.

If you have more questions or need further details, feel free to ask!

0 Comments

no data
Be the first to share your comment!