|
Sometimes you will find that a class definition does not have even a single constructor defined in it. When a compiler encounters such class, it creates a default constructor on the fly. This constructor is called as the default constructor. It takes no parameters and simply invokes the superclass constructor with no arguments. The default constructor is implicitly given the access modifier of the class. For example, if the class is public, the default constructor is implicitly public.
|
|
Default constructor is different than default access constructor. Default constructor is created by the compiler whereas the default-access constructor (constructor without any modifier) is created by the programmer. |
Listing 3.22 illustrates the presence of default constructor that the compiler will create for class Apple.

When you run DefaultConstructorTest, the output may surprise you if you do not know about default constructor. Even though it appears that Apple has no constructor, the Compiler creates one (the default constructor) and (if you could see it) it would look something like this:
Apple() {
super();
}
Now when you create an Apple object (at runtime), this (invisible) default constructor of Apple is called, which in turn calls the superclass (Fruit’s) constructor. Therefore, the message “In Fruit Constructor” will be printed on console.
Note that the Fruit class must have an accessible constructor that takes no arguments. If not, you will get a compile-time error while compiling the Apple class because the default constructor for Apple would try to make a call with super() to the Fruit constructor with no arguments, and will fail to access it. For example, if you change the access modifier of Fruit constructor (in listing 3.22) to private, you will get a compile-time error for Apple class.
Also note that compiler creates default constructor only when a class has no constructor at all. For example, if you define even a single constructor for Apple class, either with or without arguments, the default constructor will not be created.