gpt4 book ai didi

java - 带有 int、Object 和 String [] args 的 Main 方法

转载 作者:行者123 更新时间:2023-12-01 18:09:26 25 4
gpt4 key购买 nike

我从互联网上获得了以下代码,即使有 3 种主要方法,如果我从命令提示符运行该应用程序:

java MainTest 1 2 3

我会得到输出:

String main 1

public class MainTest {

public static void main(int [] args) {
System.out.println("int main " + args[0]);
}
public static void main(Object[] args) {
System.out.println("Object main " + args[0]);
}

public static void main(String[] args) {
System.out.println("String main " + args[0]);
}

}
  • 是否存在同一个类中需要超过 1 个 main 方法的场景?

  • 我还没有使用intObject [] args的main方法?这可能吗?我认为这只能通过 String[] args 实现。

  • 我原本希望在运行时收到错误消息。为什么我在应用程序运行时没有收到任何错误?这是否意味着传递的参数总是被解析为String并且Java获取最适合的main方法?

<小时/>

非常感谢!!

最佳答案

该示例显示了重载

main方法重载。

JVM 只查找静态的 main 方法,并且它应该只接受一个字符串数组参数。因此,您将得到 String main 作为输出

Is there any scenario where more than 1 main method is needed in the same class?

这仅取决于您的要求

I have not used yet the main method with int, Object [] args? is that even possible? I thought it was only possible with String[] args

我认为您想使用 Object[] 参数调用 main 方法。 public static void main(Object[] args) { 就像任何其他简单方法一样,您可以通过 MainTest.main(new Object{1,2}) 调用它

I was expecting getting an error message at runtime. Why I did not get any error when the application ran? Does it mean that the parameters passed are always parsed to String and Java gets the main method

代码非常好,因此您不会收到任何错误。代码描述了 main 方法重载的示例

关于java - 带有 int、Object 和 String [] args 的 Main 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34035646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com