Single-line declarations cannot contain complex initialization logic.
If you initialize the variable as:
class AnotherClass { MyClass anObject = new MyClass();
then you will find that you cannot specify the initial value in one line. You will need to place such code in the block, which quite obviously is included in the constructor (or in the non-static initialization block):
Using constructor:
class AnotherClass { MyClass anObject; AnotherClass() { try{this.anObject = new MyClass();}catch(SomeException e){} } }
Using the initialization block:
class AnotherClass { MyClass anObject; { try{this.anObject = new MyClass();}catch(SomeException e){} } }
I found that the latter makes less comprehensible code, because the declaration and initialization are separate from each other, and initialization does not occur in the constructor-encoded constructor (although there is no difference at run time).
The same goes for other complex procedures related to field initialization. For example, if you intend to initialize an Array or Collection and set the contents of the array / collection to some default value, you should do this inside the constructor:
class AnotherClass { Integer[] integers; AnotherClass() { this.integers = new Integer[10]; for(Integer integer: integers) { integer = Integer.MIN_VALUE; } } }
source share