Package-private class within a .java file - why is it accessible?(.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,这对我来说非常有意义.只有在使用默认包私有访问声明时才会混淆.
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 的虚拟机启动.
请注意,本章没有提及关于类的可见性检查.它only 指定main method 必须是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 文件中的包私有类 - 为什么它可以访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:.java 文件中的包私有类 - 为什么它可以访问?
基础教程推荐
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
