Can a file have multiple classes?

QuestionsQuestions8 SkillsProYour First Java LabOct, 02 2025
0113

Yes, a Java file can contain multiple classes. However, there are some important rules to keep in mind:

  1. 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.

  2. 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.

  3. 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.

0 Comments

no data
Be the first to share your comment!