Can we have more than two public Java classes in one file:
This is a common Java interview question. The short answer is No. We cannot define more than one public class in the same file. To understand this, let’s take an 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 made two public classes in it. A compile error will occur. If you use IntelliJ-Ideeyou will see an error message like below:
An error is displayed that the class is public and we need to create a new file for that class.
If you click on the More actions button, two options will be displayed:
- You can create another file for the second public class or
- You can change this non-publicly.
So we can create a new file or change the class to non-public.
Example 1: Change the class to private:
We can change the second class to a 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) {
}
}
Please note that the name of the file must be the same as that of the public class. In the example above, the file name should be Main.java as is the name of the public class Mainly.
Example 2: Use the class as a nested class:
Another way is to use the class as a nested class. We can create a class within 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, Mainly is the outer class and Second class is the inner class. These are called nested classes. For example,
public class Main {
public static void main(String[] args) {
}
class SecondClass {
}
class ThirdClass {
}
class FourthClass {
}
}
C# Tip: DO NOT use nameof to value constants
Programming in C# involves making numerous decisions to ensure code efficiency and maintainability. One common aspect is dealing with constants,…
Can we run a Java program without the main method
Can we run a Java program without the main method? The mainly method is executed when we execute a class in…
Java program to calculate students grades in 2 different ways
Java program to calculate students grades: In this post we will learn different ways to calculate the figure from a student…
C# Tip: LINQ’s Enumerable.Range to generate a range of consecutive numbers
When you need to generate a series of numbers in ascending order, you can simply use a while loop with…
Java String charAt method explanation with examples
Java String charAt method: The signAt method of Java string is used to find a character at a given index. This…
3 Ways to Convert System.nanoTime to Seconds in Java
How to convert System.nanoTime to seconds in Java: In this post we will learn how to convert System.nanoTime Unpleasant seconds in…