Can we declare main() method as private or protected or with no access modifier?

No, we declare main() method as private or protected or with no access modifier because if we declare so, main() will not be accessible to JVM. Class will compile successfully but will get run time error as no main method found.

Example:

public class Main
{
	protected static void main(String[] args) {
		System.out.println("Protected main method.");
	}
}

Output

Error: Main method not found in class Main, please define the main method as:  
   public static void main(String[] args)    
or a JavaFX application class must extend javafx.application.Application

Note: We can declare main method as private or protected or with no access modifier, if we are using another main method as entry point. Example:

class PrivateMain {
    protected  static void main( String [] args ) {
        System.out.println( "Private main method.");
    }
}
public class Main
{
	public static void main(String[] args) {
		PrivateMain.main(args);
	}
}

Output

Private main method.

Java interview questions on main method

Please follow and like us:
Content Protection by DMCA.com