繁体   English   中英

Java多个类和多个主要方法,执行所有主要方法

[英]Java multiple Classes and multiple main methods, execute all main methods

我是Java的新手,我刚刚编写了一些代码,其中我使用了两个带有main方法的类。 我喜欢一个接一个地执行两个主要方法。 是否有可能以指定的顺序同时执行它们?

imFirst.java

public class imFirst {
    public static void main(String[] args) {
        System.out.println("I want to be the first one executed!");
    }
}

imSecond.java

public class imSecond {
    public static void main(String[] args) {
        System.out.println("I want to be the second one executed!");
    }
}

这些是在一个包中,通过eclipse执行。

你可以从imFirst调用imSecond的主要内容:

public class imFirst {
    public static void main(String[] args) {
        System.out.println("I want to be the first one executed!");
        imSecond.main(args);
    }
}

或者可以是相反的:

public class imSecond {
    public static void main(String[] args) {
        System.out.println("I want to be the second one executed!");
        imFirst.main(args);
    }
}

根据您的需要来做。 但是,不要同时做这两件事,或者你可以得到两个方法互相呼叫的无限循环。

作为旁注:使用适当的java命名约定。 类名应为CamelCase。

快速解决

您也可以像其他常规方法一样调用main -method:

public static void main(String[] args) {
    imFirst.main(null);
    imSecond.main(null);
}

更好的方法

但是你应该首先考虑为什么你甚至需要两种主要的方法 main方法是整个Java链中的第一件事,通常只对每个完整的程序使用一个方法。 目的是简单地启动程序,大多数情况下它只是调用专用类,如:

public static void main(String[] args) {
    ProgramXY programXY = new ProgramXY();
    programXY.init();
    programXY.start();
}

所以我建议你简单地将两个print语句移动到自己的类和方法中,然后简单地从一个main方法调用它们:

实用类:

public class ConsolePrinter {
    public static void println(String line) {
        System.out.println(line);
    }
}

唯一的主要方法:

public static void main(String[] args) {
    ConsolePrinter.println("I want to be the first one executed!");
    ConsolePrinter.println("I want to be the second one executed!");
}

更一般

或者更一般的目的:

头等舱:

public class FirstClass {
    public void firstMethod() {
        // ...
    }
}

二等:

public class SecondClass {
    public void secondMethod() {
        // ...
    }
}

唯一的主要方法:

public static void main(String[] args) {
    FirstClass first = new FirstClass();
    SecondClass second = new SecondClass();

    first.firstMethod();
    second.secondMethod();
}

暂无
暂无

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

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