Default constructors
As mentioned previously, a default constructor (a.k.a. a “no-arg” constructor) is one without arguments that is used to create a “basic object.” If you create a class that has no constructors, the compiler will automatically create a default constructor for you. For example:
//: c04:DefaultConstructor.java
class Bird {
int i;
}
public class DefaultConstructor {
public static void main(String[] args) {
Bird nc = new Bird(); // Default!
}
} ///:~
The line
new Bird();
creates a new object and calls the default constructor, even though one was not explicitly defined. Without it, we would have no method to call to build our object. However, if you define any constructors (with or without arguments), the compiler will not synthesize one for you:
class Hat {
Hat(int i) {}
Hat(double d) {}
}
Now if you say:
new Hat();
the compiler will complain that it cannot find a constructor that matches. It’s as if when you don’t put in any constructors, the compiler says “You are bound to need some constructor, so let me make one for you.” But if you write a constructor, the compiler says “You’ve written a constructor so you know what you’re doing; if you didn’t put in a default it’s because you meant to leave it out.”