Can the main()
method be specified as private or protected?
Will it compile?
Will it run?
Yes, it will compile. But it wil not run as entry point of the program.
Java looks for the public main method signature. If any of the modifiers is different, then it wil assume it as some other method.
run and test 4 urself. :)
It will compile, it will not run (tested using Eclipse).
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.
Yes, It will compile but Not Run. It will give you the following errors
Error: Main method not found in class A, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
Following are the simple code for testing
class A {
private static void main(String arg[])
{
System.out.print(2+3);
}
}
You can have as many classes with whatever main methods as you want. They just can't be an entry point unless they match the signature.