Constructor Chaining in Java – Changing Order & Using Super () Keyword
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
In our previous tutorial, we discussed Copy Constructor and Constructor Overloading in Java in detail. Here, we will learn about Constructor Chaining in Java with examples. Moreover, we will check what happens if we change the order of constructors and Java constructor chaining to other class using super() keyword.
So, let’s start Constructor Chaining in Java.
What is Constructor Chaining in Java?
Java constructor chaining is a method of calling one constructor with the help of another while considering the present object.
It can be done in 2 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 a constructor from the base class.
Constructor chaining happens through legacy. A subclass constructor’s undertaking is to call superclass’ constructor first. This guarantees formation of subclass protest begins with the introduction of the information individuals from the superclass. There could be any quantities of classes in a legacy chain. Each constructor calls up the chain till class at the best is come to.
This procedure is utilized when we need to play out various errands in a solitary constructor as opposed to making a code for each assignment in a solitary constructor we make a different constructor for each undertaking and make their chain which makes the program clearer.
Do you know about Java Regular Expression (Java Regex) with Examples
class Temp { Temp() { this(5); System.out.println("The Default constructor"); } Temp(int x) { this(5, 15); System.out.println(x); } Temp(int x, int y) { System.out.println(x * y); } public static void main(String args[]) { new Temp(); } }
Output-
75
5
The Default constructor
a. What happens if we change the order of constructors?
class Temp { Temp() { System.out.println("default"); } Temp(int x) { this(); System.out.println(x); } Temp(int x, int y) { this(5); System.out.println(x * y); } public static void main(String args[]) { new Temp(8, 10); } }
Output-
default
5
80
Do you know How to Establish JDBC Connection in Java?
b. Constructor Chaining to other class using super() keyword
class Base { String name; Base() { this(""); System.out.println("No-argument constructor of" + " base class"); } Base(String name) { this.name = name; System.out.println("Calling parameterized constructor" + " of base"); } } class Derived extends Base { Derived() { System.out.println("No-argument constructor " + "of derived"); } Derived(String name) { super(name); System.out.println("Calling parameterized " + "constructor of derived"); } public static void main(String args[]) { Derived obj = new Derived("test"); } }
Output-
Calling parameterized constructor of a base
Calling parameterized constructor of derived
Let’s Explore The Difference Between Abstract Class and Interface in Java
Error Handling in Constructor Chaining
Constructor chaining can be used to implement robust error-handling mechanisms. By throwing exceptions from constructors and handling them in higher-level constructors, you can ensure that objects are always created in a valid state. For instance, a constructor might throw an IllegalArgumentException if an invalid parameter is passed. A higher-level constructor can catch this exception, log the error, and provide a default value for the parameter.
Benefits of Constructor Chaining:
1. Improved Code Reusability: Constructor chaining allows you to reuse common initialization logic across different constructors, reducing code duplication.
2. Enhanced Readability: By delegating initialization steps to smaller constructors, complex object creation becomes easier to understand, following a clear step-by-step process.
3. Better Maintainability: Breaking down initialization into smaller chunks makes code easier to modify and maintain in the future.
So, this was all about Constructor Chaining in Java Tutorial. Hope you like our explanation.
Conclusion
Hence, we learned about Constructor Chaining In Java Programming Language. In addition, we checked two conditions: what happens if we change the order of constructors and Java constructor chaining to other class using super() keyword. We hope through this document we solve all your queries, share your feedback in the comment section.
Related Topics-Â Wrapper Class in JavaÂ
Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google
Why did you pass string argument “name” when u won’t use the value “test” u passed into it?
You have missed few points here.
1. By default , all derived class constructors call its super class’s default constructor (i.e no argument constructor) if super class’s constructor is not called explicitly in derived class’s constructor.
If your Base class has argument constructors only and no “No Arugument Constructor” (i.e Base(){}) , then default construction will not be created automatically (internally).
So, if you try to create object for Derived class -> Derived(String name) but this constructor does not have line Super(name), then during compilation , compiler try to find and execute Base() constructor. As it is not available, compilation will be failed.