有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

什么时候需要将java类X放入名为X.java的文件中?

伙计们,我遇到过这样的法律行为:

文件B.java:

final class C {}
final class D {}

文件A.java:

class B {}
public class A {}

问题:

  1. 什么时候需要将类X放入自己的X.java文件中?课堂可见性/最终结果在这里重要吗
  2. 关于这个类/java关系有官方规范吗

非常感谢


共 (3) 个答案

  1. # 1 楼答案

    在大多数实现中,事实上的标准是源文件只能包含一个顶级public类型定义。源文件的名称必须是该类型的名称

    源文件可以包含嵌套类型,但根据定义,它们不是顶级public类型

    这在Java语言规范中是推荐的,但不是必需的

    JLS 7.6 Top Level Type Declarations

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

    请注意final与可访问性无关,因此这与此无关

    相关问题

    另见

  2. # 2 楼答案

    Sun/Oracle编译器允许每个文件最多有一个公共顶级类,在这种情况下,文件名必须是类名

    {a1}不强制要求这种行为,但明确允许:

    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;

  3. # 3 楼答案

    公共类类名必须位于名为ClassName的文件中。爪哇

    非公立课程没有这样的限制

    这样做的结果是,一个Java源文件只能有一个公共类,但可以有任意多个非公共类