java main在类中,main()方法在Java类文件中的优选位置

When it comes to order/sequence methods in java class.

Where do you expect/prefer to see main() method?

at the top before each field (to stress user its existence and force

him to use it )

at the bottom (to let user see fields first and after that discover main)

after c-tor

or ... .

Please share your thoughts, this is kind of stylistic/philosophical question.

Please do not suggest to keep main() in separate file alone.

解决方案

These are just my thoughts:

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

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() 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值