Multiple Classes in Java

Multiple Classes in Java

Yes, you can have multiple classes in a single Java file. There are a few key points to understand regarding how multiple classes can be organized and used within a single file:

Multiple Classes in Java

Key Points

  • Public Class: A Java file can have at most one public class. The name of this public class must match the name of the file.
  • Non-Public Classes: You can have multiple non-public classes in the same file. These classes will have package-private access by default.
  • Nested Classes: Classes can also be nested within other classes (inner classes).

Example

Example
```java 
// File: Main.java

// Public class - the file name must be Main.java
public class Main {
    public static void main(String[] args) {
        System.out.println("This is the Main class.");
        
        // Creating an instance of the Helper class
        Helper helper = new Helper();
        helper.displayMessage();
        
        // Creating an instance of the InnerHelper class
        InnerHelper innerHelper = new InnerHelper();
        innerHelper.displayInnerMessage();
    }
}

// Non-public class
class Helper {
    void displayMessage() {
        System.out.println("This is the Helper class.");
    }
}

// Another non-public class
class InnerHelper {
    void displayInnerMessage() {
        System.out.println("This is the InnerHelper class.");
    }
}
```

Explanation

1. Public Class:

  • `Main` is the public class, and the file name is `Main.java`.

2. Non-Public Classes:

  • `Helper` and `InnerHelper` are non-public classes. They do not have any access modifier specified, so they have package-private access by default.

3. Usage:

  • Within the `main` method of the `Main` class, instances of `Helper` and `InnerHelper` are created and their methods are called.

Important Rules

1. File Naming:

  • If there is a public class in the file, the file name must be the same as the public class name with a `.java` extension.

2. Access Modifiers:

  • Only one class can be public in a single Java file.
  • Other classes in the file can be package-private or can have other access modifiers (protected, private) if they are nested classes.

3. Compilation:

  • When compiled, each class in the file generates a separate `.class` file. For example, `Main.class`, `Helper.class`, and `InnerHelper.class` will be generated.

Summary

Yes, you can have multiple classes in a single Java file. Only one of these classes can be public, and the file name must match the public class name. The other classes can be non-public and will have package-private access by default unless specified otherwise. This allows you to organize related classes together in a single file for convenience.

Homepage

Readmore