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?
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.