Thursday 2 November 2017

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

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 = new AnotherMultiplePublic();
            amp.sampleMethod();
      }

}

class AnotherMultiplePublic {

      public void sampleMethod(){
            System.out.println("Print sample method");
      }

}

OUTPUT:
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:

3 comments:

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.