Scientech Easy Constructor Chaining in Java with Example programs | Scientech Easy

Friday, March 22, 2019

Constructor Chaining in Java with Example programs

Constructor Chaining in Java


First of all, we understand the definition of chaining in Java. The definition of Chaining in Java is " a set of links which connect one constructor to another constructor". Thus, we can define Constructor chaining as "Constructor chaining in Java is a technique of calling one constructor from another constructor using "this()" and "Super()" keyword"

When you will use constructor chaining, it is important to understand the order in which the constructor will execute. The constructor chain is followed until it reaches the last chained constructor and the end of the chain will always be object's class constructor because of the inheriting every class from the object class by default.

Now see the below figure which shows that a class College with three constructors in which first we called the two parameter constructor after that one parameter constructor called using this(parameters) keyword and then called the default constructor. That's the order of execution. You can also change the order as you like. Therefore, it is important to understand the order of execution of the constructor that which constructor has to execute first and last?  
Constructor chaining in java
You cannot call the constructor directly by name because it is illegal in Java.

Why do we use/need Constructor chaining in Java?


In Java, Constructor chaining is used where you want to perform multiple tasks in a separate constructor for each task and make their order by chaining which makes the program more readable and easy to understand for everyone. You can provide as many as constructors as you want in your classes and use constructor chaining to set the link among them.

How to call one Constructor from another constructor? 


To call one constructor from another constructor is called Constructor chaining in Java and it can be implemented in two ways:
1. Using this() keyword to call the current class constructor within "same class".
2. Using super() keyword to call the Super class constructor from the "base class".
Let's see one by one.

this() Constructor Call in Java


If you need to call the same or current class constructor within the same class, you will have to use this() Keyword. The syntax to call the same class constructor are:
       this(), or this(ParamterList)
The statement this(parameters)  invokes the same class constructor with parameters which must match.
For example:
                      this();  To call default current class constructor.
                      this("name");  ➨ To call one parameter current class constructor with String argument.
                      this("shubh", 24)  ➨ To call two parameters current class constructor with String and int argument.
Key points:
1. You must use the this () keyword to call the current class constructor because JVM never puts automatically this() keyword like a super() keyword.
this() constructor call in Java
2. this() keyword must be in the first line of the constructor to call the same class constructor or current class otherwise you will get this error message: Exception in thread "main" java.lang.Error: Unresolved compilation problem: Constructor call must be the first statement in the constructor.
3. There must be at least one constructor without this keyword.
4. Constructor chaining can be done in any order.

Let's see a very simple example program step by step.
Program Source Code 1
    package scientecheasy; public class Developed { Developed(){ System.out.println("Java was developed by James Gosling"); } Developed(int year){ // Declaration of this keyword with two parameters list. Must be the first line. Don't forget. this("Java" , 1995); // It will call two parameter const. of same class. System.out.println("James Gosling is known as Father of Java programming language."); } Developed(String name, int year){ // Declaration of this keyword without the parameter. this(); // It will call default constructor due to no parameter in this() keyword. System.out.println("at Sun Microsystem and released in 1995"); } // Instance method declaration. void display(){ System.out.println("The Java compiler is written in Java but Java runtime in ANSI C."); } // Static method or main method. public static void main(String[] args) { // Create the object of class Developed using the new keyword and passes the int value. Developed obj=new Developed(1995); // It will call one parameter constructor. // Call display method using object reference variable obj. obj.display(); }}
    Output: Java was developed by James Gosling at Sun Microsystem and released in 1995 James Gosling is known as Father of Java programming language. The Java compiler is written in Java but Java runtime in ANSI C.
Let's take one more example program related to this.
Program Source Code 2:
    package protien; public class Protein { // Declaration of Encapsulated Instance Variable. private String gender; private int need; private String source; Protein(){ this("female" ,46); System.out.println("Protein requirement for children above 9 years old: 36 gm/day"); } Protein(String s, int need){ this("male" , 56 , "milk"); System.out.println("Protein requirement for women: 46 gm/day"); } Protein(String gender, int need, String source){ this.gender=gender; this.need=need; this.source=source; System.out.println("Protein requirement for men: 56 gm/day"); } }

    package protein; public class ProteinTest { public static void main(String[] args) { //Create three objects with different parameters in the constructor. Protein p1=new Protein(); Protein p2=new Protein("female",46); Protein p3=new Protein("male", 56, "milk"); } }

    Output: Output after creating the first object Protein requirement for men: 56 gm/day Protein requirement for women: 46 gm/day Protein requirement for children above 9 years old: 36 gm/day Output after creating the 2nd object. Protein requirement for men: 56 gm/day Protein requirement for women: 46 gm/day Output after creating the 3rd object. Protein requirement for men: 56 gm/day

super() Constructor Call in Java


If you need to call superclass constructor from the subclass constructor then you will have to use the super() keyword in the subclass constructor. The syntax to call a superclass constructor is:
    super(), or super(Parameter_list).
The statement super() calls the no-argument constructor of its superclass and the super(argument) invokes the superclass constructor where argument must match. 
For example:
           super(); To call the default superclass constructor.
           super(24); To call the superclass constructor with one int parameter.
Key points:
1. You must use the super() keyword to call the superclass constructor but if you do not put a super keyword, JVM will put automatically the super() keyword.
2. super() keyword must be in the first line of the constructor. Calling a superclass constructor' name in a subclass causes a syntax error.
3. A constructor is used to create the object of the class. Unlike properties and method, the constructor of the superclass is not inherited in the subclass. They can only be called from the subclass constructor using the super keyword.

Let's take one simple example program to understand all the points.
Program Source Code 3:
    package scientecheasy; public class School { // Declare the instance variable. String stName; int stRoll; int stId; School(String schoolName){ this(2); // calls one parameter constructor with int within same class. System.out.println("Student's Detail: "); } School(int s){ System.out.println("Delhi Public School"); } School(String stName, int stRoll, int stId){ (Line 6) this("DPS");// calls one parameter constrcutor with String parameter within same class. this.stName=stName; this.stRoll=stRoll; this.stId=stId; } void display(){ System.out.println("Name: " +stName); System.out.println("Roll no. : " +stRoll); System.out.println("Id: " +stId); } }
    package scientecheasy; public class Student extends School{ // extends is used for developing inheritance between two classes. Student(){ super("Shubh" , 2 , 2345);// It will call superclass constructor with three parameters. } Student(String schoolName){ this(); } public static void main(String[] args) { // Create the object of the class School and passes String value within double quotes from const. Student st=new Student("DPS"); // calls one parameter const. of same class. st.display(); } }
    Output: Delhi Public School Student's Detail: Name: Shubh Roll no. : 2 Id: 2345
Program Source code 4:
    package Nutrition; public class Proteins { Proteins(){ System.out.println("Protein is one of the basic building blocks of the Human body. "); System.out.println("Hair, Skin, Eyes, Muscles, and organs are all made up of Protein"); } }
    package Nutrition; public class Source extends Proteins { Source(){ this(1); // It will call one parameter constructor of same class. System.out.println("Source of Proteins are milk, eggs, meat, pulses, soybeans"); } Source(int s){ // Here, we will not place any super()keyword. // JVM will automatically put the super() keyword and call superclass constructor. System.out.println("Proteins are made up of amino acids"); } }
    package Nutrition; public class MyProtein { public static void main(String[] args) { Source sc=new Source(); } }
    Output: Protein is one of the basic building blocks of the Human body. Hair, Skin, Eyes, Muscles, and organs are all made up of Protein Proteins are made up of amino acids Source of Proteins are milk, eggs, meat, pulses, soybeans
Final words
Hope that this tutorial has covered almost all the important points related to Constructor Chaining in Java with an Example program in an easy way and step by step. We hope that you will have enjoyed this tutorial.
Thanks for reading!
Next ➤ Copy constructor in Java

⏪ Prev Next ⏩