3

So I was looking at this question here. And people were suggesting that you can put code in a java class like so

class myClass
{
  int a;

  {
    //insert code here dealing with a
  }
}

How does the code in the brackets get executed and when does it get executed? Is there any limit to what I can put there or is it just reserved for variable initialization?

Thanks!

Community
  • 1
  • 1
Grammin
  • 11,808
  • 22
  • 80
  • 138
  • possible duplicate of [Some questions regarding Initialization Block in Java](http://stackoverflow.com/questions/2703215/some-questions-regarding-initialization-block-in-java) – Jeff Foster Oct 21 '11 at 14:22

4 Answers4

4
class X

    Foo x = something;  // a variable initializer

    // an instance initializer
    { 
        statement1 
    }

    ...

    X()
    {
        statement2
    }

the constructor is translated to

    X()
    {
        super();

        // instance initializers and variable initializers
        // in their textual order
        x = something;
        statement1    
        ...

        // the original constructor body
        statement2
    }
irreputable
  • 44,725
  • 9
  • 65
  • 93
3

This is an instance initialization block. I would recommend reading this article. It is called before any constructor in the current class is executed and after all super-class constructors have completed.

Ingo Kegel
  • 46,523
  • 10
  • 71
  • 102
2

You could write a simple test to check the order of execution of different blocks:

class MyClass {
        MyClass() {
                System.out.println("construtor");
        }

        static {
                System.out.println("static block");
        }

        {
                System.out.println("initialization block");
        }
}

Result:

static block
initialization block
construtor
Crozin
  • 43,890
  • 13
  • 88
  • 135
1

This code block is executed per instance i.e. it has access to instance methods, fields etc.

It is executed after the constructor hierarchy of that class has been executed but before that class' constructor.

Thus you have to be careful what data you access in there.

Example:

class Foo {
  protected String name;

  {
    System.out.println("Foo's name: " + name);  
  } 

  public Foo(String n) {
    name = n; 
    System.out.println("constructing Foo");
  }
}

class Bar extends Foo {
  {
    System.out.println("Bar's name: " + name); 
  }

  public Bar(String n) {
    super(n); 
    System.out.println("constructing Bar");
  }
}

If you now create a new Bar instance using new Bar("baz");, you would see this output:

Foo's name: null
constructing Foo
Bar's name: baz
constructing Bar

As you can see, the execution order of this is:

  1. Foo initializer block
  2. Foo constructor
  3. Bar initializer block
  4. Bar constructor
Thomas
  • 87,414
  • 12
  • 119
  • 157