What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?
public Module() {
this.name = "";
this.credits = 0;
this.hours = 0;
}
public Module(String name, int credits, int hours) {
this.name = name;
this.credits = credits;
this.hours = hours;
}
Neither of them. If you define it, it’s not the default.
The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are
String,intandint, and that the class itself is public:This is exactly the same as
And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.
See the Java specifications, specifically: Section 8.8.9. Default Constructor of Java Language Specification.
Clarification
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because