Is it possible to specify the main () method as private or protected?

Is it possible to specify the main() method as private or protected?

Will it compile?

Will it work?

+4
source share
4 answers

It will compile, it will not start (verified using Eclipse).

0
source

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

Yes

will it compile?

Yes

will it work

Yes, but this cannot be made an application entry point. It will work if it is called from another place.

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 cannot be used as the entry point of the application, but it can be called from the PublicMain class

Private methods cannot be called, but from the class itself. So you will need something like:

  public static void callMain() { main( new String[]{} ); } 

To call main if it was private.

+13
source

Yes, it will compile. But this will not work as an entry point to the program.

Java is looking for the main signature of the main method. If any of the modifiers is different, then he will assume that this is some other method.

run and test 4 yourself. :)

+5
source

You can have as many classes with any basic methods you want. They simply cannot be an entry point if they do not match the signature.

+4
source

Source: https://habr.com/ru/post/1311376/


All Articles