0

Going through Java documentation I had a question about initializer blocks. The documentation says under section Initializing Instance Members:

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

To test this I tried to implement it as below.

class First{

    {
        System.out.println("A Block");
    }
    First(){
        System.out.println("Inside default constructor");
    }

    First(String a){
        this();
        System.out.println("Inside parameterized constructor");
        System.out.println("String = "+a);
    }
    {
        System.out.println("B Block");
    }
}

When I create an object of First class as per documentation, I was expecting the code in initializer blocks to be copied in both the constructors and printed twice, but the output I receive is as below:

A Block
B Block
Inside default constructor
Inside parameterized constructor
String = Test

Even though I am executing both the constructors. Could someone please explain what I seem to have misunderstood or is there something wrong with my execution which is causing it to not follow the documentation.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Shivam...
  • 409
  • 1
  • 8
  • 21
  • 4
    That description in the tutorial is oversimplified, basically when you `new` a Java class, first the initializer blocks are invoked, followed by your constructor call. In other words, they are not copied into every constructor, it is *as if* they are copied into the first constructor you call. – Mark Rotteveel Feb 08 '23 at 11:07
  • Related: [Are fields initialized before constructor code is run in Java?](https://stackoverflow.com/questions/14805547/are-fields-initialized-before-constructor-code-is-run-in-java) – Mark Rotteveel Feb 08 '23 at 11:12
  • Or actually, it is more correct to say that it behaves as if the initializer block is copied into each constructor which has an implicit or explicit call to super(), just after that call to super. – Mark Rotteveel Feb 08 '23 at 11:16

0 Answers0