How many public classes can be created in a java source file?
In this chapter of java interview questions, we will learn about:
-
can we have multiple public classes in a java source file?
-
video tutorial on having multiple public classes in a java source file.
how many public classes can be created in a java program?
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.
Check our video tutorial explaining how many public classes can be created in a java program?
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 TutorialsInHand must be defined in its own file'
Example: multiple public classes in a java source file
Lets see one example on can we have multiple public classes in a java source file?
See the screenshot below which shows two or multiple public classes in a java source file generating compiler error. Here the name of source file is TightlyCoupled.java
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.
MCQ question is asked on this topic:
can we have two public classes in one java file true or false?
Now obviously you can easily answer it, right.
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Sonu Pandit
Technology geek, loves to write and share knowledge with the world. Having 10+ years of IT experience. B.Tech in Computer Science & Engineering
Page Views :
Published Date :
Jul 26,2022