8.4. Overloaded Constructors

Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as the class, their signatures are differentiated by their parameter lists.

			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
				
				// Below constructors (1 & 2) are overloaded constructors
				
				// 1. Explicit default constructor
				Light(){
					this.noOfWatts = 100;
					this.indicator = true;
					this.location = "Living Room";
				}
				
				// 2. Non default constructor
				Light(int noOfWatts, boolean indicator, String location){
					this.noOfWatts = noOfWatts;
					this.indicator = indicator;
					this.location = location;
				}

				public static void main(String[] args) {
					// Instantiate and call the method
					
					// 3. Valid, calling explicit default constructor
					Light light = new Light();
					System.out.println("Printing values from default constructor");
					light.printLightState();
					
					// 4. Valid, calling non default constructor
					Light light1 = new Light(200,false,"Reading Room");
					System.out.println("Printing values from non default constructor");
					light1.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);
				}

			}