Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using initialization blocks? [duplicate]

I know that Initialization blocks run when the class is first loaded (a static initialization block) or when an instance is created (an instance initialization block).

class SmallInit {
   static int x;
   int y;
   static { x = 7 ; } // static init block
   { y = 8; } // instance init block
}

But what is the special benefit of this, when we can do it like this:

class SmallInit {
   static int x = 7;
   int y = 8;
}
like image 890
Bhushan Avatar asked Oct 21 '25 15:10

Bhushan


1 Answers

One nice thing about instance initialization blocks is that they make the Double Brace Initialization pattern possible.

Instead of this:

Set<String> names = new HashSet<String>();
names.add("Peter");
names.add("Paul");
names.add("Mary");

You can do this:

Set<String> names = new HashSet<String>() {{
    add("Peter");
    add("Paul");
    add("Mary");
}};

The first brace creates an anonymous inner class; the second starts the instance initializer block. (Note that this means names is an instance of an anonymous subclass of HashSet, but that's often not an issue. This also means that this pattern only works for non-final classes.)

This is especially useful in one-off situations where it would be convenient to initialize an object as an expression. For example:

doSomethingToSet(new HashSet<String>() {{
    add("Peter");
    add("Paul");
    add("Mary");
}});
like image 172
Wayne Avatar answered Oct 24 '25 07:10

Wayne