Why is there no collision when overloading the main function?

Possible duplicate:
Can we overload the main method in Java?

When I tried to compile and run the following code, it works, and I see "A" on the console.

Why?

In my mind (String ... args) it's the same thing (String arg, String [] args).

public class AFewMainExample { public static void main(String... args) { System.out.print("A"); } public static void main(String args) { System.out.print("B"); } public static void main(String[] args, String arg) { System.out.print("C"); } public static void main(String arg, String[] args) { System.out.print("D"); } } 
+4
source share
4 answers

The parameters (order (or) type (or) both) are different for each main method, which leaves only one main method with real main syntax, so no problem.

If you add the following main method, you will see a compile-time error, because now there are two methods with the exact syntax.

 public static void main(String[] args) { System.out.print("A"); } 

Read this tutorial for more information on congestion.

0
source

This is actually stated in JLS, ยง12.1.4 :

The main method must be declared public , static and void . It must specify a formal parameter ( ยง8.4.1 ), the declared type of which is the String array. Therefore, one of the following declarations is valid:

  • public static void main(String[] args)

  • public static void main(String... args)

There is no difference between the varargs type and the standard array type other than the way the function is called, as indicated here . Therefore, the varargs version satisfies all of the above criteria and passes as a valid main method. Obviously, all your other main overloads are not equivalent (otherwise there would be compilation).

+2
source

the first signature is the only one that matches void main (String [] args)

difference fn (String ... args) vs fn (String [] args)

+1
source

The main problem was this:

 + signature of main(String... args) is different for - main(String[] args, String arg) - main(String arg, String[] args) + main(String... args) - not equals for main(String[] args, String[] args2) - only for main(String[] args) 

although I will catch a compilation error in the following example:

 public class MainOverloadingExample4 { void go(String s){ System.out.println("void go(String s)"); } void go(String ... s){ System.out.println("void go(String ... s)"); } void go(String s, String ... arr){ System.out.println("void go(String s, String ... arr){"); } public static void main(String[] args) { new MainOverloadingExample4().go("where I am?", "why I am here?"); } } 

The go (String []) method is ambiguous for the type MainOverloadingExample

0
source

All Articles