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?
Is it just something imposed by Eclipse, or does the Java compiler have somethi开发者_如何学编程ng against having everything in the same file?
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.
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-private access.
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.
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.
It's a language requirement. The only way to embed classes in a single file is creating inner classes.
It's actually in the Java specification : 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.
精彩评论