8.2. The Default Constructor

A default constructor is a constructor without any parameters, i.e., it is a no-parameter constructor. It has the following signature:

<class name>()

Implicit default constructor: If a class does not specify any constructors, then an implicit default constructor is generated for the class by the compiler.The implicit default constructor is equivalent to the following implementation:

<class name>(){
super();
} // No parameters. Calls super class constructor.

The only action taken by the implicit default constructor is to call the superclass constructor. This ensures that the inherited state of the object is initialized properly.

Note: We'll learn about the super() call / invoking superclass constructor while learning about constructor chaining in coming chapters.

Let’s build a new class Light to learn about default constructors, non default constructors and overloaded constructors in Java.

			package javatutorial;

			/**
			 *  Example class to learn about default constructors, non default constructors 
			 *  and overloaded constructors in Java.
			 *  
			 *  @author f5java.com
			 */
			public class Light {
				
				// Fields:
				int noOfWatts; // wattage
				boolean indicator; // on or off
				String location; // placement
				
				// 1. No constructor, compiler generates a default constructor

				public static void main(String[] args) {
					// Instantiate and call the method
					
					Light light = new Light(); // call to implicit default constructor
					light.printLightState();

				}
				
				/**
				 * Prints the state of light object
				 * 
				 */
				public void printLightState(){
					System.out.println("Printing current state of Light");
					System.out.println("No of Watts: " + noOfWatts);
					System.out.println("Is light on: " + indicator);
					System.out.println("Location of light : " + location);
				}

			}