2016-03-04

Java’s object lifecycle


The JVM initializes classes and objects before they are used. Class initialization consists of class field initializers and class initialization blocks. Object initialization consists of constructors, object field initializers, and object initialization blocks. Class initialization always completes before the first object is created from the class.





<clinit>() methods

When compiling class initializers and class initialization blocks, the Java compiler stores the compiled bytecode (in top-down order) in a special method named <clinit>(). The angle brackets prevent a name conflict: you cannot declare a <clinit>() method in source code because the < and > characters are illegal in an identifier context.

<init>() methods & calling constructors

After loading a class, the JVM calls this method before calling main() (when main() is present).

When a class doesn't extend another class, the <init>() method begins with bytecode to call the Object() constructor. When a constructor starts with super(), <init>() begins with bytecode to call the superclass constructor. When a constructor begins with this() (to call another constructor in the same class), <init>() begins with the bytecode sequence for calling the other constructor; it doesn't contain code to call a superclass constructor.

Javaworld