In Java, on compilation we get a .class file for each class( including nested classes and interfaces) defined in the source file.
What is the reason for this multiple
In response to @Jon Skeet's rhetorical question:
Another class then refers to Bar, so the JVM needs the code for it... how would you suggest it finds the file?
Suppose (hypothetically) that the Java classfile format represented nested / inner classes by embedding them in the classfile for the outermost class. The binary name for the Bar is "Lsome/pkg/Foo$Bar;
". The class loader could split the name at the "$
" character, use the first part to locate the classfile for Foo, and then navigate to the embedded Bar class representation.
I think that the real reason that inner/nested classes have separate classfiles is historical. IIRC, Java 1.0 did not support nested or inner classes, and hence the corresponding classfile formats did not need to deal with them. When Java 1.1 was created (supporting inner/nested classes), Sun wanted the classfile format to be compatible with the classfiles produced by the Java 1.0 compiler. So they chose to implement inner / nested classes as separate classfiles, using the reserved "$
" character in the binary classname.
A second possible reason is that the flat format simplifies class loading compared to a hypothetical embedded format.
And finally, there was (and still is) no compelling reason for them NOT to use a flat file format. It maybe creates some minor head-scratching when some programmer wants to load inner classes using Class.forName()
but that is pretty rare occurrence ... and the solution is straight-forward.