public static void main(String arg[ ] ) in java is it fixed?

前端 未结 9 1358
离开以前
离开以前 2020-12-03 03:25

I was recently asked in an exam if public static void main(String arg[]) format of main method was fixed? Can we change it? Can we use main

9条回答
  •  天命终不由人
    2020-12-03 04:08

    If not, why is it not hard coded that main(String arg[]) would stand for public static void main(String arg[]) always?

    You can have methods called "main" with any signature and access you like. The special rules only apply to the method you want the JVM to call to start a program.

    public class Test {
      public static void main(String[] args) {
        StrangeMain m = new StrangeMain();
        System.out.println(m.main());
        System.out.println(m.main(new String[]{"aaa","bbb"}));
      }
    }
    
    class StrangeMain{
      protected String main(){
        return "xyzzy";
      }
      protected String main(String[] arg){
        return arg[0];
      }
    }
    

    compiles, runs, and outputs:

    xyzzy
    aaa
    

提交回复
热议问题