Is calling java.lang.Object constructor really necessary?

I recently installed the Eclipse outtecode plugin and found that my Test class

public class Test { } 

calls the constructor java.lang.Object

 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 constructor

Is there any reason? Judging by java.lang.Object bytecode

  public <init>()V L0 LINENUMBER 37 L0 RETURN MAXSTACK = 0 MAXLOCALS = 1 

he does not do anything. Just coming back.

+4
source share
2 answers

It must comply with section 4.9.2 of the JVM specification for structural constraints:

Each instance initialization method (ยง2.9), with the exception of the instance initialization method received from the constructor of the Object class, must call either another instance initialization method of this, or an instance initialization method of its super superclass super before its instance members access.

Now the rule can be relaxed for classes that are direct subclasses of Object , but I doubt that it will be beneficial and will be inelegant (IMO). What if the constructor Object to perform some initialization in the future? Are you sure you want a specification that allows you to get around it?

+4
source

The Java compiler should not treat java.lang.Object differently than any other base class, which probably has a more complex default constructor. Therefore, the constructor of the base class must be executed from the constructor of any subclass. This byte code is also safe for future modifications to the base class (including Object ): if someone changes the base class on some day, the subclass code should not be recompiled.

BTW changes in the base class, including Object, are not so exotic: think of tooling packages. If you want to use the JDK and, for example, count the entire created object, you want to change the bytecode java.lang.Object . Now, if the bytecode does not contain a call to the Object constructor, your tool code just won't run.

+3
source

All Articles