Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!