Constructor Chaining in Java
Read more »
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.