我知道在java文件中声明的public
类的名称必须与其文件名相同。但我想知道这如何没有给我编译错误,而是成功运行。
class Foo //<-- this can be any name...
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
我知道默认访问权限是package private
。对于上面的程序,类名和文件名不必相同。它正确执行,而不是编译器错误。
有人能提供一些线索吗?谢谢。
编辑:
现在我明白了!但另一个问题引起了我的注意。当同一个文件中有两个这样的类时会发生什么?
嗯,我认为实现了 main
方法的类将会生成一个 .class
文件。没有任何编译错误,但令我惊讶的是也没有生成任何 .class
文件。为什么会这样?
最佳答案
是的,那绝对没问题。即使对于公共(public)类,这也是编译器特定的可选限制。
If and only if packages are stored in a file system (§7.2), the host system may choose to enforce the restriction that it is a compile-time error if a type is not found in a file under a name composed of the type name plus an extension (such as .java or .jav) if either of the following is true:
The type is referred to by code in other compilation units of the package in which the type is declared.
The type is declared public (and therefore is potentially accessible from code in other packages).
请注意第二个要点 - 当您的类(class)不公开时,此限制不适用。
编辑:根据更新的问题...
What happens when there are two such classes in the same file?
类文件是根据类名生成的。 main
方法的存在与此完全无关,原始源文件名也是如此。如果编译成功,当然应该生成一个类文件。如果没有示例代码来重现问题,我们无法判断到底发生了什么。
关于java - 在java中省略访问说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21231730/