为什么java main类需要main()方法 [英] Why main() method is needed in java main class

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

问题描述

我知道我们可以在没有main()方法的情况下成功编译和运行java程序,但为什么我们仍然需要java的主类中的main()方法?

I know we can compile and run a java program successfully without a main() method, but why we still need main() method in java's main class?

推荐答案

每个Java应用程序都必须包含一个主要方法,其签名如下所示:

Every Java application must contain a main method whose signature looks like this:

   public static void main(String[] args)

主要方法如何被调用

Java语言中的main方法类似于C和C ++中的main函数。当Java解释器执行应用程序时(通过在应用程序的控制类上调用),它通过调用类的main方法开始。然后main方法调用运行应用程序所需的所有其他方法。

The main method in the Java language is similar to the main function in C and C++. When the Java interpreter executes an application (by being invoked upon the application's controlling class), it starts by calling the class's main method. The main method then calls all the other methods required to run your application.

如果尝试在没有main方法的类上调用Java解释器,解释器拒绝编译您的程序并显示类似于以下内容的错误消息:

If you try to invoke the Java interpreter on a class that does not have a main method, the interpreter refuses to compile your program and displays an error message similar to this:

 In class NoMain: void main(String argv[]) is not defined

主要方法的参数

从下面的代码片段中可以看出,main方法接受一个参数:String类型的元素数组。

As you can see from the following code snippet, the main method accepts a single argument: an array of elements of type String.

   public static void main(String[] args)

this array是运行时系统将信息传递给应用程序的机制。数组中的每个String称为命令行参数。命令行参数允许用户在不重新编译的情况下影响应用程序的操作。例如,排序程序可能允许用户使用此命令行参数指定数据按降序排序:

This array is the mechanism through which the runtime system passes information to your application. Each String in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument:

    -descending

了解更多信息

http://journals.ecs.soton.ac.uk /java/tutorial/getStarted/application/main.html

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

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