繁体   English   中英

为什么不从另一个类中调用一个类的静态方法“ main”?

[英]Why not call the static method “main” of a class from another class?

如果我上课:

public class HelloWorld {
  public static String main(String[] args) throws IOException {

 public createMessage(){

 String message = "Hello World!";

  }

 }
 return message; //return of the main static method
}

为什么不能从另一个类将main称为HelloWorld.main(args)

String msg = (String) HelloWorld.main(args);

System.out.println(msg);

按照我们称为静态方法的方式。

您的代码不是有效的Java代码。 它不会编译。 我使用以下步骤修复了编译错误:

  • main方法的返回类型更改为void
  • 移除throws IOException ,因为没有抛出异常,编译器会抱怨它
  • 在打开方法createMessage之前先关闭方法main createMessage
  • 使方法createMessage变为静态,因此可以从静态方法main调用它
  • String添加为方法createMessage返回类型
  • 将返回语句移至方法createMessage

这是固定的代码:

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println(createMessage());
    }

    public static String createMessage() {
        String message = "Hello World!";
        return message;
    }
}

您可能不想自己从另一个方法调用main方法。 主要方法是程序的入口点,这意味着JVM自动调用它来启动程序。 在main方法中,您可以打印hello world消息。 为此,您可以使用createMessage方法创建消息。 该方法执行完后,将创建消息传递给Java的方法System.out.println() ,以将文本输出到控制台。


您可以通过替换两行来进一步简化代码

        String message = "Hello World!";
        return message;

用这一行:

        return "Hello World!";

是的,您可以从另一个类调用main方法。

但是,不应从应用程序内部调用main()方法。 main()方法应该用作应用程序的入口,以启动程序,而不是用于递归地执行该应用程序内的逻辑。 如果再次需要功能,则应将其放在单独的方法中。

暂无
暂无

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

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