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,
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:
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:
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:
Multiple public class in same source file |
'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:
What about a inner class ?
ReplyDeleteWhat about a inner class ?
ReplyDeleteWhat about a inner class ?
ReplyDelete