为什么main方法在Java中是静态的 [英] Why main method is static in java

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

问题描述

我听到有人说如果main不是静态的,那么JVM可以创建一个对象 包含main的类的名称,并通过对象调用该main.
但是问题是,在重载的构造函数或什至只有一个参数化的构造函数的情况下,JVM如何知道要调用哪个构造函数,然后传递什么呢."

I have heard some people saying " if main is not static then JVM could create an object of class containing main and call that main through object.
But the problem is how JVM knows which constructor to call in case of overloaded constructors or even if there is only one paramaterized constructor, then what to pass."

这是正确的原因吗?
因为在不进入主函数的情况下如何创建类的对象?
请对此发表您的看法.如果那不是正确的原因,那么正确的原因是什么?

Is that the correct reason?
Because how can object of class be created without entering into main function?
Please give your views on this. If that is not the right reason, then what's the correct reason?

推荐答案

这只是一个约定. Java语言设计人员可以轻松地决定必须指定要实例化的类,从而使其构造函数成为主要方法.但是调用静态方法同样有效,不需要先实例化一个类.

It's just a convention. The Java language designers could have easily decided that you must designate a class to be instantiated, making its constructor the main method. But calling a static method is just as effective and doesn't require a class to be instantiated first.

此外,如果类具有超类,则可以通过更改超类来改变程序启动的行为(因为必须在子类之前调用​​超类构造函数),这可能是无意的.静态方法没有这个问题.

Also, if the class has a superclass, you could alter the behavior of program startup by changing a superclass (since superclass constructors must be called before subclasses), perhaps unintentionally. Static methods don't have this problem.

main方法是静态的,因为它使事情变得更简单,但是如果他们想使其变得更复杂,则可以这样做.

The main method is static because it keeps things simpler, but if they wanted to make it more complicated, they could have.

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

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