Doubt about the initiator block

0

I would like to know why the code compiles but does not execute?

Follow the code:

package exemploinicializador2;

public class ExemploInicializador2 {

   private String nome = "Aurélio";
   private String sobrenome = "Soares";
   private  int idade = 25;
   private  double f = 354.34;

   // Bloco Inicializador
   {
    System.out.println ("Nome: " +nome);
    System.out.println ("Sobrenome: " +sobrenome);
    System.out.println ("Idade: "+idade);
    System.out.println ("F: "+f);
    }
   // Construtor
   public ExemploInicializador2 () {
       System.out.println ("Dentro do Construtor");
   }
}

The other code is:

package exemploinicializador2;

public class TesteInicializador2 {
    public static void main (String args []) {
        TesteInicializador2 objeto = new TesteInicializador2();
    }
}
    
asked by anonymous 09.05.2017 / 20:41

1 answer

5

Both codes compile and only the second one displays something. Failure to display anything on the terminal does not mean that these actions did not occur.

The reason for not displaying anything from ExemploInicializador2 is because it is not instantiated at any time. Now, if there is no instance of an object of this class, nothing of it will be executed.

Try changing the second class as below:

package exemploinicializador2;

public class TesteInicializador2 {
    public static void main (String args []) {
        ExemploInicializador2 objeto = new ExemploInicializador2();
    }
}

In this case, both will continue to be compiled and the excerpt of class ExemploInicializador2 will be executed and displayed, since we are instantiating an object.

See working at ideone

    
09.05.2017 / 21:51