Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the main( ) method be specified as private or protected?

Tags:

java

Can the main() method be specified as private or protected?

Will it compile?

Will it run?

like image 907
billu Avatar asked May 31 '10 05:05

billu


People also ask

Can main class be protected?

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.

Why main method is not private?

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.

Can main method be public?

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.

What happens if we make main method private in Java?

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.


1 Answers

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.

like image 134
OscarRyz Avatar answered Sep 21 '22 02:09

OscarRyz