java中的多个main()方法 [英] Multiple main() methods in java

查看:215
本文介绍了java中的多个main()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道创建额外主要方法会对您的代码产生什么影响。

I was wondering what the effect of creating extra main methods would do to your code.

例如,

public class TestClass {
    public static void main (String[] args){
        TestClass foo = new TestClass();
    }
}

程序初始启动后,将创建foo它内部会有另一个公共主要方法。这会导致任何错误吗?

After the program initially starts up, foo will be created and it would have another public main method inside it. Will that cause any errors?

推荐答案

这不会导致错误。仅仅因为初始化对象,并不意味着主要方法被执行。 Java最初只会调用传递给它的类的main方法,比如

It will cause no errors. Just because you initialize an object, doesn't mean the main method gets executed. Java will only initially call the main method of the class passed to it, like

> java TestClass

然而,做类似的事情:

public class TestClass
{
 public static void main (String[] args)
 {
  TestClass foo = new TestClass();
  foo.main(args);
 }
}

public class TestClass
{
 public TestClass()
 {
   //This gets executed when you create an instance of TestClass
   main(null);
 }

 public static void main (String[] args)
 {
  TestClass foo = new TestClass();
 }
}

会导致 StackOverflowError ,因为你明确地调用了TestClass的main方法,然后再次调用main方法,再次,再次调用,....

That would cause a StackOverflowError, because you are explicitly calling TestClass's main method, which will then call the main method again, and again, and again, and....

如有疑问,请测试一下: - )

When in doubt, just test it out :-)

这篇关于java中的多个main()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆