gpt4 book ai didi

java - 为什么 Java 文件必须与其公共(public)类同名?

转载 作者:IT老高 更新时间:2023-10-28 21:01:05 24 4
gpt4 key购买 nike

Possible Duplicate:
Why filename in java should be same as class name?

我有一个名为 temp.java 的文件。我写了以下代码。为什么会这样?

class demo //not public keyword and not same as filename
{
public static void main(String []args)
{
System.out.println("this is Main method");
}
}

为什么这不起作用?

public class demo
{
public static void main(String []args)
{
System.out.println("this is Main method");
}
}

最佳答案

在您的第一个示例中,您的类实际上被声明为“包私有(private)”(无修饰符),这意味着只有同一包中的类才能访问它。在您的第二个示例中,您已将其声明为 public。

这是编译器很好地满足 JLS 的场景。

The JLS states:

When packages are stored in a file system (§7.2.1), 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).

This restriction implies that there must be at most one such type per compilation unit. This restriction makes it easy for a compiler for the Java programming language or an implementation of the Java virtual machine to find a named class within a package; for example, the source code for a public type wet.sprocket.Toad would be found in a file Toad.java in the directory wet/sprocket, and the corresponding object code would be found in the file Toad.class in the same directory.

这意味着,对于场景 1,由于您只有 temp.java 和包私有(private)类 demo,因此任何代码都不会引用它包的其他编译单元,因此它将毫无问题地编译。

您的第二个场景已将类声明为 public - 这意味着它可能可以从其他包中的代码访问 - 因此它必须符合类名等于文件名的标准。

如果您在第一个场景中(在同一个包中)创建了另一个类,然后尝试引用类 demo,您应该会收到编译错误。

关于java - 为什么 Java 文件必须与其公共(public)类同名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10442758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com