← Back to Chapters

Constructor Overloading in Java

?️ Constructor Overloading in Java

? Quick Overview

Constructor overloading in Java allows a class to have multiple constructors with different parameter lists. This helps create objects in different ways depending on the data available at the time of object creation.

? Key Concepts

  • Multiple constructors in the same class
  • Different parameter types or counts
  • Improves flexibility and readability
  • Compile-time polymorphism

? Syntax / Theory

A constructor has the same name as the class and no return type. Overloading occurs when constructors differ by parameters.

? View Code Example
// Class demonstrating constructor overloading
class Student {
int id;
String name;

// Default constructor
Student() {
id = 0;
name = "Unknown";
}

// Parameterized constructor with one parameter
Student(int i) {
id = i;
name = "Not Assigned";
}

// Parameterized constructor with two parameters
Student(int i, String n) {
id = i;
name = n;
}
}

? Code Example (Main Class)

? View Code Example
// Main class to test constructor overloading
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student(101);
Student s3 = new Student(102, "Amit");

System.out.println(s1.id + " " + s1.name);
System.out.println(s2.id + " " + s2.name);
System.out.println(s3.id + " " + s3.name);
}
}

? Interactive Demo: Car Factory

Simulate creating a Car object. Enter values below and click a constructor button to see how overloading logic selects the initializer.

 

? Live Output / Explanation

The program creates three objects using different constructors. Each constructor initializes the object differently based on the parameters passed.

✅ Tips & Best Practices

  • Use constructor overloading to avoid repetitive setter calls
  • Keep constructors simple and focused
  • Prefer constructor chaining for cleaner code

? Try It Yourself

  • Create a class Book with overloaded constructors
  • Add constructors with different combinations of title, author, and price
  • Print details using multiple objects