简体   繁体   中英

Can multiple main method of class A can be called from another class B main method

I want to call the main method of the same class with different string arguments from another class main method.

public class A {

    public static void main(String[] args) {

        String[] testArgs = {"Hi", "Helloworld" };

        B.main(testArgs );

        String[] testArgs1 = {"Hi", "Java" };

        B.main(testArgs1 );

    }

}

public class B {

    public static void main(String[] args) {

        System.out.println(args[0] + " " + args[1]);
    }

}

是的,您可以,但是您只需要从 B 类中删除“公共”,因为在 Java 中,一个文件只有一个公共类。

Yes, you can call a main method exactly like you would call any other static method, from within the same class or from another class (as you already do).

1) If you put two classes, like A and B, in the same source file, exacly one of must be declared public. The name of this public class must be the prefix of the name of the file. (So, if A is the public class, the name of the file must be A.java, if stored in a ordinary file system.)

2) If you put A and B in separate source files, they can both be public.

Regardless of how you choose to store the classes, you call the main methods the same way. To call B's main method from A, write just

B.main( ... )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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