Reputation: 136002
I've recently installed bytecode outline Eclipse plugin and discovered that my Test class
public class Test {
}
calls java.lang.Object's constructor
public class Test {
public <init>()V
L0
LINENUMBER 15 L0
ALOAD 0
INVOKESPECIAL java/lang/Object.<init>()V
RETURN
L1
LOCALVARIABLE this LTest; L0 L1 0
MAXSTACK = 1
MAXLOCALS = 1
}
INVOKESPECIAL java/lang/Object.<init>()
V means calling java.lang.Object's constructor
Does it make any sense? Judging by java.lang.Object bytecode
public <init>()V
L0
LINENUMBER 37 L0
RETURN
MAXSTACK = 0
MAXLOCALS = 1
it's doing nothing. Just returns.
Upvotes: 4
Views: 759
Reputation: 115328
Java compiler should not treat java.lang.Object
differently than any other base class that probably has more sophisticated default constructor. Therefore the constructor of base class must be executed from constructor of any subclass. This byte code is also safe for future modifications of base class (including Object
): if one day somebody changes base class the code of subclass should not be re-compiled.
BTW changes in base class including Object are not so exotic: think about instrumentation packages. If you want to instrument the JDK and for example count all created object you want to modify byte code of java.lang.Object
. Now, if byte code does not contain invocation of Object
constructor your instrumented code just will not run.
Upvotes: 3
Reputation: 1500275
It has to in order to satisfy section 4.9.2 of the JVM specification on structural constraints:
Each instance initialization method (§2.9), except for the instance initialization method derived from the constructor of class Object, must call either another instance initialization method of this or an instance initialization method of its direct superclass super before its instance members are accessed.
Now the rule could be relaxed for classes which are direct subclasses of Object
- but I doubt that it would have any benefit, and would be inelegant (IMO). What if the Object
constructor did perform some initialization in the future? Would you really want a spec which allowed you to bypass it?
Upvotes: 4