Why does Java generate multiple lump files when compiling?

In Java, when compiling, 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 generation of the .class file?
Is this to simplify the reusablity class?
Why not create one .class for one .java file?

+7
java
source share
3 answers

In response to the risky question @Jon Skeet:

Another class then refers to Bar, so the JVM needs code for it ... how would you suggest finding a file?

Suppose (hypothetically) that the format of a Java class is nested / inner classes, inserting them into a class file for the outermost class. The binary name for the string is " Lsome/pkg/Foo$Bar; ". The class loader can split the name into the $ character, use the first part to find the class file for Foo, and then go to the built-in representation of the Bar class.

I think the real reason that inner / nested classes have separate class files is historical. IIRC, Java 1.0 did not support nested or inner classes, so the corresponding class file formats did not need them. When Java 1.1 was created (supporting inner / nested classes), Sun wanted the class file format to be compatible with the class files created by the Java 1.0 compiler. Therefore, they decided to implement inner / nested classes as separate class files, using the reserved character " $ " in the binary class name.

A second possible reason is that the flat format makes class loading easier than the hypothetical inline format.

And finally, there was (and still is) no convincing reason for them NOT to use the flat file format. Perhaps this creates some minor scratches when some programmer wants to load inner classes using Class.forName() , but this is a pretty rare occurrence ... and the solution is straightforward.

+7
source share

The JVM should be able to find the code for this class, given its name. If there is no connection between the original file name and the code file name and you want the code file name based on the original file name, how do you expect it to load the code?

As an example: suppose I had to compile Foo.java, which contains the Bar class.

Another class then refers to Bar, so the JVM needs code for it ... how would you suggest finding a file?

Note that there is a separate deployment unit in .NET called the assembly, and the type reference also includes the assembly name, but slightly different from what you suggested.

+12
source share

This is a constructive decision regarding the compilation unit created by the developers. Compiled classes are usually combined into a jar file.

Excerpt from Java Language Spec

7.3 Compilation Units CompilationUnit is the target symbol (ยง 2.1) for the syntactic grammar (ยง 2.3) of a Java program.

Types declared in different compilation units can depend on each other, circularly. The Java compiler must organize the compilation of all such types at once.

+2
source share

All Articles