0

I read that an initializer block is "an unnamed code block that contains th code that initializes the class?

For example :

class A {
  final int x;
  final int y;
  final String n;

{ 
    x = 10;
    y = 20;
}

public A(String name ) {

/* etc... etc */

I have never seen this type of code used, so I was wondering where it may be helpful. Why don't we just initialize variables in constructor ?

thanks

Caffeinated
  • 11,982
  • 40
  • 122
  • 216

2 Answers2

2

I think it can sometimes be helpful to initialize a variable immediately when it is defined.

public class Stooges {
  private ArrayList<String> stooges = new ArrayList<>();
  { stooges.add("Lary"); stooges.add("Curly"); stooges.add("Moe"); }

  // ... etc. other methods.
}

That initializer is now common to all constructors, so it avoids code duplication. You could use a private method and call similar code from within all constructors, but this way avoid even remembering to insert a method call. Less maintenance!

There could be other examples. If the initializer code calls a method that throws an exception, then you can't just assign it. You have to catch the exception.

markspace
  • 10,621
  • 3
  • 25
  • 39
1

A common use for this is the static initializer block:

class A {
    static boolean verbose;
    final int x;
    final int y;
    final String n;

static { 
    verbose = doSomethingToGetThisValue();
}

public A(String name ) {

/* etc... etc */

This is useful because your static variables might be used by a static method before an instance of the class is ever created (and therefore before your constructor is ever called).

See also this SO answer.

Community
  • 1
  • 1
Jason
  • 11,744
  • 3
  • 42
  • 46