In Java, if you have multiple classes in a single file, the following rules apply:
-
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 namedMainClass, the file must be namedMainClass.java. -
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:
MainClassis public and must be inMainClass.java.HelperClassis 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!
