Yes, a Java file can contain multiple classes. However, there are some important rules to keep in mind:
-
Public Class: If the file contains a public class, the file name must match the name of that public class. You can have other non-public classes in the same file, but only one public class is allowed.
-
Non-Public Classes: You can define multiple non-public classes in a single file without any restrictions on their names. These classes are accessible only within the same package.
-
Inner Classes: You can also define inner classes (classes defined within another class) in a file. Inner classes can be public, private, or package-private.
Here’s an example:
// File: MyClasses.java
public class MyClass {
// Public class
}
class AnotherClass {
// Non-public class
}
class YetAnotherClass {
// Another non-public class
}
In this example, MyClass is public and must match the file name, while AnotherClass and YetAnotherClass are non-public and can coexist in the same file.
