Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why instance initiazer block in java executed only once?

Tags:

java

class B {

    {
        System.out.println("IIB B");
    }

    B(int i) {
        System.out.println("Cons B int");

    }

    public B() {
        this(10);
        System.out.println("Cons B");
    }
}

public class C extends B {

    {
        System.out.println("IIB C");
    }

    public C() {
        System.out.println("Cons C");
    }

    public static void main(String[] args) {
        C c1 = new C();
    }
}

Output

 IIB B
Cons B int
Cons B
 IIB C
Cons C

As per Oracle tutorials ,

"The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors."

So why initializer blocks of class B is not executed twice as constructor is executing twice?

like image 289
Ravi Godara Avatar asked Feb 28 '14 08:02

Ravi Godara


2 Answers

So why initializer blocks of class B is not executed twice as constructor is executing twice?

No, the constructor runs only once. Delegating work to another constructor is taken into account by the compiler and the instance initializers are not copied into a constructor which begins with a this() invocation.

In general, you don't need to bother reasoning about where exactly the instance initializer code is copied. Simply rely on the fact that it will run once and only once for each object initialization.

The moment at which instance initializers run is immediately after completing the super() constructor call.


A terminological note

The link you include in your question is not the Javadocs, but an Oracle Tutorial. There is a very important difference between these two: Javadocs are normative whereas the tutorials are only descriptive. Some wording in the tutorials may be imprecise as a compromise between teaching value and factual accuracy.

If you ever have a doubt about something you have read in a tutorial, then try to find the authoritative statement in the Java Language Specification or the JDK Javadoc.

like image 63
Marko Topolnik Avatar answered Oct 26 '22 23:10

Marko Topolnik


You have created only one instance of B.i.e. an instance of C. so, it will get printed only once since the constructor runs only once. Try creating another instance of C, then you will get it printed twice.

like image 33
Keerthivasan Avatar answered Oct 27 '22 00:10

Keerthivasan