当java类X需要放入一个名为X.java的文件? [英] When java class X required to be placed into a file named X.java?
问题描述
伙计,我遇到了这样的法律行为:
File B.java :
final class C {}
final class D {}
strong>文件A.java:
class B {}
public class A {}
问题:
- 它自己的X.java文件?
- 类型由其他编译的代码引用
- 类型声明为
public
(因此可以从其他包)。 - When class X is required to be placed into its own X.java file? Does class visibility/final matter here?
- Is there any official spec on this class/java relation?
- 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). - Java Tutorials/Packages/Managing Source and Class Files
- Joseph D. Darcy's blog - Nested, Inner, Member, and Top-Level Classes
b
非常感谢。
大多数实现中的事实标准是源文件只能包含一个顶层 public
类型定义。源文件的名称必须是该类型的名称。
源文件可以包含嵌套类型,但是根据定义,它们不是顶级 public
类型。
这是在Java语言规范中推荐的,
$ b
JLS 7.6顶级类型声明
当包存储在文件系统中时,主机系统可以选择强制执行如果在类型名称加扩展名(例如
.java
或)下的文件中找不到类型的编译时错误, .jav
):
这个限制意味着每个编译单元最多只能有一个这样的类型。这种限制使得Java编程语言的编译器或Java虚拟机的实现容易在包内找到命名的
类
;例如,public
类型wet.sprocket.Toad
的源代码将位于文件<$ c在wet / sprocket
目录中的<$ c> Toad.java ,并且相应的目标代码将在文件Toad.class
。
注意 final $
相关问题
另请参阅
Guys, I've come across such legal behaviour:
File B.java:
final class C {} final class D {}
File A.java:
class B {} public class A {}
Questions:
Thanks a lot.
The de-facto standard in most implementations is that a source file can only contain one top-level public
type definition. The name of the source file must be the name of that type.
A source file can contain nested types, but by definition they're not a top-level public
type.
This is recommended in, but not required by, the Java Language Specification.
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:
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 apublic
typewet.sprocket.Toad
would be found in a fileToad.java
in the directorywet/sprocket
, and the corresponding object code would be found in the fileToad.class
in the same directory.
Note that final
has nothing to do with accessibility, so it's not a relevant issue in this matter.
Related questions
See also
这篇关于当java类X需要放入一个名为X.java的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!