可以在 Eclipse 的一个文件中包含多个类吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2366310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Possible to have several classes in just one file in Eclipse?
提问by devoured elysium
Is it possible to have several classes in a single java file in Eclipse? Or must I really have each one in a different file?
是否可以在 Eclipse 的单个 java 文件中包含多个类?或者我真的必须将每个文件放在不同的文件中?
Is it just something imposed by Eclipse, or does the Java compiler have something against having everything in the same file?
它只是 Eclipse 强加的东西,还是 Java 编译器反对将所有内容放在同一个文件中?
回答by pkaeding
You can only have one public class per file, according to the Java spec (this is not Eclipse's rule). You can have inner classes, or static classes, in the same file as a public class.
根据 Java 规范(这不是 Eclipse 的规则),每个文件只能有一个公共类。您可以在与公共类相同的文件中包含内部类或静态类。
回答by trashgod
Eclipse follows the relevant Java standard: 7.6. Top Level Type Declarations. At the top level, a single source file may declare any number of classes, but only one may be public. Any others have package-privateaccess.
Eclipse 遵循相关的 Java 标准:7.6。顶级类型声明。在顶层,单个源文件可以声明任意数量的类,但只有一个是公共的。任何其他人都拥有包私有访问权限。
回答by u7867
You can have multiple classes in just one file in Java (it's a Java restriction) but there can be only one class in the file that is public, and that class must have the same name as the file. Generally you only put two classes in one file if the second class is meant to only be used by the first class or its close neighbours.
在 Java 中,您可以在一个文件中拥有多个类(这是 Java 限制),但文件中只能有一个类是公共的,并且该类必须与文件同名。通常,如果第二个类仅由第一类或其近邻使用,则您只将两个类放在一个文件中。
回答by Uri
You can have only one top level class or interface, and the declarations of inner classes (static or otherwise) inside it. This is a restriction that comes from Java, not from Eclipse. In fact, the C++ editor for Eclipse would have no problems with it for C++ files.
您只能有一个顶级类或接口,以及内部类(静态或其他)的声明。这是来自 Java 而不是来自 Eclipse 的限制。事实上,Eclipse 的 C++ 编辑器对于 C++ 文件没有问题。
回答by Lluis Martinez
It's a language requirement. The only way to embed classes in a single file is creating inner classes.
这是语言要求。在单个文件中嵌入类的唯一方法是创建内部类。
回答by ALOToverflow
It's actually in the Java specification : http://java.sun.com/docs/books/jls/third_edition/html/packages.html#26783
它实际上在 Java 规范中:http: //java.sun.com/docs/books/jls/third_edition/html/packages.html#26783
If you want more than one class in the same file, it has to be a inner class from the 'top' public one.
如果您希望在同一个文件中包含多个类,则它必须是来自“顶级”公共类的内部类。