What kinds of constructor does Java support, and what does the compiler do when you do not declare one?
A constructor is the method that builds an object. It has the same name as the class, it has no return type at all, and it is called for you when you write new.
Java supports all the usual variations. You can write as many constructors of one class as you like, as long as their parameter lists are different. You can write a constructor that takes arguments and one that takes none. You can write a constructor that calls another constructor of the same class, which is called chaining. And you can write a constructor of a class that extends another, which must call the parent constructor first.
Here is what the compiler does when you do not declare any constructor. It quietly writes one for you. That constructor takes no arguments, it calls the parent constructor for you, and it leaves every field at the default value for its type.
public class Main {
public static void main(String[] args) {
// The compiler wrote this constructor for us.
Widget simple = new Widget();
System.out.println("default : " + simple.describe());
// This one we wrote ourselves.
Widget named = new Widget("bolt");
System.out.println("named : " + named.describe());
}
}
class Widget {
private final String name;
// We wrote this one, so the compiler did not write a default.
Widget(String name) {
this.name = name;
}
String describe() {
return "widget " + name;
}
}
There is one detail here that catches everybody. The moment you write any constructor of your own, the compiler stops writing the default one. So in the example above, the call new Widget() no longer compiles, and you have to write a constructor that takes no arguments if you want one.
The next question in this topic looks at exactly what the default constructor does.