Multiple Main Methods in Java: Overloading Rules Explained

使用して回答:GPT-4o-mini によってJava Q&A Hub

質問:

What happens if there are multiple main methods inside one class in Java?

回答:

In Java, a class can have multiple methods with the same name, but they must have different parameter lists. This is known as method overloading. However, when it comes to the main method, there are specific rules that apply.

The main method in Java is defined as:

public static void main(String[] args)

If you try to define multiple main methods in the same class with the exact same signature (i.e., the same name and parameter types), the Java compiler will throw a compilation error because it does not allow duplicate method signatures.

However, you can overload the main method by changing its parameter list. For example, you can have:

public class MyClass {
    public static void main(String[] args) {
        System.out.println("Main method with String[] args");
    }

    public static void main(String arg) {
        System.out.println("Overloaded main method with String arg");
    }

    public static void main(int arg) {
        System.out.println("Overloaded main method with int arg");
    }
}

In this example, the class MyClass has three main methods, but they are overloaded with different parameter types. The Java Virtual Machine (JVM) will only call the main method with the signature public static void main(String[] args) when you run the program. The other overloaded versions of main can be called from within the program or from other methods, but they will not be invoked by the JVM as the entry point of the application.

In summary:

  • You cannot have multiple main methods with the same signature in a class.
  • You can overload the main method with different parameter lists, but only the standard main(String[] args) will be called by the JVM when the program starts.