When does the compiler generate a default constructor for you, and what does it leave the object with?
The compiler writes a default constructor for you in one case only. That is when your class has no constructor written in it at all.
public class Main {
public static void main(String[] args) {
Settings s = new Settings();
System.out.println(s.name + "|" + s.retries + "|" + s.verbose);
}
}
And what does it leave the object with? It sets every field to the default value for its type, and nothing else. There is no check, no message and no default that is meaningful to the domain.
the type of the field the default value
---------------------- -----------------
int, long, short, byte 0
double, float 0.0
boolean false
char the null character
an object reference null
So here is the class and what it looks like without a constructor.
public class Settings {
private String name;
private int retries;
private boolean verbose;
}
And the output of the program is null|0|false, because that is what the default constructor left in the three fields. The name is null, the retries are zero and the verbose flag is false.
And that is the problem with the default constructor. It creates an object that is valid as far as Java is concerned and nonsense as far as your domain is concerned. A Settings with a null name is not a thing that makes sense, and the code has to check for it everywhere.
the field type the default is it sensible for the domain
-------------------- --------------- ------------------------------
String null no
int 0 sometimes
boolean false sometimes
a list null no
And there is a second detail worth knowing about. The default constructor is only there when the class has no constructor of its own. As soon as you write one, the compiler stops making it for you. So a class with a constructor that takes a name cannot be created with new Settings() any more, and the compiler tells you so.
And the third detail is about the parent class. If your class extends another class and the parent has no no-argument constructor, then you cannot have a default constructor either, because the compiler has to call something in the parent. So the default constructor only appears when the whole chain of parents allows it.
So the rule to remember is this. The free default constructor leaves every field at the language default, which is often not a sensible starting point.
The last question in this topic is about what happens when you write your own constructor.