Subba
Subba

Reputation: 406

Does anyone really use Object initialize blocks in Java ? Was this used anywhere in Java API?

I know Java supports the object initialization blocks as shown below. The following code shows that the object initialize block always calls when the TestObjectInitialize instance has been created.

public class TestObjectInitialize {

    public int abc;

    //object initialize block
    {
      abc= 5;
    }

    public TestObjectInitialize() {

    }


    public static void main(String... args) {
          TestObjectInitialize toi = new TestObjectInitialize();
          System.out.println(toi.abc);
    }

}

Upvotes: 1

Views: 97

Answers (3)

Vishal K
Vishal K

Reputation: 13066

Does anyone really use Object initialize blocks in Java ?

Answer is Yes . Now the Question is Why?
If you have final variables that may require programming logic to set them. Because , a final variable MUST be set before the constructor is called, and the only way to do this is to set it to some hard coded value during declaration , or to set it inside of an initializer block. Although , It can also be done in constructor But what if you have more than one constructor defined in clas?? Then you would have to initialize that final variable in every constructor which leads to code redundancy. For more information watch here and here.

Was this used anywhere in Java?

I have not seen it in any API of Java till now . But we most of the times use it in codes like following way:

private final Set<String> VALID_CODES = new HashSet<String>() {{
    add("XZ13s");
    add("AB21/X");
    add("YYLEX");
    add("AR2D");
 }};

Upvotes: 1

jdb
jdb

Reputation: 4519

I have seen people do this:

Map<String, String> map = new HashMap<String, String>() {{
    put("key1", "value1");
    put("key2", "value2");
}};

It can be useful when you have a method

class Init {
    static int initFoo(Map<String, String> map) {
        // ...
    }
}

You can call it like this:

class FooBar {
    static int foo = Init.initFoo(new HashMap<String, String>() {{
                        put("key1", "value1");
                        put("key2", "value2");
                     }});
}

Upvotes: 4

bikeshedder
bikeshedder

Reputation: 7487

I have used the static variant of it several times. e.g. it can be used to initialize a collection inside the class:

static List<String> words = new ArrayList<String>();
static {
    words.add("foo");
    words.add("bar");
}

The main benefit of this is that you keep declaration and initialization at the same place. A non static initializer still has the benefit that runs for all constructors without you having to chain the constructors.

public class Foo {
    int value;
    {
        value = getDefaultValue();
    }

    public Foo() {
    }
    public Foo(String something) {
    }

}

value = getDefaultValue() is executed regardless of the ctor being used.

Upvotes: 2

Related Questions