For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
When creating objects in Java, you often need different ways to initialize them. Some objects may require default values, while others need specific parameters. This is where constructor overloading in Java becomes useful.
It allows a class to have multiple constructors with different parameter lists, giving you flexibility in object creation.
This guide explains constructor overloading in Java with rules, examples, and best practices. You will learn how Java handles overloaded constructors, how this() and super() affect execution, and where constructor overloading fits in real-world applications.
A class can have multiple constructors as long as each has a unique parameter list. This is called constructor overloading in Java. The compiler determines which constructor to call based on the number and types of arguments passed during object creation.
Below are key aspects of constructor overloading in Java:
The following example demonstrates how constructor overloading in Java works with a Student class:
class Student {
String name;
int age;
// Default constructor
Student() {
name = "Unknown";
age = 0;
}
// Constructor with one parameter
Student(String n) {
name = n;
age = 18; // Default age
}
// Constructor with two parameters
Student(String n, int a) {
name = n;
age = a;
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Alice");
Student s3 = new Student("Bob", 22);
s1.display();
s2.display();
s3.display();
}
}
Example Output:
Name: Unknown, Age: 0
Name: Alice, Age: 18
Name: Bob, Age: 22
This example shows how constructor overloading in Java allows flexible object initialization. The next section explains the rules that must be followed when overloading constructors.
To avoid errors, you need to follow specific rules while implementing constructor overloading in Java. Below are the key rules:
Also Read: Top 13 String Functions in Java | Java String [With Examples]
Now that you know the rules, you should also understand how this() helps in constructor overloading in Java. The next section explains this concept in detail.
Instead of repeating code in multiple constructors, you can use this() to call one constructor from another within the same class. This technique reduces redundancy and improves maintainability.
The following example demonstrates constructor chaining using this():
class Employee {
String name;
int salary;
// Constructor with no parameters
Employee() {
this("Unknown", 0); // Calls the constructor with two parameters
}
// Constructor with one parameter
Employee(String n) {
this(n, 30000); // Calls the constructor with two parameters
}
// Constructor with two parameters
Employee(String n, int s) {
name = n;
salary = s;
}
void display() {
System.out.println("Employee: " + name + ", Salary: " + salary);
}
public static void main(String[] args) {
Employee e1 = new Employee();
Employee e2 = new Employee("Alice");
Employee e3 = new Employee("Bob", 50000);
e1.display();
e2.display();
e3.display();
}
}
Example Output:
Employee: Unknown, Salary: 0
Employee: Alice, Salary: 30000
Employee: Bob, Salary: 50000
This approach simplifies constructor overloading in Java by reducing code duplication. Next, you will see real-world scenarios where constructor overloading improves Java applications.
Constructor overloading in Java is commonly used in applications that require multiple ways to initialize an object. Below are some real-world examples:
The following example demonstrates a Bank Account class with overloaded constructors:
class BankAccount {
String accountNumber;
double balance;
// Constructor with only account number
BankAccount(String accNum) {
accountNumber = accNum;
balance = 0.0; // Default balance
}
// Constructor with account number and initial balance
BankAccount(String accNum, double bal) {
accountNumber = accNum;
balance = bal;
}
void display() {
System.out.println("Account Number: " + accountNumber + ", Balance: ₹" + balance);
}
public static void main(String[] args) {
BankAccount acc1 = new BankAccount("123456");
BankAccount acc2 = new BankAccount("789012", 500.75);
acc1.display();
acc2.display();
}
}
Example Output:
Account Number: 123456, Balance: ₹0.0
Account Number: 789012, Balance: ₹500.75
These real-world applications show why constructor overloading in Java is widely used. However, it is also important to understand how it differs from method overloading. The next section provides a detailed comparison.
Both constructor overloading and method overloading allow multiple versions of the same function in a class, but they serve different purposes. The table below highlights the key differences.
Feature | Constructor Overloading | Method Overloading |
Purpose | Initializes objects differently | Performs different actions on objects |
Name | Same as class name | Can have any name |
Return Type | No return type | Must have a return type |
Call Mechanism | Called automatically | Called explicitly by object |
Use Case | Helps create objects with different initial states | Allows methods to perform varied tasks based on input parameters |
Now that you understand how constructor overloading in Java works and how it compares to method overloading, the next section covers common mistakes and best practices when overloading constructors.
To write efficient and error-free overloaded constructors, you should follow some best practices. Below are key recommendations:
By following these practices, you can ensure that constructor overloading in Java remains efficient and maintainable.
Also Read: Careers in Java: How to Make a Successful Career in Java in 2025
Understanding constructor overloading in Java is essential for effective object-oriented programming. Now, it's time to explore how Java handles constructor execution, including the order of constructor calls in inheritance and how super() works in constructor chaining.
When working with constructors, you need to understand how Java determines the order of execution. This is especially important when dealing with constructor overloading in Java and inheritance.
Java follows a structured execution process when initializing objects. The constructor execution order depends on the class hierarchy, constructor chaining, and whether this() or super() is used. In this section, you will learn how Java handles constructor calls step by step.
Whenever you create an object, Java ensures that all relevant constructors are executed in a specific order. The following rules define the execution flow:
To see how constructor execution works, the next section provides a detailed example.
When a class has multiple constructors, Java follows a structured approach to execute them. The following example demonstrates constructor overloading in Java using constructor chaining with this().
class Person {
String name;
int age;
// Constructor with no parameters
Person() {
this("Unknown", 18); // Calls constructor with two parameters
System.out.println("Default constructor executed");
}
// Constructor with one parameter
Person(String n) {
this(n, 18); // Calls constructor with two parameters
System.out.println("Constructor with one parameter executed");
}
// Constructor with two parameters
Person(String n, int a) {
name = n;
age = a;
System.out.println("Constructor with two parameters executed");
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person("Alice");
Person p3 = new Person("Bob", 25);
}
}
Example Output:
Constructor with two parameters executed
Default constructor executed
Constructor with two parameters executed
Constructor with one parameter executed
Constructor with two parameters executed
This shows that constructor chaining always calls the most parameterized constructor first when this() is used. Now, let’s see how constructor execution works when a class inherits another class.
When a class extends another class, Java ensures that the parent class constructor executes first, followed by the child class constructor. This maintains proper initialization in the class hierarchy.
The following example demonstrates constructor overloading in Java along with constructor execution order in inheritance.
class Parent {
Parent() {
System.out.println("Parent class constructor executed");
}
}
class Child extends Parent {
Child() {
System.out.println("Child class constructor executed");
}
public static void main(String[] args) {
Child c = new Child();
}
}
Example Output:
Parent class constructor executed
Child class constructor executed
By default, Java calls the default constructor of the parent class before executing the child class constructor. However, if the parent class does not have a default constructor, you must explicitly call a parameterized constructor using super(). The next section explains this concept.
In constructor overloading in Java, super() is used to call a parent class constructor explicitly. This is useful when the parent class does not have a default constructor or when specific initialization is required.
Consider the following example:
class Parent {
Parent(String message) {
System.out.println("Parent constructor executed: " + message);
}
}
class Child extends Parent {
Child() {
super("Hello from Parent"); // Calls the parameterized constructor of Parent
System.out.println("Child constructor executed");
}
public static void main(String[] args) {
Child c = new Child();
}
}
Example Output:
Parent constructor executed: Hello from Parent
Child constructor executed
Using super() ensures that Java calls the correct parent class constructor before executing the child class constructor. The next section compares this() and super() to clarify their differences.
Both this() and super() are used in constructor overloading in Java, but they serve different purposes. The table below highlights the key differences:
Feature | this() | super() |
Purpose | Calls another constructor of the same class | Calls a constructor of the parent class |
Used In | Constructor chaining within the same class | Constructor chaining between parent and child classes |
Placement | Must be the first statement in a constructor | Must be the first statement in a child class constructor |
Default Behavior | Not called automatically | Automatically calls the parent class's default constructor if super() is not explicitly used |
Now that you understand the difference between this() and super(), the next section highlights common mistakes developers make when handling constructor execution.
While working with constructors, developers often make mistakes that lead to compilation errors or unexpected behavior. Below are some common pitfalls to avoid:
By avoiding these mistakes, you can ensure smooth constructor execution in Java programs.
Following best practices helps you write efficient and error-free constructor code. Below are some key recommendations:
Also Read: OOPS Concept in Java Explained for Beginners
By following these best practices, you can improve the structure and readability of your Java programs.
Now that you understand constructor execution in Java, it’s time to move forward and explore the advantages and disadvantages of constructor overloading in Java, along with scenarios where it should or should not be used.
Understanding constructor overloading in Java is easier when you practice it. In this exercise, you will create a Java program that demonstrates constructor overloading using different constructors for initializing objects.
This step-by-step exercise will help you:
The first step is to define a class with overloaded constructors. The next section walks you through writing the class and understanding constructor behavior.
To see constructor overloading in action, you will create a Product class. This class will include three constructors, each demonstrating a different way to initialize an object.
Below is the Java code for this example:
class Product {
String name;
double price;
// Default constructor
Product() {
this("Unknown", 0.0);
System.out.println("Default constructor called");
}
// Constructor with one parameter
Product(String n) {
this(n, 100.0);
System.out.println("Constructor with one parameter called");
}
// Constructor with two parameters
Product(String n, double p) {
name = n;
price = p;
System.out.println("Constructor with two parameters called");
}
void display() {
System.out.println("Product Name: " + name + ", Price: $" + price);
}
public static void main(String[] args) {
Product p1 = new Product();
Product p2 = new Product("Laptop");
Product p3 = new Product("Smartphone", 799.99);
p1.display();
p2.display();
p3.display();
}
}
With the class structure ready, the next step is to examine the expected output when this program runs.
The output of this program depends on which constructor is called. Below is the expected output when executing the main() method:
Constructor with two parameters called
Default constructor called
Product Name: Unknown, Price: $0.0
Constructor with two parameters called
Constructor with one parameter called
Product Name: Laptop, Price: $100.0
Constructor with two parameters called
Product Name: Smartphone, Price: $799.99
Each line in the output corresponds to a constructor being executed. The next section explains how Java determines which constructor to call and in what order.
Java determines constructor execution order based on how constructors are chained. The rules for execution in this example are:
Now that you understand how constructors execute, the next section explores variations to experiment with and deepen your understanding.
To reinforce your understanding of constructor overloading in Java, try modifying the program in the following ways:
Now that you have implemented constructor overloading in Java, test your knowledge with a quick quiz designed to challenge your understanding of overloaded constructors, constructor chaining, and execution flow.
Test your understanding of constructor overloading in Java with the following multiple-choice questions (MCQs). These questions will help reinforce key concepts such as constructor execution order, constructor chaining, and the differences between constructors and methods.
1. What is the primary purpose of a constructor in Java?
A) To define a class's behavior
B) To initialize an object when it is created
C) To destroy an object after use
D) To call another method in a class
Answer: B) To initialize an object when it is created
2. Which of the following is true about constructor overloading in Java?
A) Overloaded constructors must have different names
B) Overloaded constructors must have different return types
C) Overloaded constructors must have different parameter lists
D) Overloaded constructors must use super()
Answer: C) Overloaded constructors must have different parameter lists
3. What happens if a class does not explicitly define a constructor?
A) The program will not compile
B) Java provides a default constructor
C) The class cannot be instantiated
D) Java throws a runtime exception
Answer: B) Java provides a default constructor
4. What is the correct syntax for calling another constructor in the same class?
A) super()
B) this()
C) new()
D) extends()
Answer: B) this()
5. In constructor chaining, which constructor executes first when using this()?
A) The most parameterized constructor
B) The default constructor
C) The constructor with the fewest parameters
D) The last constructor in the class
Answer: A) The most parameterized constructor
6. Which keyword is used to call a parent class constructor explicitly?
A) this
B) super
C) parent
D) base
Answer: B) super
7. What is a potential issue with constructor overloading?
A) It always leads to infinite loops
B) Having too many overloaded constructors can make the code hard to read
C) Java does not support constructor overloading
D) Overloaded constructors cannot have parameters
Answer: B) Having too many overloaded constructors can make the code hard to read
8. What is the correct order of execution when a child class constructor is invoked?
A) Child class constructor executes first, then the parent class constructor
B) Parent class constructor executes first, then the child class constructor
C) Java randomly decides the execution order
D) Only the child class constructor executes
Answer: B) Parent class constructor executes first, then the child class constructor
9. If a parent class has a parameterized constructor and no default constructor, what must the child class do?
A) Define its own default constructor
B) Explicitly call the parent’s parameterized constructor using super()
C) Avoid creating objects of the child class
D) Use this() instead of super()
Answer: B) Explicitly call the parent’s parameterized constructor using super()
10. How does Java decide which constructor to execute in an overloaded constructor setup?
A) It always executes the default constructor
B) It matches the arguments passed during object creation with the constructor’s parameter list
C) It picks the constructor with the fewest parameters
D) It executes all constructors in the class
Answer: B) It matches the arguments passed during object creation with the constructor’s parameter list
Now that you have tested your knowledge of constructor overloading in Java, it's time to explore how upGrad can help you advance your Java programming skills and prepare for industry-level projects.
With over 10 million learners and 200+ industry-focused courses, upGrad is a trusted name for professionals and students looking to build careers in software development.
You can enroll in expert-led programs designed to help you gain hands-on experience, industry knowledge, and real-world coding skills. Below are some Java-related courses that can help you grow in your programming journey.
If you’re unsure about the right learning path, you can take advantage of upGrad’s free one-on-one career counseling sessions. These sessions help you understand which Java course suits your goals, career aspirations, and job opportunities.
Additionally, you can visit upGrad’s offline learning centers, where you can get in-person mentoring, access to study resources, and networking opportunities with other learners and industry experts.
Similar Reads:
Constructor overloading can impact performance if complex initialization logic is present. Each overloaded constructor may have different execution paths, leading to variations in object instantiation time. In performance-critical applications, excessive overloading can slow down execution due to redundant initialization operations.
Yes, if both parent and child classes have overloaded constructors with similar parameter lists, ambiguity may arise. Java resolves this using method resolution order, but it can still lead to confusion. To avoid ambiguity, explicitly calling super() or restructuring constructor parameters is recommended.
Annotations like @Autowired in Spring or @Inject in Java EE can dictate how frameworks select and invoke constructors. Overloaded constructors must be carefully annotated to avoid conflicts. If multiple annotated constructors exist, explicit selection using qualifiers or factory methods may be necessary.
Poorly designed overloaded constructors can expose private fields, leading to unintended object states or security flaws. If a constructor allows partial initialization, it can create inconsistent objects. To mitigate security risks, always validate constructor parameters and avoid exposing unnecessary initialization logic.
Dependency injection frameworks, such as Spring and Guice, rely on constructors for object instantiation. Overloaded constructors must be correctly defined, as ambiguous constructor definitions can lead to injection failures. Using explicit annotations like @Primary or @Qualifier helps resolve conflicts.
Yes, serialization frameworks like Java's Serializable use default constructors during object reconstruction. If a class relies only on overloaded constructors without a no-arg constructor, deserialization may fail. Providing a default constructor or implementing custom deserialization logic ensures proper restoration of objects.
Overloaded constructors in immutable classes allow flexible instantiation while preserving immutability. Since instance variables are assigned only once, constructor overloading provides different ways to initialize immutable objects. However, careful parameter validation is needed to maintain object consistency.
Constructor overloading provides multiple initialization paths in design patterns such as Builder or Factory. In the Builder Pattern, constructors are often replaced with step-by-step initialization. In the Factory Pattern, overloaded constructors allow returning different object variations without exposing the constructor logic.
Excessive constructor overloading can make code difficult to read and maintain. Developers may struggle to track which constructor is best suited for specific use cases. Overloaded constructors should be documented clearly, and alternative patterns like factory methods should be used for better readability.
Using too many overloaded constructors can lead to confusion. Best practices include limiting constructor overloading, preferring factory methods or Builder patterns, and ensuring constructors follow a logical sequence. Providing meaningful default values also reduces unnecessary overloading.
Reflection APIs allow accessing overloaded constructors dynamically, but distinguishing between them requires handling parameter types explicitly. Using getDeclaredConstructors() retrieves all constructors, and getParameterTypes() helps select the right one. Reflection-based instantiation should be used cautiously due to performance and security risks.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.