Java 类文件中 main() 方法的首选位置 [英] Preferable location of main() method in Java class file

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

问题描述

说到 java 类中的 order/sequence 方法.您希望/更喜欢在哪里看到 main() 方法?

When it comes to order/sequence methods in java class. Where do you expect/prefer to see main() method?

  • 在每个字段之前的顶部(强调用户它的存在和强制他使用它)
  • 在底部(让用户先看到字段,然后再发现主要)
  • 在 c-tor 之后
    或... .

请分享您的想法,这是一个文体/哲学问题.请不要建议将 main() 单独保存在单独的文件中.

Please share your thoughts, this is kind of stylistic/philosophical question. Please do not suggest to keep main() in separate file alone.

推荐答案

这些只是我的想法:

main() 是一个与对象实例无关的静态方法.我们知道它作为入口点存在,这使得我们的程序/类可执行.

main() is a static method unrelated to object instances. We know that it exists as an entry point, that makes our program/class executable.

问题是在 Java 中,所有东西(除了基元)都是一个对象,所以 main() 必须在某个类中的某个地方声明.此类静态方法可能执行的代码更关注设置程序以供执行,并委托我们的业务逻辑(实际执行某些操作的对象)来运行应用程序.因此,它的关注点不同于我们类的其余部分(它定义了我们试图封装的一些数据和行为).

The thing is that in Java, everything (but primitives) is an object, so main() must be declared in some class somewhere. The code such a static method may execute is more concerned with setting up the program for execution, and delegating to our business logic (objects that actually do something) to run the application. As such, its concern is distinct from the rest of our class (which defines some data and behaviour that we are trying to encapsulate).

main() 并不真正属于我们日常类的数据和行为,因为我怀疑每个类都需要单独执行.main() 关心的是运行我们的程序.因此,它应该在与应用程序启动/执行相关的项目模块中从我们的业务对象中声明出来.因此,正如您可能会猜到的,我提出的正是您所说的不建议的内容 - 使 main 尽可能远离您的类和逻辑,并且仅在您的应用程序入口点的上下文中声明它.

main() doesn't really belong with the data and behaviour of our everyday classes, as I doubt that every class needs to be executable on its own. main()'s concern is with running our program. As such, it should be declared away from our business objects, in a module of the project concerned with application launch/execution. So, as you might be guessing, I am proposing exactly what you've said not to suggest - keep main away from your classes and logic as much as possible, and only declare it in the context of an entry point to your application.

至于文件本身的位置,我认为这并不重要 - 只要该文件中的代码显然与设置和运行程序有关.

As to the location within a file itself, I don't really think it matters - as long as it is obvious that the code in that file is concerned with setting up and running the program.

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

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