Is it correct to create a constructor method in an abstract class?

9

If an abstract class can not be instantiated, creating a constructor method for this abstract class can be considered as good practice or not? If so, what is the reason for creating the implementation of this method?

Here is a snippet of code that illustrates my question:

public abstract class Funcionario {

    private String nome;
    private int numeroRegistro;

    public Funcionario(int numeroRegistro) {
        setNumeroRegistro(numeroRegistro);
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getNumeroRegistro() {
        return numeroRegistro;
    }

    public void setNumeroRegistro(int numeroRegistro) {
        this.numeroRegistro = numeroRegistro;
    }

    public abstract double obterSalarioBruto();

    @Override
    public String toString() {
        return "Funcionario [getNome()=" + getNome() + ", getNumeroRegistro()=" + getNumeroRegistro() + "]";
    }

}
    
asked by anonymous 27.09.2015 / 03:43

1 answer

9

That's right, of course. Unless the builder is not needed . And it is not always. A lot of programmer builds builder without need.

But if the abstract class has states (it usually has) and they need to be initialized when an object based on it (not by direct instantiation, of course, but because another class inherited from it) is created, then the constructor needs to be called, yet which indirectly through the daughter class.

You have a question about the call of the constructor of a higher class by a lower class . It makes no difference whether the class is abstract or not.

Obviously, if the class has no state, ie internal variables, it is unlikely that a constructor is needed. But there is another problem, also not exclusive to abstract classes. And if the class has no state, it should probably be static.

Avoid calling other methods inside the constructor. Normally it should initialize the variables directly. Depending on the method called it can be dangerous and put the instance in a dubious state or break the application. It does not mean that it's wrong to call the methods, just make sure it's what you want, often the boot logic is different from the assignment logic. This case is the same, so it seems appropriate to use the same. But this is an opposite of DRY . Now the code does the same, then there is a maintenance and they spend doing different things. The code starts having problems because it was conceptually ill-conceived (of course you can pack it together, but you may forget you have to). Note that I am in the field of the hypothesis, the concrete case should always be evaluated.

    
27.09.2015 / 03:55