1

While searching for a way to define static constructors, I've stumbled upon the use of the following:

class MyClass {
    { /* code for constructor-like (?) effect */ }
}

Basically the code that is entered in curly brackets directly in the class works, as far as I can see, exactly the same as a code in a constructor - except that it is called before the constructor.

What is the purpose of this, and are there other differences between this and a standard constructor?

Thanks in advance,

Acidic
  • 6,154
  • 12
  • 46
  • 80
  • Don't get confused with the curly brackets. Those are not necessary. – Sarwar Erfan Nov 28 '11 at 12:13
  • @Sarwar Erfan: Nope; they are, otherwise you can't get "code with constructor like effect". For e.g. catching exceptions etc. – Sanjay T. Sharma Nov 28 '11 at 12:15
  • @SanjayT.Sharma: Ok, they are called before constructor, so I would not call it "constructor like" effect. If you omit the curly brackets, you cannot catch excpetions, but aren't the calling time and result same? – Sarwar Erfan Nov 28 '11 at 12:19

2 Answers2

8

Those are called instance initializers. The details can be found in another SO question.

Community
  • 1
  • 1
Sanjay T. Sharma
  • 22,857
  • 4
  • 59
  • 71
  • Thanks. (Exactly same answer as Jesper, but he answered first so I have to give him the accepted answer) – Acidic Nov 28 '11 at 12:49
3

The block with the curly brackets is an instance initializer block. This page from Oracle's Java Tutorials has some more info about it.

Also see: How is an instance initializer different from a constructor?

Community
  • 1
  • 1
Jesper
  • 202,709
  • 46
  • 318
  • 350