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. Its as if when you dont 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 Youve written a constructor so you know what youre doing; if you didnt put in a default its because you meant to leave it out.