Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is each public class in a separate file?

I recently started learning Java and found it very strange that every Java class must be declared in a separate file. I am a C# programmer and C# doesn't enforce any such restriction.

Why does Java do this? Were there any design consideration?

Edit (based on few answers):

Why is Java not removing this restriction now in the age of IDEs? This will not break any existing code (or will it?).

like image 870
Sandbox Avatar asked Aug 23 '09 14:08

Sandbox


2 Answers

I have just taken a C# solution and did just this (remove any file that had multiple public classes in them) and broke them out to individual files and this has made life much easier.

If you have multiple public classes in a file you have a few issues:

  1. What do you name the file? One of the public classes? Another name? People have enough issues around poor solution code organization and file naming conventions to have one extra issue.

  2. Also, when you are browsing the file / project explorer its good that things aren't hidden. For example you see one file and drill down and there are 200 classes all mushed together. If you have one file one class, you can organize your tests better and get a feel for the structure and complexity of a solution.

I think Java got this right.

like image 58
leora Avatar answered Sep 28 '22 05:09

leora


According to the Java Language Specification, Third Edition:

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.

Emphasis is mine.

It seems like basically they wanted to translate the OS's directory separator into dots for namespaces, and vice versa.

So yes, it was a design consideration of some sort.

like image 22
Mark Rushakoff Avatar answered Sep 28 '22 06:09

Mark Rushakoff