11

为什么你需要在你的类中有一个包含public static void main (String[] args){}

为什么不使用构造函数创建一个单独的类并实例化它呢?

4

4 回答 4

20

main() method is the entry point for any program in java. This is the method which is invoked by the JVM to execute the program.

Every class including abstract classes has a constructor. Even if you don't declare one explicitly, compiler will add a default constructor. The main() method has to belong to some public class (which will always have a constructor). Yes generally it is preferable to design another class which has all the programming logic and just instantiate this class in the main class i.e. the one with main() method in it.

But you can also have a class with main method which creates object of its own class (because you cannot access instance members from static methods).

于 2013-04-13T10:20:41.717 回答
8

Method public static void main(String[] args) does not create instance of your class. But constructor does.

Having main(String[]) method in several classes help to test functionality of a particular class in a big application.

于 2013-04-13T10:20:57.700 回答
6

构造函数和main方法有两个不同的目的。

构造函数允许创建给定类的实例,而main方法仅允许启动程序的潜在入口点

此外,对于给定的类,您可以有多个构造函数(接受零个或多个参数),但只有一个主要方法(在​​给定的类中)。

主要区别是我的第一点——它们有不同的目的。一个是启动程序的入口点,另一个是显式地允许创建类的实例。

于 2013-04-13T10:26:32.793 回答
1

While I don't think this will be constructive...

Some programmers like to place a main "test" program inside of the class itself to construct and use it. Some professors like to be faux-OOP by constructing an object and having it do the work.

...neither are strong patterns worthy of emulating in my personal opinion.

于 2013-04-13T10:22:28.923 回答