Constructor Chaining in Java
In Java you can call one constructor from another and it’s known as constructor chaining in Java. Don’t confuse between constructor overloading and constructor chaining, former is just a way to declare more than one constructor in Java. this and super keyword is used to call one constructor from other in Java. this() can be used to call other constructor of same class while super() can be used to call constructor from super class in Java. Just keep in mind that this() in realty calls no argument constructor of same class, while this(2) calls another constructor of same class which accepts one integer parameter. Similarly super() can be used to call no argument constructor of super class and super with parameter can be used to call other overloaded constructor of parent class. Calling one constructor from other is called constructor chaining in Java, which we seen while discussing constructor overloading in Java. Constructor chaining is also used to implement telescoping pattern where an object can be created with combination of multiple property. In our last tutorial we have seen some important properties of Java constructor as well as answered question What is Constructor in Java and in this Java tutorial we will see example of how to call one constructor from other for same class and super class.
How to call overloaded constructor in Java
Constructor overloading allows you to declare multiple constructor while constructor chaining allows you to call those constructor. This is main difference between constructor overloading and constructor chaining. Since constructor can only be called from another constructor in Java, constructor chaining is an important concept to understand to know How and when class is initialized in Java. Here is complete code example of constructor chaining which shows How to call overloaded constructor of same class and parent class in Java.
That’s all on What is constructor chaining in Java. We have seen How to call overloaded constructor from same class using this() and constructor from super class using super(). Key thing to remember is that call to another constructor must be first line in calling constructor.
Other Java programming tutorial you may find useful