Overloaded builders: Instance initializer

2

From the point of view of compiler behavior and java class design what would be the justification for using the Instance Launcher block?

Considering the following class:

class Caneta {
    public Caneta() {
        System.out.println("Caneta:constructor");
    }
    public Caneta(String a) {
        System.out.println("Caneta:constructor2");
    } 

    /** ################################### */
    /** Inicializador de Instância */
    /** ################################### */
    {
        System.out.println("Caneta:init1");
    }

    /** ################################### */
    /** Inicializador de Instância */
    /** ################################### */
    {
        System.out.println("Caneta:init2");
    }
    /** ################################### */

    public static void main(String[] args) {
        new Caneta();
        new Caneta("aValue");
    }
}

The output of the previous code is:

Caneta:init1
Caneta:init2
Caneta:constructor
Caneta:init1
Caneta:init2
Caneta:constructor2

Why do you think you need an instance initializer if you can initialize your instances using constructors?

Reference:

[MALA GUPTA, 2015], OCP Java SE 7 Programmer II
Certification Guide : PREPARE FOR THE 1ZO-804 EXAM

    
asked by anonymous 31.03.2017 / 04:02

1 answer

2

This is a good explanation:

  

Instance initializers are useful alternatives to instance variable initializer when:

     
  • Initialization code should catch exceptions;
  •   
  • Perform extensive calculations that can not be represented with an instance variable initializer.
  •   

You can of course always write such code in constructors.   However, in a class that has multiple constructors, you would repeat the code in each constructor. With this alternative, you can write the code only once, and it will run regardless of which constructor is used to construct the object. They are also useful in inner class anonymous, which can not declare a constructor.

     

These initializers (as well as variable ones) can not refer to variables declared textually later in the code. When an object is created, the initializers are executed in textual order - their order of appearance in the source code. This rule helps prevent initializers from using instance variables that have not yet been properly initialized.

Source: JavaWorld Object initialization in Java .

    
31.03.2017 / 05:32