Why the main program in Java is put into a class?

2019-02-03 10:49发布

Why does the main method have to be put into a class? I understand the main ideas of OOP but I cannot get why the main program is defined within a class. Will such a class instantiated somewhere? I mean there is no code outside the class. What is a reason to define a class and never use objects of this class?

标签: java class
9条回答
男人必须洒脱
2楼-- · 2019-02-03 11:09

What @Bombe said. I would add that to OO purists, the fact that the entry class is not instantiated is a misstep. The reason is the static main prevents someone from writing a family of main classes that share the same main() method written using a template method pattern.

If Java had been written to instantiate the main class and invoke the main method, users would have enjoyed the benefits of inheritance and interfaces.

查看更多
戒情不戒烟
3楼-- · 2019-02-03 11:10

That's simply how Java was designed: (almost) everything is an object, and code can only exist as part of a class.

Since the main() is static, it being called does not automatically lead to an instantiation of the class. However, it's perfectly possible (and quite common, at least in small Swing programs and Applets) to have the class that contains the main() be an otherwise normal class that is instantiated and used like any other class.

查看更多
看我几分像从前
4楼-- · 2019-02-03 11:15

When the Java language was designed, the notion that everything must be an object was a point of dogmatism. (though they left in a few primitive types). These days you could perhaps design a language that uses a closure -- even one outside any class -- instead.

查看更多
登录 后发表回答