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

前端 未结 5 567
余生分开走
余生分开走 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:37

    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. :)

    0 讨论(0)
  • 2020-12-18 04:43

    It will compile, it will not run (tested using Eclipse).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-18 04:51

    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);
      }
    }
    
    0 讨论(0)
  • 2020-12-18 04:55

    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.

    0 讨论(0)
提交回复
热议问题