.java文件中的包私有类 - 为什么它可以访问? [英] Package-private class within a .java file - why is it accessible?

查看:112
本文介绍了.java文件中的包私有类 - 为什么它可以访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码,其中 HelloWorld 类具有默认或包私有访问权限:

Consider the following code, where the HelloWorld class has default or package-private access:

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!"); // Display the string.
    }
}

并假设上述代码保存在文件中名为 HelloWorld.java 。所以我的问题是:因为 HelloWorld 现在是一个包私有类,它是如何工作的? main()方法不应该在包中可见或可访问,我是对的吗?

And assume that the above code is saved in a file called HelloWorld.java. So my question is: since HelloWorld is now a package-private class, how does it work? The main() method should not be visible or accessible across packages, am I right?

它非常有意义如果类 HelloWorld 被声明为public,请告诉我。仅当使用默认的package-private访问声明它时才会出现混淆。

It makes perfect sense to me if the class HelloWorld is declared public. Confusion is only when it is declared with the default package-private access.

推荐答案

JVM启动在§12.1虚拟机启动JLS

请注意,本章说明 nothing 关于类的可见性检查。 指定 main 方法必须 public

Note that this chapter says nothing about visibility checks with regards to the class. It only specifies that the main method must be public.

这意味着根本没有检查类级别的可见性(这种情况有意义,因为还没有可用于检查可见性的上下文:其中包是来电者?)。

This means that there simply is no check for visibility on the class level (which kind-of makes sense as there is no context yet against which to check the visibility: in which "package" is the "caller"?).

这篇关于.java文件中的包私有类 - 为什么它可以访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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