We can have more than one class in a single java source file but with certain restriction.

Among multiple classes that you create in a single source file, only one can be public. Find an example given below,

package basic;
public class MultiplePublic {
      public static void main(String[] args) {
            //By java radar
            System.out.println(“Executing main method”);
            AnotherMultiplePublic amp = newAnotherMultiplePublic();
classAnotherMultiplePublic {

      public void sampleMethod(){
            System.out.println(“Print sample method”);


Executing main method

Print sample method

As shown above, write both classes in same source file with MultiplePublic class being public. As stated above if only one class is declared public then the code will run fine. So in this case the code will be executed without any glitches and produce output as stated under output header.

 Second Scenario:

Now, we will try to assign public access modifier to more than one class. Say two classes will have public modifier.

In this scenario, look at the below given screen-shot, to find out the result:

java radar examples
Multiple public class in same source file

See the red under line below AnotherMultiplePublic class in the screenshot above. Place the mouse cursor above it and you will see the error message:

                ‘The public type AnotherMultiplePublic must be defined in its own file

Conclusion: That means in the same source file one cannot have more than one public class. 
Though there is no problem if you want to keep more than one class in same source file and you restrict the application of public modifier to only one class as we did in our first scenario.

Note for Readers: Please share your valuable thoughts on this post’s question to help others.

You may also like to read:

  • checked and unchecked exception in java
  • string[] args parameter in main()
  • collection vs collections 
  • how string is immutable in java?
  • difference between == and equals() in java

Source link

Can we keep more than one class in a single java source file?

Leave a Reply

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