The answer is yes, we can overload the main() method. A Java class can have any number of main() methods. For example, the MainDemo class below has multiple main() methods.

 package com.magic.main;

public class MainDemo {
    
    public static void main(String[] args) {
        System.out.println("Hello World!");
        main();
        main("test".toCharArray());
        main(new int[]{0});
        main("test");
        main(0);
    }

    public static void main() {
        System.out.println("no args");
    }

    public static void main(char[] args) {
        System.out.println("args type is char[]");
    }

    public static void main(int[] args) {
        System.out.println("args type is int[]");
    }

    public static int main(String arg) {
        System.out.println("arg type is String");

        return 0;
    }

    public static void main(int arg) {
        System.out.println("arg type is int");
    }

}

Running the program, you can see that the following results are output:

 Hello World!
no args
args type is char[]
args type is int[]
arg type is String
arg type is int

It can be seen that the main() method can be overloaded, so another question arises: Can the main() method in Java be overridden?

For more knowledge points related to Java interviews, you can pay attention to the [Java Interview Manual] applet, which involves Java foundation, multithreading, JVM, Spring, Spring Boot, Spring Cloud, Mybatis, Redis, database, data structure and algorithm.


十方
226 声望433 粉丝