为什么包含main的类不必公开? [英] Why doesn't the class containing main have to be public?

查看:77
本文介绍了为什么包含main的类不必公开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我声明了以下类

class A { //not public
  public static void main(String args[]) {
     System.out.println("done");
 }

当我编译并运行它时,运行正常并打印输出已完成。即使我声明它在包a;中也是相同的行为。

When I compile and run it, it runs fine and prints the output "done". Same behavior even when I declare it as being in a "package a;"

但是,如果JVM规范要求主方法应该公开,因为它看不到否则主要是,它不应该适用于班级吗?
如果JVM未能看到A.main(),当它未被公开时,它是如何看到A类本身的。

However, if JVM spec mandates that main method should be public since "it can't see main otherwise", shouldn't it apply to the class as well? If the JVM "can't see" A.main() when it is not declared public, how is it able to see the class A itself.

除了因为规范是这样说的之外,还有其他解释吗?

Is there any explanation for this other than "because the specification says so"?

推荐答案

JVM可以访问每个类应用程序始终是因为其职责之一是强制执行可见性规则。因此,可以得出结论,如果需要,它可以忽略可见性规则(例如,当用户启动应用程序时,JVM必须找到入口点,即 main())。

The JVM has access to every class in the application all the time because one of its responsibilities is enforcing visibility rules. Therefore, one can draw the conclusion that it can ignore visibility rules if need be (e.g. when the user starts the application, the JVM has to find the entry point, which is main()).

换句话说,JVM不是访问此函数的类,因此可见性不适用。它基本上是监督者,管理从执行到终止的应用程序。

In other words, the JVM is not a class accessing this function, so visibility doesn't apply. It is basically the overseer, managing the application from execution to termination.

参考执行

这篇关于为什么包含main的类不必公开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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