Can the main()
method be specified as private or protected?
Will it compile?
Will it run?
As default itself allowed why not protected. essentially public means the class is visible outside its package whereas default or package scoped means it's only visible to other classes inside the same package.
The JVM does not have any special handling to call private methods from outside a class. The methods you named are all public. The only way you can bypass the visibility model is to use reflection, but this is wanted because it's purpose is to have deeper insight to objects.
This is the access modifier of the main method. It has to be public so that java runtime can execute this method. Remember that if you make any method non-public then it's not allowed to be executed by any program, there are some access restrictions applied. So it means that the main method has to be public.
Declaring the main method private or, protected It searches for the main method which is public, static, with return type void, and a String array as an argument. If such a method is not found, a run time error is generated.
is the method main( ) can be specified as private or protected?
Yes
will it compile ?
Yes
will it run ?
Yes, but it can not be taken as entry point of your application. It will run if it is invoked from somewhere else.
Give it a try:
$cat PrivateMain.java
package test;
public class PrivateMain {
protected static void main( String [] args ) {
System.out.println( "Hello, I'm proctected and I'm running");
}
}
class PublicMain {
public static void main( String [] args ) {
PrivateMain.main( args );
}
}
$javac -d . PrivateMain.java
$java test.PrivateMain
Main method not public.
$java test.PublicMain
Hello, I'm proctected and I'm running
In this code, the protected method can't be used as entry point of the app, but, it can be invoked from the class PublicMain
Private methods can't be invoked but from the class it self. So you'll need something like:
public static void callMain() {
main( new String[]{} );
}
To call main
if it were private.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With