BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java – Constructor Chaining with example

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

Calling a constructor from the another constructor of same class is known as Constructor chaining. The real purpose of Constructor Chaining is that you can pass parameters through a bunch of different constructors, but only have the initialization done in a single place. This allows you to maintain your initializations from a single location, while providing multiple constructors to the user. If we don’t chain, and two different constructors require a specific parameter, you will have to initialize that parameter twice, and when the initialization changes, you’ll have to change it in every constructor, instead of just the one.

As a rule, constructors with fewer arguments should call those with more

constructor chaining

Let’s understand this with the help of an example.

Constructor Chaining Example

In this example, I have several constructors, one constructor is calling another constructor using this keyword.

this() should always be the first statement in constructor 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 a constructor

class Employee
{   
    public String empName;
    public int empSalary;
    public String address;

    //default constructor of the class
    public Employee()
    {
    	//this will call the constructor with String param
        this("Chaitanya");
    }

    public Employee(String name)
    {
    	//call the constructor with (String, int) param
    	this(name, 120035);
    }
    public Employee(String name, int sal)
    {
    	//call the constructor with (String, int, String) param
    	this(name, sal, "Gurgaon");
    }
    public Employee(String name, int sal, String addr)
    {
    	this.empName=name;
    	this.empSalary=sal;
    	this.address=addr;
    }

    void disp() {
    	System.out.println("Employee Name: "+empName);
    	System.out.println("Employee Salary: "+empSalary);
    	System.out.println("Employee Address: "+address);
    }
    public static void main(String[] args)
    {
        Employee obj = new Employee();
        obj.disp();
    }
}

Output:

Employee Name: Chaitanya
Employee Salary: 120035
Employee Address: Gurgaon

Top Related Articles:

  1. Final Keyword In Java – Final variable, Method and Class
  2. Method Overloading in Java with examples
  3. Java – Default constructor with example
  4. Constructor Overloading in Java with examples
  5. OOPs concepts – What is Association in java?

Tags: Java-OOPs

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Sean says

    October 22, 2014 at 9:26 AM

    But what is the point of constructor chaining?
    i.e. why would I ever want to do this?

    Reply
    • Pratibha Patil says

      June 18, 2016 at 1:47 AM

      It is done to achieve run time polymorphism. One can pass different values at runtime

      Reply
    • likhit says

      April 7, 2017 at 8:57 AM

      you would need it to reduce the code size when there is something repetitive
      Eg: for a lift to be programmed you’ll need to type the code for the things to be done in the 1st floor even when you have to go to the 2nd or 3rd floor you can just call the constructor chaining to skip the code of 1st floor when the 3rd floor button is pressed.

      hope you understood..

      Reply
  2. Kartik Khullar says

    October 27, 2015 at 5:07 AM

    Thanks so much ! Now I easily understood the concept of Constructor chaining. Thanks Author !

    Reply
    • Huggins says

      March 2, 2017 at 10:30 AM

      But what is the difference between Constructor Overloading and Constructor Chaining

      Reply
  3. Devendra says

    November 5, 2015 at 12:20 PM

    In the above scenario how many objects gets created in heap, since constructors are using for creating an object. But here you are using constructor chaining to call 4 constructors at a time by passing 3 arg constructor.

    Physically there should be only one object that is ‘obj’, then what about rest?

    I’m suspecting all rest of the objects are created in heap and it does not have references, so those objects are abandon objects (garbage will clean these objects).

    Please reply.

    Thanks,
    Devendra Modem

    Thanks,
    Devendra Modem

    Reply
  4. Abhishek Kumar says

    April 28, 2016 at 10:51 AM

    Then What is the difference between Constructor Overloading and Constructor Chaining the above example is for Constructor Overloading

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap