为什么Java中的main方法总是需要参数? [英] Why does main method in Java always need arguments?

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

问题描述

为什么Java中的main方法总是需要参数?我们为什么每次都要写 String [] args ,而不是在我们使用任何参数时写它?

Why does the main method in Java always need arguments? Why should we write String[] args every time, instead of just writing it when we use any arguments?

像这样的方法生成未找到主方法编译器错误。因为我们从不对main方法使用任何参数,所以应该允许这样做。

A method like this generates Main method not found compiler error. Since we never use any arguments to the main method, this should be allowed.

public static void main()
{
}

这不是面试问题。编程时我才想到这一点。

This is not an interview question. It just came to my mind while programming.

推荐答案

基本上,有四个答案:


  1. 因为这就是它的设计方式。是的,我知道这是一个循环的原因。但重点是,这是它的方式,它不会改变。因此,除非您计划设计自己的语言,否则这个问题没有实际意义。

  1. Because that's the way it was designed. Yea, I know that's a circular reason. But the point is that this is the way it is and it ain't going to change. So unless you are planning on designing your own language, the question is moot.

设计的清洁度(又称DRY原则)。当一个人可以完成工作时,不要指定两个入口点签名。显然,它可以。

Cleanness of design (aka the DRY principle). Don't specify two entry point signatures when one can do the job. And clearly, it can.

语义简洁。假设(假设)Java 支持 void main(String []) void main()入口点。如果一个类定义了两个方法会发生什么?这是一个错误吗?如果没有,当存在歧义时哪一个优先?这有点令人困惑吗?

Semantic simplicity. Suppose (hypothetically) that Java did support both void main(String[]) and void main() entry points. What would happen if a class defined both methods? Is that an error? If not, which one takes precedence when there is ambiguity? Is this confusing yet?

只允许 void main(String []),JLS可以避免这个问题。

By only allow void main(String[]), the JLS avoids the problem.

这类似于标准的C和C ++入口点签名。 (不可否认,一些C / C ++运行时也支持其他非标准入口点......但这并不是一件好事... IMO。)

This is analogous to the standard C and C++ entrypoint signatures. (Admittedly, some C / C++ runtimes support other non-standard entrypoints as well ... but that's not exactly a good thing ... IMO.)

这些都不意味着以另一种方式做到这一点毫无疑问是错误的。例如,C#为您提供了替代签名,并通过要求开发人员以其他方式指定入口点来处理歧义问题。

None of this means that it would have been unambiguously wrong to do it another way. And for example C# gives you alternative signatures, and deals with the ambiguity problem by requiring the developer to designate an entry point some other way.

FWIW,此维基百科页面描述多种语言的主要方法。

FWIW, this wikipedia page describes the "main" method in a number of languages.

这篇关于为什么Java中的main方法总是需要参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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