2
From the perspective of compiler behavior and java class design what would be the justification for using the Instance Initializer 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 constructs?
Reference:
[MALA GUPTA, 2015], OCP Java SE 7 Programmer II
Certification Guide: PREPARE FOR THE 1ZO-804 EXAM
@Tiagos, the two questions I asked are different. A question about the behavior of overloaded methods and another question about using Instance Initializer from the compiler and java class design point of view. Are not duplicates!
– pss1suporte