Search code examples
javacode-organization

Why is each public class in a separate file?


I recently started learning Java and found it very strange that every Java public 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 considerations?

Edit (based on a 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?).


Solution

  • 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.