Instance Initialization Block Part 2 Tutorial

In my Instance Initialization Block Part 1 tutorial I presented an example of how you can save time and optimize your code by using an instance initialization block. In this tutorial I explain when the instance initialization block is called and why the timing is an important to thing to become familiar with. There are a few simple rules for the execution of an instance initialization block:

  • The instance initialization block is invoked once every time an instance of a class is created.
  • The instance initialization block is invoked directly after a call to super(). Do not forget about the implicit super() call if you do not explicitly put it in your constructor.
  • Multiple instance initialization blocks execute top-down.

The following code will display the string literal "the quick brown fox jumps over the lazy dog" to the console using a mix and match of constructors and initialization blocks.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md InstanceBlockTwo
C:\Java>cd InstanceBlockTwo
C:\Java\InstanceBlockTwo>Notepad InstanceBlockTwo.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class InstanceBlockTwo {
    public static void main(String args[]) {
        new ChildClass().displayMessage();
    }
}

class ParentClass {
    ParentClass() {
        this(26);
        System.out.print("over ");
    }

    ParentClass(int pointlessVar) {
        this("huh?");
        System.out.print("fox jumps ");
    }

    ParentClass(String whatever) {
        super();
        System.out.print("brown ");
    }

    { System.out.print("the "); }

    { System.out.print("quick "); }

}

class ChildClass extends ParentClass {
 
    {
        System.out.print("the lazy ");
    }

    void displayMessage() {
        System.out.println("dog");
    }   
}

Now switch back to the command prompt (CMD) and type in javac InstanceBlockTwo.java and press Enter.
Now type in java InstanceBlockTwo and press Enter.


C:\Java\InstanceBlockTwo>javac InstanceBlockTwo.java
C:\Java\InstanceBlockTwo>java InstanceBlockTwo
the quick brown fox jumps over the lazy dog


Final thoughts

If you had trouble following this tutorial, I would recommend watching it again. However, if you followed along just fine with the logic flow on this tutorial, then you are ready to proceed to my next tutorial on Static Initialization Blocks.


Tutorials