Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

166
Visualizações
Why Would a Default Constructor and a Parameterized Constructor Both Be In a Class?

I have a segment of Java code here where an abstract class has been created. Something I'm confused on with this segment, though, is why the writer decided to use both a default constructor and a parameterized constructor.

abstract class Person {
    String personName;
    String personID;

    //default consructor
    Person() {
    
    }

    //parameterized constructor
    //assigns personName and personID to object at time of creation
    Person(String personName, String personID) {
        this.personName = personName;
        this.personID = personID;
    }

    //getters and setters

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public String getPersonID() {
        return personID;
    }

    public void setPersonID(String personID) {
        this.personID = personID;
    }
}

Can somebody explain why both of these constructors have been written rather than just one or the other?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Hibernate requires a no-argument constructor, it uses reflection to call the no-arg constructor when it needs to instantiate a persistent class. So a constructor can be present due to its being needed by a library or framework.

Apparently the other constructor is there as a convenience so the programmer can set the name and ID without calling separate setters.

If you want you can make the no-arg constructor private and Hibernate can still use it.

There is a pattern called constructor chaining (described here: Is it good or bad to delegate to another constructor (using this()) within a constructor) which shows how multiple constructors can make sense, but the code shown isn’t doing that.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda