java中的public static void main(String arg [])是固定的吗? [英] public static void main(String arg[ ] ) in java is it fixed?
问题描述
我最近在考试中被问到 public static void main(String arg [])
格式 main
方法是固定的?
我们可以改变吗?
我们可以使用 main
而不使用任何 public
, static
或 void
?
如果没有,为什么不硬编码 main(String arg [])
代表 public static void main(String arg [])
总是?
I was recently asked in an exam if public static void main(String arg[])
format of main
method was fixed?
Can we change it?
Can we use main
without any of public
, static
or void
?
If not, why is it not hard coded that main(String arg[])
would stand for public static void main(String arg[])
always?
推荐答案
主方法的签名在 Java语言规范部分12.1.4 并明确说明:
The signature of the main method is specified in the Java Language Specifications section 12.1.4 and clearly states:
方法main必须声明为public,static和void。必须
指定一个形式参数(§8.4.1),其声明的类型是
String的数组。
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.
- 它必须是
public
否则无法调用它 - 它必须
static
因为在调用之前无法实例化对象 -
String $ c $的列表c> arguments允许在从命令行执行Java程序时传递参数。可以在没有参数的情况下定义它,但是更实用(和其他语言类似)
- 返回类型是
void
因为没有其他任何东西是没有意义的:Java程序可以在到达main方法结束之前终止(例如,通过调用System.exit()
) - it must be
public
otherwise it would not be possible to call it - it must be
static
since you have no way to instantiate an object before calling it - the list of
String
arguments is there to allow to pass parameters when executing a Java program from the command line. It would have been possible to define it without arguments but is more practical like that (and similar to other languages) - the return type is
void
since it does not make sense to have anything else: a Java program can terminate before reaching the end of the main method (e.g., by callingSystem.exit()
)
方法签名因此可以是:
public static void main( String[] args )
public static void main( String... args )
请注意 varargs 版本( ...
)仅在Java 5中有效
note that the varargs version (...
) is only valid from Java 5
由于Java语言允许括号 []
位于类型或变量之后(第一个通常是首选),
As the Java language allows the brackets []
to be positioned after the type or the variable (the first is generally preferred),
public static void main( String args[] ) // valid but usually non recommended
也有效
这篇关于java中的public static void main(String arg [])是固定的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!