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
Now Reading
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
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
Constructor in Java is the most widely used paradigm that is used to initialize objects of a class. The constructor and class name are the same, and the constructor is invoked with the help of the “new” keyword.
While constructor overriding in Java is never possible, you can still overload a constructor, unlike method overriding. When an object is created with the help of the “new” keyword, the constructor is called to set initial values to the object's instance variables. So now, what is constructor overloading?
Constructor overloading in Java refers to the ability of the paradigm to define multiple instances within itself. In simpler terms, a user invokes the overloading procedure to define multiple constructors in a class with different parameter lists. Each constructor can be different in terms of type, number, and set of parameters.
By overloading constructors, the user can create objects of the same class using different initialization values or different ways of initializing the object. This provides flexibility and allows the class to handle various scenarios when creating objects.
Constructor overloading in Java means defining multiple constructors in a class, each with a different parameter list. This allows you to create objects using different initialization values or different ways of initializing the object. By overloading constructors, you can provide flexibility and handle various scenarios when creating objects of a class. Now, let’s look at a constructor program in Java with output.
Constructor overloading example:
import java.util.*;
public class Student
{
private int rollno;
private int marks;
public Student() {
rollno = 0;
marks = 0;
}
public Student(int rank) {
rollno = rank;
marks = rank;
}
public Student(int idno, int ranks) {
rollno = idno;
marks = ranks;
}
}
In the above example, the class Student has three constructors:
1. The first constructor has no parameters and initializes both objects/attributes of class Student- i.e. rollno (roll number) and marks to 0.
2. The second constructor takes a single parameter side and sets both rollno and marks to that value, i.e. the rank creating an object of class Student with two similar attributes.
3. The third constructor takes two parameters idno (student’s ID number), and ranks and assigns them to rollno and marks, respectively, creating an object of class Student with two differentiable attributes.
Now, the user can create objects of the Student class using different constructors. For example:-
Student student1 = new Student();
Student student2 = new Student(5);
Student student3 = new Student(003, 7);
In the example above, student1 is created using the constructor with no arguments, student2 is created using the constructor with one argument, and student3 is created using the constructor with two arguments. Each object has different dimensions based on the constructor used.
Constructor overloading allows you to create objects with different initial states or provide different ways of object initialization based on your requirements.
If the user is looking for multiple initializations for the objects of a particular class, the paradigm of constructor overloading comes in handy. Constructor overloading aids the user in creating objects with different initial states or handling various scenarios when creating objects. Here are a few scenarios where constructor overloading can be beneficial:
1. Different Initialization Options
Just like in the example above with class Student, suppose you have a class representing a rectangle, and you want to create objects with different initialization options, for example- the length and width of the rectangle. Using constructor overloading, you can now create multiple constructors with different sets of parameters to accommodate various ways of initializing the object, such as providing a side only, which would make it a square, or providing both length and width.
public class Rect {
private int len;
private int wid;
public Rect (int oneside) {
len = oneside;
wid = oneside;
}
public Rect (int length, int width)
{
len = length;
wid = width;
}
Rect rect1 = new rect(25);
Rect rect2 = new Rect(10, 25);
}
2. Handling Default Values
Constructor overloading allows you to provide default values for certain parameters, making it easier to create objects without specifying all the values. This can be helpful when some parameters are optional or have sensible default values.
public class Shop {
private String name;
private String category;
private int price;
public Shop(String nm, String cgry) {
this.name = name;
this.category = category;
price = 0; // Default price
}
public Shop(String name, String category, int price) {
this.name = name;
this.category = category;
this.price = price;
}
Shop shop1 = new Shop("Dress", "Apparel");
Shop shop2 = new Shop("Harry Potter", "Book", 300);
}
3. Convenience and Flexibility
Constructor overloading also aids the user with convenience and flexibility, allowing them to initialize objects differently. This enhances the reusability of the class and increases the efficiency of the program syntax. Constructor overloading is thus an important paradigm that handles different initialization possibilities and helps the class become more versatile.
public class Shopkeeper
{
private int totalsale;
private int expenses;
private int profit;
public Shopkeeper (int totalsale, int expenses, int profit) {
this.totalsale = totalsale;
this.expenses = expenses;
this.profit = profit;
}
public Shopkeeper (int totalsale, int profit) {
this.totalsale = totalsale;
this.profit = profit;
this.expenses = 4000; // Default year
}
Shopkeeper sc1 = new Shopkeeper (8000, 6000, 4000);
Shopkeeper sc2 = new Shopkeeper (5000, 1000);
}
Parameter | Constructor Overloading | Method Overloading |
Purpose | Initialize objects | Provide different functionality or actions |
Usage | Creating objects | Performing operations or providing functionality |
Invocation | Automatically invoked during object creation | Explicitly called by method name and appropriate arguments |
Return Type | No return type | Can have different return types |
Naming | Same name as the class | Same name within the class |
Parameter Consideration | Constructor parameters are used to initialize objects with different values | Method parameters are used to affect behavior or functionality of an object |
There are certain rules one must be mindful of while creating Constructors in Java. Although the concept allows for a huge scope of reusability in Java programming, its syntax and rules must be kept in mind.
The this() keyword in Java is usually the first statement after one performs constructor overloading. It is used to invoke another constructor within the same class.
Here's an example that demonstrates the use of this() in constructor overloading:
public class Hellothis {
private int x;
public Hellothis ()
{
this(0);
}
public MyClass(int y)
{
this.x = y;
}
}
As the name suggests, the constructor allows the user to create a new object by copying the values of another object of the same class.
It is a special constructor creating an independent copy of an existing object. The copy constructor is essential to create a duplicate constructor without affecting the original object when needing a deep copy.
While copy constructor is definitely a faster method to create a duplicate of objects already initialized in the class, there are other methods to perform the same function too. These do not use constructors.
1. Using Object.clone()
The Object class provides a clone() method that can be overridden and used with the Cloneable interface to perform a shallow copy of an object.
2. Manual object initialization or setter methods
Another way to copy values from one object to another is by using object initialization or setter methods.
Constructor overloading provides users with several benefits to enhance the flexibility and usability of the classes. Here are the key benefits of constructor overloading:
1. Multiple initialization options
Constructor overloading allows defining multiple ways to initialize objects of a class. Users can choose the appropriate constructor based on their requirements and easily create objects with different initial states within parameterized constructors in Java or otherwise.
2. Improved re-usability
Constructor overloading enhances the re-usability of the class and its syntax by allowing the creation of multiple constructors. Users can select the constructor that best matches their needs, streamlining the instantiation process, offering only relevant information, and improving efficiency.
3. Default values and optional parameters
Constructor overloading minimizes the need for irrelevant syntax by providing default values or making parameters optional.
4. Encapsulation and flexibility
Constructor overloading supports the principle of encapsulation by allowing users to define constructors with different access modifiers (public, private, protected). This provides control over the accessibility of the constructors and further eliminates confusion by exposing only the necessary constructors to the external code, enhancing encapsulation, and ensuring proper object initialization.
Constructor overloading is a special paradigm in Java that provides flexibility and versatility of program syntax. It is a powerful feature that enhances the flexibility and usability of Java classes. Constructor overloading makes the code more adaptable, readable, and user-friendly by providing multiple ways to initialize objects.
1. Can a class have multiple copy constructors in Java?
No, Java does not support multiple copy constructors. However, if necessary, a user can opt for approaches such as the clone() method or manual copying to achieve similar functionality.
2. Can a constructor be inherited in Java?
Constructors are not inherited in Java. However, the concept of the subclass constructor is similar to implicitly or explicitly invoking the superclass constructor. This is only done to initialize inherited members of the class.
3. What is the difference between constructor overloading and method overloading in Java?
Constructor overloading is the process of defining multiple constructors in a class with different parameter lists, while method overloading in Java is the process of defining multiple methods with the same name but different parameter lists within a class.
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...