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

前端 未结 5 577
余生分开走
余生分开走 2020-12-18 04:24

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

Will it compile?

Will it run?

5条回答
  •  北海茫月
    2020-12-18 04:45

    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.

提交回复
热议问题