(Translated by https://www.hiragana.jp/)
Constructor Chaining In Java with Examples - GeeksforGeeks
Open In App

Constructor Chaining In Java with Examples

Last Updated : 04 Jul, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Constructor chaining is the process of calling one constructor from another constructor with respect to current object. 

One of the main use of constructor chaining is to avoid duplicate codes while having multiple constructor (by means of constructor overloading) and make code more readable.

Prerequisite - Constructors in Java 

Constructor chaining can be done in two ways: 
 

  • Within same class: It can be done using this() keyword for constructors in the same class
  • From base class: by using super() keyword to call the constructor from the base class.

Constructor chaining occurs through inheritance. A sub-class constructor’s task is to call super class’s constructor first. This ensures that the creation of sub class’s object starts with the initialization of the data members of the superclass. There could be any number of classes in the inheritance chain. Every constructor calls up the chain till the class at the top is reached.

Why do we need constructor chaining? 

This process is used when we want to perform multiple tasks in a single constructor rather than creating a code for each task in a single constructor we create a separate constructor for each task and make their chain which makes the program more readable. 
 

Constructor Chaining within the same class using this() keyword:

Constructor Chaining In Java

Java




// Java program to illustrate Constructor Chaining
// within same class Using this() keyword
class Temp
{
    // default constructor 1
    // default constructor will call another constructor
    // using this keyword from same class
    Temp()
    {
        // calls constructor 2
        this(5);
        System.out.println("The Default constructor");
    }
 
    // parameterized constructor 2
    Temp(int x)
    {
        // calls constructor 3
        this(5, 15);
        System.out.println(x);
    }
 
    // parameterized constructor 3
    Temp(int x, int y)
    {
        System.out.println(x * y);
    }
 
    public static void main(String args[])
    {
        // invokes default constructor first
        new Temp();
    }
}


Output:  

75
5
The Default constructor

Rules of constructor chaining : 

  1. The this() expression should always be the first line of the constructor.
  2. There should be at-least be one constructor without the this() keyword (constructor 3 in above example).
  3. Constructor chaining can be achieved in any order.
     

What happens if we change the order of constructors?
Nothing, Constructor chaining can be achieved in any order

Java




// Java program to illustrate Constructor Chaining
// within same class Using this() keyword
// and changing order of constructors
class Temp
{
    // default constructor 1
    Temp()
    {
        System.out.println("default");
    }
 
    // parameterized constructor 2
    Temp(int x)
    {
        // invokes default constructor
        this();
        System.out.println(x);
    }
 
    // parameterized constructor 3
    Temp(int x, int y)
    {
        // invokes parameterized constructor 2
        this(5);
        System.out.println(x * y);
    }
 
    public static void main(String args[])
    {
        // invokes parameterized constructor 3
        new Temp(8, 10);
    }
}


Output: 

default
5
80

NOTE: In example 1, default constructor is invoked at the end, but in example 2 default constructor is invoked at first. Hence, order in constructor chaining is not important. 
 

Constructor Chaining to other class using super() keyword :

Java




// Java program to illustrate Constructor Chaining to
// other class using super() keyword
class Base
{
    String name;
 
    // constructor 1
    Base()
    {
        this("");
        System.out.println("No-argument constructor of" +
                                           " base class");
    }
 
    // constructor 2
    Base(String name)
    {
        this.name = name;
        System.out.println("Calling parameterized constructor"
                                              + " of base");
    }
}
 
class Derived extends Base
{
    // constructor 3
    Derived()
    {
        System.out.println("No-argument constructor " +
                           "of derived");
    }
 
    // parameterized constructor 4
    Derived(String name)
    {
        // invokes base class constructor 2
        super(name);
        System.out.println("Calling parameterized " +
                           "constructor of derived");
    }
 
    public static void main(String args[])
    {
        // calls parameterized constructor 4
        Derived obj = new Derived("test");
 
        // Calls No-argument constructor
        // Derived obj = new Derived();
    }
}


Output: 

Calling parameterized constructor of base
Calling parameterized constructor of derived

Note : Similar to constructor chaining in same class, super() should be the first line of the constructor as super class’s constructor are invoked before the sub class’s constructor.
Alternative method : using Init block
When we want certain common resources to be executed with every constructor we can put the code in the init block. Init block is always executed before any constructor, whenever a constructor is used for creating a new object.
Example 1:

Java




class Temp
{
    // block to be executed before any constructor.
    {
        System.out.println("init block");
    }
 
    // no-arg constructor
    Temp()
    {
        System.out.println("default");
    }
 
    // constructor with one argument.
    Temp(int x)
    {
        System.out.println(x);
    }
 
    public static void main(String[] args)
    {
        // Object creation by calling no-argument
        // constructor.
        new Temp();
 
        // Object creation by calling parameterized
        // constructor with one parameter.
        new Temp(10);
    }
}


Output: 
 

init block
default
init block
10

NOTE: If there are more than one blocks, they are executed in the order in which they are defined within the same class. See the ex. 
Example :
 

Java




class Temp
{
    // block to be executed first
    {
        System.out.println("init");
    }
    Temp()
    {
        System.out.println("default");
    }
    Temp(int x)
    {
        System.out.println(x);
    }
 
    // block to be executed after the first block
    // which has been defined above.
    {
        System.out.println("second");
    }
    public static void main(String args[])
    {
        new Temp();
        new Temp(10);
    }
}


Output :  

init
second
default
init
second
10



Previous Article
Next Article

Similar Reads

Method Chaining In Java with Examples
Method Chaining is the practice of calling different methods in a single line instead of calling other methods with the same object reference separately. Under this procedure, we have to write the object reference once and then call the methods by separating them with a (dot.). Method chaining in Java is a common syntax to invoke multiple methods c
3 min read
Implementing our Own Hash Table with Separate Chaining in Java
All data structure has their own special characteristics, for example, a BST is used when quick searching of an element (in log(n)) is required. A heap or a priority queue is used when the minimum or maximum element needs to be fetched in constant time. Similarly, a hash table is used to fetch, add and remove an element in constant time. Anyone mus
10 min read
Constructor getAnnotatedReturnType() method in Java with Examples
The getAnnotatedReturnType() method of a Constructor class is used to return an AnnotatedType object which represents AnnotatedType to specify return type of Constructor Object. The returned AnnotatedType represents implementation of AnnotatedType itself or any of its sub-interfaces like AnnotatedArrayType, AnnotatedParameterizedType, AnnotatedType
2 min read
Constructor getAnnotatedReceiverType() method in Java with Examples
The getAnnotatedReceiverType() method of a Constructor class is used to return an AnnotatedType object that represents the AnnotatedType to specify the receiver type of this constructor. If the constructor has a receiver parameter then The receiver type of a constructor is available. If this constructor either has no receiver parameter or has a rec
2 min read
Constructor equals() method in Java with Examples
The constructor class provides information about a single constructor for a class and it also provides access to that constructor. The equals() method of java.lang.reflect.Constructor is used to compare this Constructor against the passed object. If the objects are the same then the method returns true. In java Two Constructor objects are the same
2 min read
Constructor getDeclaringClass() method in Java with Examples
The constructor class provides information about a single constructor for a class and it also provides access to that constructor. The getDeclaringClass() method of java.lang.reflect.Constructor is used to return the class object representing the class that declares the constructor represented by this object. This method returns the name of the sou
2 min read
Constructor getName() method in Java with Examples
The constructor class provides information about a single constructor for a class and it also provides access to that constructor. The getName() method of java.lang.reflect.Constructor is used to return this constructor name, as a string. Constructor name is the binary name of the constructor's declaring class. Syntax: public String getName() Param
1 min read
Constructor toGenericString() method in Java with Examples
The toGenericString() method of java.lang.reflect.Constructor class is used to return get the generic form of this constructor, i.e. a string representing the details about this constructor including the type parameters. Syntax: public String toGenericString() Parameters: This method accepts nothing. Return: This method returns a generic form of th
2 min read
Constructor toString() method in Java with Examples
The toString() method of java.lang.reflect.Constructor class is used to return string representation of this Constructor.This string is the collection of all the properties of this constructor. For creating this string method adds access modifiers of the constructor with the name of the declaring class of constructor then add parenthesized and add
2 min read
Constructor isVarArgs() method in Java with Examples
The isVarArgs() method of java.lang.reflect.Constructor class is used to return the boolean value true if this Constructor can take a variable number of arguments as parameters else method will return false.VarArgs allows the constructor to accept a number of arguments. using VarArgs is a better approach to pass arguments than array when it is not
2 min read
Constructor isSynthetic() method in Java with Examples
The isSynthetic() method of java.lang.reflect.Constructor class is used to return the boolean value true if this constructor object is a synthetic construct else method returns false showing this construct is not a synthetic construct. As we know Synthetic Constructs are Class, Fields, and Methods that are created by the Java compiler for internal
3 min read
Constructor hashCode() method in Java with Examples
The hashCode() method of java.lang.reflect.Constructor class is used to return a hashcode for this Constructor object. The hashcode is always the same if the constructed object doesn’t change. Hashcode is a unique code generated by the JVM at the time of class object creation. We can use hashcode to perform some operation on hashing related algorit
2 min read
Constructor getParameterCount() method in Java with Examples
The getParameterCount() method of java.lang.reflect.Constructor class is used to return the number of parameters present on this constructor object. Every constructor contains a number of parameters starting from zero to many. This method is helpful to get those numbers of parameters. Syntax: public int getParameterCount() Parameters: This method a
2 min read
Constructor getGenericParameterTypes() method in Java with Examples
The getGenericParameterTypes() method of java.lang.reflect.Constructor class is used to return an array of objects that represent the types of the parameters present on this constructor object. The arrangement Order of the returned array from this method is the same as the order of parameter present on this constructor object. If the constructor ha
2 min read
Constructor getDeclaredAnnotations() method in Java with Examples
The getDeclaredAnnotations() method of java.lang.reflect.Constructor class is used to return annotations present on this Constructor element as an array of Annotation class objects. The getDeclaredAnnotations() method ignores inherited annotations on this constructor object.Returned array can contains no annotations means length of that array can b
2 min read
Constructor getGenericExceptionTypes() method in Java with Examples
The getGenericExceptionTypes() method of java.lang.reflect.Constructor class is used to return the exception types present on this constructor object as an array. The returned array of objects represent the exceptions declared to be thrown by this constructor object. If this constructor declares no exceptions in its throws clause then this method r
2 min read
Constructor getAnnotation() method in Java with Examples
The getAnnotation() method of a Constructor class is used to get this constructor object annotation for the specified type if such an annotation is present, else null. Specified type is passed as parameter. Syntax: public <T extends Annotation> T getAnnotation(Class<T> annotationClass) Parameters: This method accepts a single parameter
2 min read
Constructor getParameterAnnotations() method in Java with Examples
The getParameterAnnotations() method of a Constructor class is used to get a two-dimensional Annotation array that represent the annotations on the formal parameters of this Constructor. If the Constructor contains no parameters, an empty array will be returned. If the Constructor contains one or more parameters then a two-dimension Annotation arra
2 min read
Constructor getTypeParameters() method in Java with Examples
The getTypeParameters() method of a Constructor class is used to get an array of TypeVariable objects declared by this Constructor Object, in declaration order. Elements of array represent the type variables objects declared by Method. An array of length 0 is returned by this getTypeParameters(), if the Method Object generic declaration contains no
2 min read
Constructor newInstance() method in Java with Examples
The newInstance() method of a Constructor class is used to create and initialize a new instance of this constructor, with the initialization parameters passed as parameter to this method. Each parameter is unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as nece
3 min read
java.lang.reflect.Constructor Class in Java
java.lang.reflect.Constructor class is used to manage the constructor metadata like the name of the constructors, parameter types of constructors, and access modifiers of the constructors. We can inspect the constructors of classes and instantiate objects at runtime. The Constructor[] array will have one Constructor instance for each public constru
4 min read
Constructor Overloading in Java
Java supports Constructor Overloading in addition to overloading methods. In Java, overloaded constructor is called based on the parameters specified when a new is executed. When do we need Constructor Overloading? Sometimes there is a need of initializing an object in different ways. This can be done using constructor overloading. For example, the
5 min read
Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?
Prerequisite: Interface and Abstract class in Java. A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created. Why interfaces can not have the constructor? An Interface is a complete abstraction of class. All data members present in the interface are by de
4 min read
Constructor Overloading with Static Block in Java
In Java, Constructor is a block of codes similar to the method that is used to initialize the object’s state. A constructor is invoked at the time of object or instance creation. Each time an object is created using a new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of
4 min read
Using the super Keyword to Call a Base Class Constructor in Java
We prefer inheritance to reuse the code available in existing classes. In Java, Inheritance is the concept in which one class inherits the properties of another class. In the below example there are two classes Programming and DP while Programming is Parent class and DP is child class. From the main class, we have created an object of DP i.e. child
5 min read
Why a Constructor can not be final, static or abstract in Java?
Prerequisite: Inheritance in Java Constructor in java is a special type of method which is different from normal java methods/ordinary methods. Constructors are used to initialize an object. Automatically a constructor is called when an object of a class is created. It is syntactically similar to a method but it has the same name as its class and a
6 min read
Why Enum Class Can Have a Private Constructor Only in Java?
Every enum constant is static. If we want to represent a group named constant, then we should go for Enum. Hence we can access it by using enum Name. Enum without a constructor: enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } Enum with a constructor: enum Size { SMALL("The size is small."), MEDIUM("The size is medium."),
2 min read
Constructor in Java Abstract Class
Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor. So if we do not define any constructor inside the abstract class then JVM (Java Virtual Machine) will give a default constructor to the abstract class. I
4 min read
Difference Between Constructor and Static Factory Method in Java
Whenever we are creating an object some piece of code will be executed to perform initialization of that object. This piece of code is nothing but a constructor, hence the main purpose of the constructor is to perform initialization of an object but not to create an object. Let us go through the basic set of rules for writing a constructor. They ar
4 min read
Recursive Constructor Invocation in Java
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems. Here recursive constructor invocation and stack o
3 min read
Article Tags :
Practice Tags :