devoured elysium
devoured elysium

Reputation: 105057

Possible to have several classes in just one file in Eclipse?

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 something against having everything in the same file?

Upvotes: 5

Views: 13627

Answers (6)

trashgod
trashgod

Reputation: 205785

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.

Upvotes: 4

Uri
Uri

Reputation: 89729

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.

Upvotes: 1

ALOToverflow
ALOToverflow

Reputation: 2699

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.

Upvotes: 0

Mr. Shiny and New 安宇
Mr. Shiny and New 安宇

Reputation: 13908

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.

Upvotes: 2

Lluis Martinez
Lluis Martinez

Reputation: 1973

It's a language requirement. The only way to embed classes in a single file is creating inner classes.

Upvotes: 0

pkaeding
pkaeding

Reputation: 37633

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.

Upvotes: 14

Related Questions