Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
Now Reading
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
egant technique that you should consider grasping as a software developer. It makes your code cleaner, more efficient, and easier to understand. In constructor chaining, you call one constructor from another within the same class.
Our exploration of "Constructor Chaining in Java" will unfold across several vital sections. Each is designed to improve your understanding of the subject matter incrementally.
We'll start with the basics, introducing the concept of constructor chaining and its implications in Java. To make the learning process engaging and hands-on, we will walk you through practical examples. This step-by-step approach will ensure you understand constructor chaining in Java with examples.
Next, we'll take you through a particular type of chaining known as “Constructor chaining in Java using super.” This approach will allow you to explore how superclass constructors can be invoked in subclass constructors.
Moving ahead, we'll categorize and explain the 'Types of constructor chaining in Java'. Differentiating between them will provide you with the flexibility to choose the most appropriate type depending on the coding requirements.
We'll then compare local chaining and constructor chaining in Java, highlighting the unique characteristics and applications of each. This understanding will equip you with the knowledge to make more informed coding decisions.
By the end of this guide, you will have a thorough understanding of constructor chaining in Java, supported by hands-on examples and practical knowledge. Your journey through this material will enhance your Java programming skills and open new avenues for more efficient coding practices.
Constructor chaining in Java is the process of calling one constructor from another with respect to the current object. This technique allows you to ensure that a series of constructors, each with a different parameter list, are executed in a specific order.
This is a powerful concept because it allows you to set up a Java object in a consistent and controlled manner, no matter which constructor is called. It can make your code cleaner, more readable, and easier to maintain.
Constructor Chaining in Java with Example
In this code, the ChainingDemo class has two constructors. When an object of ChainingDemo is created using the default constructor, it automatically calls the single parameter constructor using the this() keyword. The this(10) statement chains the constructors together, ensuring the single parameter constructor is called before the default constructor. The result is that the val variable is initialized to 10.
Here's the output:
Constructor chaining is a key concept in Java that offers numerous benefits, and understanding these needs will help you appreciate its importance in code design and implementation.
Let's consider the following constructor chaining in Java example
In this code, we have an Employee class with three fields (name, age, department). There are three constructors, each handling a different scenario:
Output
There are certain rules that govern the process of constructor chaining in Java. Understanding these rules will let you apply this concept effectively and correctly. Here are the key rules:
Let's illustrate these rules with an example:
This program demonstrates Rules 1 and 3. The this(10); statement, which is a call to another constructor, is the first statement in the default constructor, following Rule 1. It also shows Rule 3, because only one other constructor is called.
Output
However, if we modify the Test(int value) constructor to call this(), it will result in a recursive constructor invocation, violating Rule 2 and leading to a StackOverflowError:
There are two types of constructor chaining in Java:
When constructor chaining is used within the same class, it involves calling one constructor from another constructor in the same class. The keyword this() is used to call another constructor in the same class.
Here's an example:
In this example, when an object of the Demo class is created using the default constructor, it automatically calls the parameterized constructor, initializing the value to 10.
Output
In Java, a subclass constructor can call a constructor in its superclass. The keyword super() is used to call a constructor in the parent class.
Here's an example:
In this example, when an object of the Child class is created, it automatically calls the constructor of its parent class Parent, followed by the constructor in the Child class itself.
Output
In Java, you can call one constructor from another constructor within the same class. This process is known as constructor chaining, and the keyword this() is used to make this call. It's a useful technique to maintain cleaner code and promote code reusability.
An example of a Constructor Calling From Another Constructor:
In this code, when we create a Vehicle object using the default constructor, it automatically calls the parameterized constructor due to the this("Car", 0); statement. This initializes type as "Car" and speed as 0. The call to the parameterized constructor must be the first statement in the calling constructor.
Output
This shows that the parameterized constructor is called first, followed by the default constructor. The Vehicle object's type and speed values are displayed as initialized by the parameterized constructor.
In Java, a subclass constructor has the ability to call a constructor from its superclass. This is a form of constructor chaining in Java using super. This mechanism allows a subclass to inherit the fields and methods of its superclass, ensuring that the superclass constructor's initialization code is executed before the subclass constructor's code. The keyword super() is used for this purpose.
For example:
In this example, when an object of the Dog class is created, it first calls the constructor of its superclass Animal because of the super(); statement. This initializes the type field. Then the Dog constructor is executed, initializing the name field.
Output
This shows that the superclass constructor is called first, followed by the subclass constructor. The type and name values are displayed as initialized by the Animal and Dog constructors respectively.
In Java, the order in which constructors are declared in the class does not affect how they are called or their execution. The constructor called depends on the arguments passed when creating an object of the class.
However, within a constructor, the call to another constructor using this() or to a superclass constructor using super() must be the first statement. If it's not, you will receive a compilation error.
For example:
Here, even though the parameterized constructor (Constructor 1) is declared before the default constructor (Constructor 2), when we create an object with the default constructor, it first calls the parameterized constructor due to the this(10); statement. After that, it continues executing the rest of the default constructor.
Output
Besides constructor chaining in Java, there's another method to initialize common logic across constructors, which is known as the initialization block, or 'init block' for short. The init block is a block of code that looks like a method, but it's outside any method and is written directly within the class. It is executed whenever an instance of the class is created, no matter which constructor is called.
Here's an example to show how the init block works:
In this code, the init block is called every time an object of the Demo class is created. It initializes the value to 10. Then, depending on the constructor used to create the object, the value may be reinitialized. If the default constructor is used, the value remains 10. If the parameterized constructor is used, the value is changed to the parameter value.
Output
This shows that the init block is called before each constructor, performing common initialization logic.
Local Chaining | Constructor Chaining | |
What | Method chaining in a single statement. | One constructor calls another. |
Use | Invoking methods that return the object instance. | Performing common actions in multiple constructors. |
How | Using return this; | Using this() within a class, super() from a subclass. |
Scope | Limited to a particular method call. | Applies to an entire class or between a class and its superclass. |
Constructor chaining in Java is a powerful feature that allows one constructor to call another constructor within the same class or in its superclass. This process ensures efficient initialization of objects, eliminates code redundancy, and enhances the readability of the code. Constructor chaining within the same class is achieved using the this() keyword, while chaining from a subclass to a superclass is done using super(). Other concepts, like the initialization block and local chaining, offer additional techniques for code reuse and organization. Mastering these concepts can contribute to writing cleaner, more efficient Java code.
1. What happens when the this() or super() keywords are not included in a constructor?
If this() or super() are not included explicitly, Java implicitly includes them. For a subclass constructor, if super() is not included, Java will automatically insert a no-argument super() as the first statement, thus calling the superclass's no-argument constructor. For this(), if not used, it simply means there's no explicit call to another constructor in the same class.
2. What are the limitations of using constructor chaining in Java?
The main limitation is that a constructor call, whether this() or super(), must be the first statement in a constructor. Additionally, you can't use both this() and super() in the same constructor, as both have to be the first statement.
3. How is constructor chaining different from method overloading?
Constructor chaining is a process where one constructor calls another within the same class or a superclass. Whereas method overloading is a feature that allows a class to have two or more methods with the same name but different parameters.
4. How does constructor chaining relate to the concept of inheritance in Java?
Constructor chaining is closely linked to inheritance. When creating an instance of a subclass, the constructor of its superclass is always invoked first to ensure proper initialization of the fields inherited from the superclass. This is achieved via constructor chaining with the super() keyword.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...