I am a passionate software developer and consultant on Java and related technologies since 2002. I have keen interest in reading, writing tech blogs and designing enterprise applications in Java. Upendra is a DZone MVB and is not an employee of DZone and has posted 5 posts at DZone. You can read more from them at their website. View Full User Profile

Revisiting Basics: Execution Sequence while loading a class

08.20.2011
| 3527 views |
  • submit to reddit

Here, we discuss how Java's call sequence behaves when an object is being instantiated. I explain this with a parent-child class relationship to help you better understand when a class is in hierarchy.

Call Sequence with an example

Our example implements two classes

  1. ParentClass
  2. ChildClass

As the names resemble ChildClass is extending from ParentClass, and we create an instance of ChildClass to monitor the execution call sequence

  1. The first thing that is executed while loading(the object is not yet fully created) a class is static variable initialization and the static blocks in parent class followed by child class static variable initialization and the blocks.
  2. The next thing is the parent class initialization block followed by the parent class constructor.
  3. The last thing is the child class initialization blocks followed by child class constructor.

When the execution control finishes executing sub class constructor, that is when we say the object is fully created and is ready to use.

The following code-snippet and it’s output explains this behavior.

package com.accordess.blogs;
 
/**
 *
 * @author
 */
 
public class ChildClass extends ParentClass{
 
    static{
        System.out.println("Child class static instance block") ;
    }
    {
        System.out.println("Child class instance block") ;
    }
 
    public ChildClass(){
        System.out.println ("Child class constructor") ;
    }
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new ChildClass () ;
    }
}
 
class ParentClass{
    private static int value = 10 ;
    static{
        System.out.println ("Parent Class static innitialization block : "+value) ;
    }
    {
        System.out.println ("Parent Class innitialization block") ;
    }
    protected ParentClass (){
        System.out.println ("Parent Class consutructor") ;
    }
 
}
 
Output:
Parent Class static innitialization block : 10
Child class static instance block
Parent Class innitialization block
Parent Class consutructor
Child class instance block
Child class constructor

From http://accordess.com/wpblog/2011/06/06/revisiting-basics-execution-sequence-while-loading-a-class/

Published at DZone with permission of Upendra Chintala, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: