简体   繁体   English

为什么重载main方法会产生语法错误?

[英]Why does overloading the main method give a syntax error?

import java.util.*;
public class Overload {
    public static void main(String...args) {
        System.out.println("in main 1");
    }
    public static void main(String args[]) {
        System.out.println("in main 2");
    }
}

I was checking if both the main methods have standard signature which one will get executed but when I compile it, it shows error. 我正在检查两个主要方法是否都有标准签名哪个将被执行但是当我编译它时,它显示错误。 why is it so? 为什么会这样?

Using an ellipsis ( ... ) is just syntactic sugaring that allows you to pass several comma-delimited arguments instead of explicitly declaring an array. 使用省略号( ... )只是语法糖,允许您传递几个逗号分隔的参数,而不是显式声明一个数组。 From within the method, for all intents and purposes that argument is an array. 从方法中,对于所有意图和目的,该参数是一个数组。 So, you're essentially defining two methods with the same signature ( public static void main(String[]) ), which is not allowed, regardless of the fact that it's the special main method. 所以,你实际上定义了两个具有相同签名的方法( public static void main(String[]) ),这是不允许的,不管它是否是特殊的main方法。

Varargs are basically compiled into single array. Varargs基本上编译成单个数组。 Hence, you have 2 methods which are the same 因此,您有两种相同的方法

Your code (changed one of the main, it's now a valid code): 你的代码(更改了一个主要代码,它现在是一个有效的代码):

import java.io.PrintStream;

public class Overload {
  public static void main2(String... paramVarArgs) {
    System.out.println("in main 1");
  }

  public static void main(String[] paramArrayOfString) {
    System.out.println("in main 2");
  }
}

This code compiled, and decompiled with a bytcode viewer: 此代码使用bytcode查看器进行编译和反编译:

public class Overload {

     public Overload() { // <init> //()V
         L1 {
             aload0 // reference to self
             invokespecial java/lang/Object <init>(()V);
             return
         }
     }

     public static varargs main2(java.lang.String[] arg0) { //([Ljava/lang/String;)V
         L1 {
             getstatic java/lang/System.out:java.io.PrintStream
             ldc "in main 1" (java.lang.String)
             invokevirtual java/io/PrintStream println((Ljava/lang/String;)V);
         }
         L2 {
             return
         }
     }

     public static main(java.lang.String[] arg0) { //([Ljava/lang/String;)V
         L1 {
             getstatic java/lang/System.out:java.io.PrintStream
             ldc "in main 2" (java.lang.String)
             invokevirtual java/io/PrintStream println((Ljava/lang/String;)V);
         }
         L2 {
             return
         }
     }
}

you cannot declare both main(String[]) and main(String...). 你不能声明main(String [])和main(String ...)。 Your class cannot have 2 main methods with same signatue (String...) is same as that of (String[]) . 您的类不能有2个具有相同signatue(String ...)的主要方法与(String [])相同。 It is not allowed in java. 它不允许在java中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM