Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>"My guess is that, until a constructor has been called for every level of the heierarchy, the object is in an invalid state. It is unsafe for the JVM to run anything on it until it has been completely constructed."</p> </blockquote> <p>Actually, it <em>is</em> possible to construct objects in Java without calling <em>every</em> constructor in the hierarchy, although not with the <code>new</code> keyword.</p> <p>For example, when Java's serialization constructs an object during deserialization, it calls the constructor of the first non-serializable class in the hierarchy. So when java.util.HashMap is deserialized, first a java.util.HashMap instance is allocated and then the constructor of its first non-serializable superclass java.util.AbstractMap is called (which in turn calls java.lang.Object's constructor).</p> <p>You can also use the <a href="http://code.google.com/p/objenesis/" rel="noreferrer">Objenesis</a> library to instantiate objects without calling the constructor.</p> <p>Or if you are so inclined, you can generate the bytecode yourself (with <a href="http://asm.objectweb.org/" rel="noreferrer">ASM</a> or similar). At the bytecode level, <code>new Foo()</code> compiles to two instructions:</p> <pre><code>NEW Foo INVOKESPECIAL Foo.&lt;init&gt; ()V </code></pre> <p>If you want to avoid calling the constructor of Foo, you can change the second command, for example:</p> <pre><code>NEW Foo INVOKESPECIAL java/lang/Object.&lt;init&gt; ()V </code></pre> <p>But even then, the constructor of Foo must contain a call to its superclass. Otherwise the JVM's class loader will throw an exception when loading the class, complaining that there is no call to <code>super()</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload