What is Instance Initializer in Java?

In this post, I will illustrate what are instance variable initializer, instance initializer, static initializer, and how the instance initializer works in Java.

1. Execution Order

Look at the following class, do you know which one gets executed first?

public class Foo {
 
	//instance variable initializer
	String s = "abc";
 
	//constructor
	public Foo() {
		System.out.println("constructor called");
	}
 
	//static initializer
	static {
		System.out.println("static initializer called");
	}
 
	//instance initializer
	{
		System.out.println("instance initializer called");
	}
 
	public static void main(String[] args) {
		new Foo();
		new Foo();
	}
}

Output:

static initializer called
instance initializer called
constructor called
instance initializer called
constructor called

2. How does Java instance initializer work?

The instance initializer above contains a println statement. To understand how it works, we can treat it as a variable assignment statement, e.g., b = 0. This can make it more obvious to understand.

Instead of

int b = 0

, we can write it as

int b;
b = 0;

Therefore, instance initializers and instance variable initializers are pretty much the same.

3. When are instance initializers useful?

The use of instance initializers are rare, but still it can be a useful alternative to instance variable initializers if:

(1) initializer code must handle exceptions
(2) perform calculations that can't be expressed with an instance variable initializer.

Of course, such code could be written in constructors. But if a class had multiple constructors, you would have to repeat the code in each constructor.

With an instance initializer, you can just write the code once, and it will be executed no matter what constructor is used to create the object. (I guess this is just a concept, and it is not used often.)

Another case in which instance initializers are useful is anonymous inner classes, which can't declare any constructors at all. (Will this be a good place to place a logging function?)

Thanks to Heinrich Hartmann for his comment:

Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are neede to execute any kinds of expressions at construction time.

Reference:
Object initialization in Java

Category >> Classes & Interfaces  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Xingxian Li
  • Very useful.

  • vokavoka

    The problem is that your example does not really show the correct order, and it is **NOT** what you think you see…
    The true order is really:
    1. First static initializer.
    When we make an instance of the class:
    2. Then member variable declarations, with DEFAULT initialization, NOT explicit initialization.
    3. THEN the class constructor…. NOT a call to the instance initializer
    4. Then an implicit call to the superclass constructor.
    5. Then the explicit member variable initialization.
    6. Then the instance initializer
    7. Then the rest of the constructor

    Thus, for a member variable when you write:
    private int a = 10;
    what really is happening is more like
    private int a;
    and a
    a=10;
    early in the constructor, but after the call to the superclass constructor.

    Sometimes you need to know this, for example if the superclass constructor calls an overridden method. Look for example at the following code:

    class A
    {
    public int c = 10;
    public int d = 10;

    public A() {
    System.out.println(“Impicit call to superclass constructor. In A constructor”);
    System.out.println(“The value of c: ” + c);
    System.out.println(“The value of d: ” + d);
    printc();
    c = 15;
    }

    public void printc() {
    System.out.println(“In A.printc – we should never get here…”);
    System.out.println(“In A.printc. c is: ” + c);
    System.out.println(“In A.printc. d is: ” + d);
    }
    }

    class B extends A
    {
    // variables are not overridden, but hidden…
    public int d = 10;
    private int e = 5;

    static {
    System.out.println(“In B static initializer”);
    }

    {
    System.out.println(“In B instance initializer”);
    System.out.println(“c is not set set, c is : ” + c);
    System.out.println(“The value of d is: ” + d);
    System.out.println(“The value of e is: ” + e);
    c = 20;
    d = 20;
    System.out.println(“c is set to 20, now c is : ” + c);
    System.out.println(“d is set to 20, now d is : ” + d);
    }

    public B() {
    // Here we have an implicit call to super();
    System.out.println(“In B constructor”);
    System.out.println(“c is not set set, c is : ” + c);
    System.out.println(“d is not set set, d is : ” + d);
    c = 30;
    d = 30;
    System.out.println(“c is set to 30, now c is : ” + c);
    System.out.println(“d is set to 30, now c is : ” + d);
    }

    public void printc() {
    System.out.println(“In B.printc”);
    System.out.println(“In B.printc. c is: ” + c);
    System.out.println(“In B.printc. d is: ” + d);
    System.out.println(“in B.printc. e is: ” + e);
    }

    public static void main(String[] args) {
    System.out.println(“Start of static main”);
    B b = new B();
    System.out.println(“End of static main”);
    }
    }

    The output is:
    In B static initializer
    Start of static main
    Impicit call to superclass constructor. In A constructor
    The value of c: 10
    The value of d: 10
    In B.printc
    In B.printc. c is: 10
    In B.printc. d is: 0
    in B.printc. e is: 0
    In B instance initializer
    c is not set set, c is : 15
    The value of d is: 10
    The value of e is: 5
    c is set to 20, now c is : 20
    d is set to 20, now d is : 20
    In B constructor
    c is not set set, c is : 20
    d is not set set, d is : 20
    c is set to 30, now c is : 30
    d is set to 30, now c is : 30
    End of static main

    As you can see, as soon as we make an instance of B, the first thing that happens is a call to the superclass constructor! It prints out c and the local value of d. It then calls printc. Since printc is overridded, it will call B.printc. It prints out c=10, d=0 and e=0 !!! d, which hides a.d, is 0. The explicit value is not set yet!!! c = 10 since it was set early in the A constructor. Then execution returns to the A constructor, c is set to 15, and then execution returns to the B constructor. Now the B instance initializer is run. We can see that the A constructor is already run since c=15, which was set last in the A constructor. Now, however, d is set to 10! Thus d must have been set after the call to the superclass constructor but before the execution of the instance initializer. The same holds for e, which was 0 in the call to B.princ but which now is 5. Then the rest of the B constructor is executed.

    Thus the order is: static initializer, then, when we make an instance, the construcor is called. The first thing that happens in the constructor is a call to the superclass constructor. When returning from the superclass constructor all EXPLICIT member variable initialization occurs but not until after the superclass constructor has returned, then the instance initializer is called, and then the rest of constructor is run.
    Thus if we write it out explicitly:
    class A {
    private int a = 10;
    { a = 20 }
    public A() {
    a = 30;
    }
    }
    Really is:
    class A {
    pritvate int a;

    public A() {
    super();
    a = 10;
    // instance initializer
    a = 20;
    // rest of the construtor
    a = 30;
    }
    }

    Really a bit strange.

  • derhein

    Also note that Anonymous classes that implement interfaces [1] have no constructors. Therefore instance initializers are neede to execute any kinds of expressions at construction time.

    [1] http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#syntax-of-anonymous-classes

  • lol

    r u tard?

  • Siraj

    I want to know how to get an JComboBox to auto suggest the elements when we type in the combo box. For an example, If I had loaded a JComboBox with these names using MySQL, [Amila, Nimila, Nikila, Sunil] and when I type “N” inside the Combo Box, it’ll drop down the list only showing Nimila & Nikila as suggestions. And I’m trying to do this on NetBeans. Thanks.