Initialization of attributes

4

Is there any difference between initializing an attribute like this:

public class Turma {

    private List<Aluno> alunos = new ArrayList<Aluno>();
}

Or so:

public class Turma {

    private List<Aluno> alunos;

    //Considerando que este é o único construtor
    public Turma() {
        alunos = new ArrayList<Aluno>();
    }
}

?

    
asked by anonymous 06.07.2017 / 21:16

1 answer

2

Underneath the cloths there are no differences. In the end, the instantiation of the attribute will be placed inside the constructor anyway.

However, in the first case, it is impossible to handle exceptions or any other operation that is necessary to work the value to be placed in the attribute.

Still this does not mean that the initialization of these attributes needs to be done in the constructors. You can create a startup block. Like, for example:

public class Turma {
   private ArrayList<Aluno> alunos;

    { // bloco de inicialização
        try {
            alunos = new ArrayList<Aluno>();
        }catch(Exception ex) {
            // Fazer algo
        }
    }
}

In the same way that you can use the initialization block, you can create a method for instantiating both the instance and static attributes.

In the Java documentation there is a section that talks a little about this.

Another difference (obvious, by the way) is that if you instantiate directly in the attribute, you can create several other constructors and this field will always be initialized, in the other case it will be necessary to instantiate the attribute in all the constructors or to do something relative to that.

Note: I speak of " instantiate " the attributes during the response, but everything that has been said is also valid for variables that are not objects, that is, it is also valid for "put value "of a variable.

    
06.07.2017 / 21:20