为什么包含main方法的类不需要在Java中公开? [英] Why a class containg a main method doesn't need to be public in Java?

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

问题描述

我编写了以下代码

I wrote the following code

 
  class Hello //Note the class is not public
  {
        public static void main(String args[]) {
System.out.println("Hello"); } }

因此,当我运行它时,它运行正常并打印输出Hello 。

So, when I run it, it runs fine and prints the output "Hello".

但是,如果JVM规范要求主要方法应该是公开的,因为它不能看到主要的,不应该也适用于该类?如果JVM未能看到Hello.main(),当它未被声明为public时,它如何能够看到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" Hello.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能够看到所有类和方法,因为它是安全/可见性执行器那么为什么main方法需要被声明为public。

And if the JVM is able to see all classes and methods as it is the "security/visibility enforcer" itself then why does the main method needs to be declared as public.

推荐答案

只是为了踢,私人类也可以进行演示按住 main

Just for kicks, a demo that private classes can also hold main:

class Outer {
    private static class Inner {
        public static void main(String[] args) {
            System.out.println("Hello from Inner!");
        }
    }
}

编译并运行良好命令行:

Compiles and runs fine from the command line:


C:\ junk> javac Outer.java

C:\ junk> java Outer $ Inner

Hello来自内心!

C:\junk>javac Outer.java
C:\junk>java Outer$Inner
Hello from Inner!

C:\ junk>

C:\junk>

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

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