当java类X需要放入一个名为X.java的文件? [英] When java class X required to be placed into a file named X.java?

查看:145
本文介绍了当java类X需要放入一个名为X.java的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



File B.java

 
final class C {}
final class D {}

strong>文件A.java:

 class B {} 
public class A {}

问题:


  1. 它自己的X.java文件?


  2. b

    非常感谢。

    解决方案

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



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



    这是在Java语言规范中推荐的,
    $ b


    JLS 7.6顶级类型声明



    当包存储在文件系统中时,主机系统可以选择强制执行如果在类型名称加扩展名(例如 .java )下的文件中找不到类型的编译时错误, .jav ):




    • 类型由其他编译的代码引用

    • 类型声明为 public (因此可以从其他包)。



    这个限制意味着每个编译单元最多只能有一个这样的类型。这种限制使得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:

    1. When class X is required to be placed into its own X.java file? Does class visibility/final matter here?
    2. Is there any official spec on this class/java relation?

    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:

    • 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.

    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆