Among multiple classes that you create in a single source file, only one can be public. Find an example given below,
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.
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:
|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