Initialization of attributes

Asked

Viewed 173 times

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>();
    }
}

?

  • 1

    https://answall.com/q/198190/28595

  • @diegofm this is C#

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 deal with 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 constructs. It is possible to create a boot block. Such as, 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 it is possible to use the boot block, it is possible to create a method to instantiate both 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 the attribute directly, you can create several other constructors and this field will always be initialized, in the other case you will need to instantiate the attribute in all constructs or do something related to it.

Note: I speak in "instantiate" the attributes during the answer, but everything that was said also applies to variables that are not objects, that is, it is also valid to "put the value" of a variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.