3

According to my knowledge, if we want to do something just before object creation we want to write that code in the instance block as it called before the constructor.

For instance:

public class TestInstanceBlock {

public static int x = 0;

 public TestInstanceBlock() {
    System.out.println("This is my Default Constructor");
 }

 {
    System.out.println("This is my instance block");
    x++;
 }

 public static void main(String[] args) {

    TestInstanceBlock obj = new TestInstanceBlock();
    System.out.println("The value of x is: " + x);
 }
}

Output:

This is my instance block
This is my Default Constructor
The value of x is: 1

For above program, we can get the same output without using instance block by just writing the instance blocks code in the constructor.

For instance:

public class TestInstanceBlock {

 public static int x = 0;

 public TestInstanceBlock() {
    System.out.println("This is my instance block");
    x++;
    System.out.println("This is my Default Constructor");
 }

 public static void main(String[] args) {

    TestInstanceBlock obj = new TestInstanceBlock();
    System.out.println("The value of x is: " + x);
 }
}

Output:

This is my instance block
This is my Default Constructor
The value of x is: 1

So, then what will be the advantage to use instance block approach over constructor approach?

  • @Ben The first statement is not correct. Instance initialization block is called *before* its class constructor (but *after* the superclass constructors). – Roman Puchkovskiy Apr 03 '18 at 08:58
  • 1
    @Ben the duplicate answers plenty of questions if you bother to read it. – Kayaman Apr 03 '18 at 08:59
  • @RomanPuchkovskiy 100% correct, my bad. – Ben Apr 03 '18 at 09:00
  • 1
    @Kayaman I could not find anything besides the last sentence in the answer by aioobe so I thought linking another answer on the topic would at least not hurt anyone. – Ben Apr 03 '18 at 09:01
  • You should be able to add to the linked topics by flagging as (potential) duplicate, although I'm not sure if you have the points for it. Well, linked it anyway. – Kayaman Apr 03 '18 at 09:05

0 Answers0