Friday, September 19, 2014

Constructor overloading and constructor chaining in Java

Whenever people just say constructor is just like a method, I'm really scared about their understanding and I really pity on constructor. The concept of constructor is completely different from a normal method. When we actually want to dig in to the core concepts, one of the key point to learn is about constructor which is used to initialize the class properties (or any other initial business logic after initialization of properties) while object creation.


What exactly we have to say is it looks like just a method but which is entirely a different thing and lot of things happen under the hood when you invoke constructor. To create an instance we must need a constructor for every Java Class. A good point to remember here is, a constructor never return anything.
JavaConstructor jCInstance = new JavaConstructor(); 
If you see the above line of code JavaConstructor is the class name and JavaConstructor() is the constructor of it. 
class JavaConstructor{  
   JavaConstructor() {   //default or no argument constructor
   //do something   
   }  
 }  
To be valid the class declaration of JavaConstructor must be the simple name of the class. Here in the above declaration I left the access modifier as default for the constructor.

 Argumented Constructor:-

An argumented constructor is which used to pass required information to the class while creating an object. Below example demonstrates that how Bus class is forcing the consumers to pass the number of seats  while creating a Bus.
Class Bus{   
  int seats;  
   Bus(int seats) {  // argumented constructor  
   this.seats = seats;  
   //do something    
   }   
  }  
Now whom so ever want to create a Bus, they can pass the no.of seats required to the Bus class. Just for example I took seats. Depends on the requirement's the arguments list may vary(color,length etc ..).
Bus volvoBus = new Bus(34); //passing seat count
Bus ordinaryBus = new Bus(28); //passing seat count

The points to note here are
  • If you forgot to write or not intentionally writing a constructor to your class, JVM creates a one for you internallywhich is a default no argument constructor.
  • If you provide a default (no arg) constructor, JVM uses it to instantiate.
  • If you are not providing default constructor and providing a argumented constructor, then consumers definitely needs to pass the required parameters. In this case, consumers cannot use default constructor anymore since you provided a argumented one and not providing default on while creating object. If they try to use default one compiler error occurs. 
Constructor Overloading:-

Just like method overloading in Java, there is constructor overloading too. Overloading a constructor means providing multiple constructors differing in arguments for a Class. For ex:
public class Bus {  
      int noOfSeats;  
      String busColor;  
      public Bus() {  
           System.out.println("This is default constructor");  
      }  
      public Bus(int seats) {  
         this.noOfSeats = seats;  
           System.out.println("To call this constructor, you need need to pass no of seats");  
      }  
      public Bus(int seats, String color) {  
         this.noOfSeats = seats;  
         this.busColor = color;  
           System.out.println("To call this constructor, you need to pass bus color");  
      }  
 }  
If you see there are multiple constructors provided with different arguments. We just overloaded the constructor. When we want to create a required bus we have to just use the appropriate constructor. It's up to us to create/passing info while creating a bus. You may buy a bus with 20 seats and color it later. Creating different types of buses is possible with above provided constructors.
class BusCreator {  
      public static void main(String[] args) {  
           Bus bus = new Bus();// I just need a bus'  
           Bus seatsBus = new Bus(20);// I need a bus with 20 seats  
           Bus coloredBus = new Bus(25, "Blue");// Need a blue color bus with 20 seats.  
      }  
 }  

Constructor Chaining-

Like the confusion between method and constructor, few usually state that invoking Parent class constructor from Child is constructor chaining. No. That is not 100% true. Weather it is own constructor or Parent constructor, invoking one constructor from other can state as constructor chaining. Lets see the below examples how usually chaining the constructor happens with in the same class and with Parent class.


We chain(calling) one constructor from other with in the same classso that we can avoid code duplication. Without chaining every constructor have whole business logic and that leads to code duplication and hard to maintain the code as well.
public class Bus {  
      int noOfSeats;  
      String busColor;  
      public Bus() {  
           constructBus();  
      }  
      public Bus(int seats) {  
           this();// calling default constructor for business logic.  
           this.noOfSeats = seats;  
      }  
      public Bus(int seats, String color) {  
           this(seats); // Using another constructor and proceeding..  
           this.busColor = color;  
      }  
      private void constructBus() {  
           // Whole process of constructing bus.  
      }  
 }  
Below we chained Parent constructor to Child constructor as below to pass the required information to Parent while creating a Child object.



public class Vehicle {  
      private String vehicleName;  
      public Vehicle(String name) {  
           this.vehicleName = name;  
      }  
 }  
 class Bus extends Vehicle {  
      int noOfSeats;  
      String busColor;  
      public Bus() {  
           super("bus"); // calling super constructor.  
           constructBus();  
      }  
 }


Update: The folks at Webucator, a provider of Java training, put together a video tutorial for this article.









Post a Comment