源文件不能具有多个公共类 [英] source file can't have more than one public class

查看:64
本文介绍了源文件不能具有多个公共类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们只能在源文件中声明一个公共文件,并且文件名必须与公共类名匹配

we can declare only one public file in a source file and file name must match the public class name

此限制是否有任何原因....

is there any reason to this restriction....

推荐答案

好吧,这不是Java中的强制性限制.Java语言规范将其称为 option .摘自JLS的第7.6节:

Well, it's not a compulsory restriction in Java. It's one that the Java Language Specification mentions as an option. From section 7.6 of the JLS:

当程序包存储在文件系统中时(第7.2.1节),如果在文件中找不到由文件名组成的名称的类型,则主机系统可以选择强制执行限制,即它是编译时错误.如果满足以下任一条件,请输入名称加上扩展名(例如.java或.jav):

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:

  • 在声明该类型的包的其他编译单元中,该代码由代码引用.
  • 该类型被声明为公共类型(因此可以通过其他程序包中的代码进行访问).

此限制意味着每个编译单元最多只能有一个这样的类型.这种限制使Java编程语言的编译器或Java虚拟机的实现可以轻松地在包中找到命名的类.例如,可以在目录wet/sprocket的Toad.java文件中找到公共类型wet.sprocket.Toad的源代码,并在同一目录的Toad.class文件中找到相应的目标代码.

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.

但是基本上,它的存在是为了鼓励您使源代码更易于浏览.如果您知道公共类的名称,通常很容易找到它的源代码.

But basically it's there to encourage you to make your source easier to navigate. If you know the name of a public class, it's usually pretty easy to find the source code for it.

这篇关于源文件不能具有多个公共类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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