I am a newbie learning Java. In Java every source file must contain a public class and that source file should have the same name as that public class. Moreover, no source file can contain two public classes. Why is this restriction?
In one of his Java Specialists' Newsletters, Heinz Kabutz digs through the Oak Language Specifications. He writes:
Why is each public class in a separate file? (Section 1)
This is a question that I have frequently been asked during my courses. Up to now I have not had a good answer to this question. In section 1, we read: "Although each Oak compilation unit can contain multiple classes or interfaces, at most one class or interface per compilation unit can be public".
In the sidebar it explains why: "This restriction is not yet enforced by the compiler, although it's necessary for efficient package importation"
It's pretty obvious - like most things are once you know the design reasons - the compiler would have to make an additional pass through all the compilation units (.java files) to figure out what classes were where, and that would make the compilation even slower.
Reasons I can think of
- Makes finding other classes slightly easier for the compiler in the beginning since it doesn't have to search all the potentially thousands of class files for a random public class, it can just go to the file.
- This probably doesn't matter anymore but just started the early convention that never changed
- In compilation a change to a file only affects that file. If there are multiple classes then everything has to be recompiled
- Best practice - Having multiple public classes in the same file makes things confusing. The purpose of files is to organize the source code, the purpose of folders is to organize the files. If all the classes of a particular package are in a single 100 MB super file then you've lost all the advantages and gained none of the benefits of files (plus adding lots of headache when editing)