Can we have two public classes in one file in Java:
This is a common Java interview question. The short answer is No. We can’t define more than one public class in the same file. To understand this, let’s take one example.
Learn with an example:
public class Main {
public static void main(String[] args) {
}
}
public class SecondClass {
public static void main(String[] args) {
}
}
In this example, we created one file Main.java and created two public classes in it. It will throw compile time error. If you are using IntelliJ-Idea, you will see an error as like below:
It is showing an error that the class is public and we should create a new file for that class.
If you click on the More actions button, it will show you two options:
- You can create another file for the second public class or
- You can change it non-public.
So, we can either create a new file or change the class to non-public.
Example 1: Change the class to non-public:
We can change the second class to non-public class and the program will work:
public class Main {
public static void main(String[] args) {
}
}
class SecondClass {
public static void main(String[] args) {
}
}
Note that the name of the file should be the same as the public class. In the above example, the file name should be Main.java as the name of the public class is Main.
Example 2: Use the class as a nested class:
Another way is to use the class as a nested class. We can create one class inside another class. These are called inner and outer class.
public class Main {
public static void main(String[] args) {
}
class SecondClass {
public void main(String[] args) {
}
}
}
Here, Main is the outer class and SecondClass is the inner class. These are called nested class. For example,
public class Main {
public static void main(String[] args) {
}
class SecondClass {
}
class ThirdClass {
}
class FourthClass {
}
}
You might also like:
- Java program to round a number to n decimal places
- Java program to print the vowels in a string
- Java program to print inverted Pyramid patterns in different ways
- Java program to print a diamond pattern with stars
- 2 different Java programs to check for Moran number
- Java program to calculate student grades in 2 different ways
- 3 different Java programs to find the next prime number