Multiple classes in one file in Java

Multiple classes in one file in Java

In this post, we will see how to have multiple classes in one file in java.

Introduction

You need to have any number of classes in a single Java file, but there is a restriction that you can declare only one Java class as public modifier with the main() method and declare (without public) for the remaining classes. Moreover, we have one rule in Java that your filename must be the same as your public class name.

Methods to Implement Multiple Classes In One Java Program

1) Nested classes

A nested class is one type of inner class that accesses other instance variables of an outer class. We can use any access modifiers for the nested inner class such as private, public, protected, or default.

There are two types of nested classes defined in Java.
1.static nested class

  1. non-static nested class.

If You define an inner class with a static keyword, such type of class is said to be a static nested class, and an inner class is also said to be a non-static nested class in Java.

Example

output

Inside Organization class constructor

Total Organization projects: 0
Inside Project class constructor.
Total Company projects: 1
Calling private method of Organization class from Project class
Greetings from private method of Organization class
Inside Project class displayDuration method
Project duration: 10
Inside Project class constructor.
Total Company projects: 2
Calling private method of Organization class from Project classGreetings from private method of Organization class
Inside Project class displayDuration method
Project duration: 20

Explanation of the program

In the above program, we have created outer class Organization, and inside it, we have created an inner class Project*. In the output, we have decided to directly access the methods and variables of an outer class Organization from the inner class Project.


2) Multiple non-static nested classes

The non-static nested class is a class within another class and should be accessible to members of the enclosing class (outer class). This class is also known as an inner class in Java. While an inner class exists within the outer class, you must instantiate the outer class first in order to instantiate the inner class.

Example

Output

Inner class show() method : outer_a = 75

Explanation

In the above program, we have created OuterClass and InnerClass classes, and also defined test()method in OuterClass and show() method in InnerClass. As you can see, we are able to access the outer_a variable directly without creating the object of an outer class.

That’s all about how to have multiple classes in one file in Java

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *