Articles

How many public classes can be created in a java source file?

How many public classes can be created in a java source file?

As a java beginner, we always are in dilemma if we can have two public classes in one java file?

Is it true or false?

 

[false, we cannot have multiple public classes in java source file]

 

There can be only one public class in a java source file.

 

If you try to create more than one public class there will be a compiler error - 'The public type '

 

See the screenshot below which shows two public class in same source file generating compiler error.

multiple public class in java file

 

Since one public class already exists so to avoid this compiler error:

  • class TutorialsInHand should not be public, or
  • it should be written in separate source file.

If you want this class to be in same source file then remove 'public' access modifier and things will be fine.

Thus it can be concluded that we cannot have multiple public classes in a java source file.


Java Interview Questions
Java Error and Solution

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Rohanjit Kumar
Technology geek, loves to write and share knowledge with the world. Having 9+ years of IT experience. B.Tech in Computer Science & Engineering
Page Views :    Published Date : Aug 22,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!