Sitemap

Member-only story

What Is Constructor Overloading in Java? (Java Interview QA)

Learn what constructor overloading is in Java, why it’s useful, and how to implement it with real-world examples and simple explanations.

2 min readApr 2, 2025

📌 Definition

Constructor overloading in Java means creating multiple constructors in the same class, each with different parameter lists.

➡️ It allows you to create objects in multiple ways depending on what data is available.

🧱 Basic Syntax

public class Book {
String title;
String author;

// Constructor 1
public Book() {
this.title = "Unknown";
this.author = "Unknown";
}

// Constructor 2
public Book(String title) {
this.title = title;
this.author = "Unknown";
}

// Constructor 3
public Book(String title, String author) {
this.title = title;
this.author = author;
}
}

🧪 Usage:

Book b1 = new Book();                     // uses constructor 1
Book b2 = new Book("Java in Action"); // uses constructor 2
Book b3 = new Book("Spring Boot", "John"); // uses constructor 3

✅ Each constructor initializes the object differently based on the provided parameters.

Why Use Constructor Overloading?

Real-World Example

Let’s say you’re building a User class for a login system:

public class User {
private String username;
private String email;
private boolean isActive;

public User(String username) {
this.username = username;
this.isActive = true;
}

public User(String username, String email) {
this.username = username;
this.email = email;
this.isActive = true;
}

public User(String username, String email, boolean isActive) {
this.username = username;
this.email = email;
this.isActive = isActive;
}
}

This allows the API consumer to create a user with just a username, or a fully populated user object — all using different constructors.

--

--

No responses yet