Why is each public class in a separate file?

Sandbox picture Sandbox · Aug 23, 2009 · Viewed 19.2k times · Source

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?).

Answer

leora picture leora · Aug 23, 2009

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.