简体   繁体   中英

Is calling java.lang.Object constructor really necessary?

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.

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM