DEV Community

Cover image for Constructors and Constructor Overloading in Java
puja Jorwar
puja Jorwar

Posted on

Constructors and Constructor Overloading in Java

Constructors & Constructor Overloading in Java

A complete, beginner-friendly guide packed with real code, common interview questions, and everything you need to truly understand how Java objects are born.


πŸ“Œ Table of Contents

  1. Introduction
  2. What is a Constructor?
  3. Types of Constructors
  4. Constructor Overloading
  5. Rules of Constructor Overloading
  6. Constructor Chaining
  7. Common Mistakes
  8. Interview Questions & Answers
  9. Best Practices
  10. Conclusion

Introduction

Every time you create an object in Java, something quietly happens behind the
scenes β€” a special block of code runs to set that object up. That special block
is called a constructor.

Think of a constructor like a checklist that runs when you open a new app for
the first time β€” it asks for your name, sets your preferences, and gets
everything ready. Without it, the app would start in a broken, undefined state.
Same idea here.

πŸ’‘ Why does this matter for interviews?
Constructors, overloading, and constructor chaining are some of the most
consistently asked Java fundamentals. Understanding them well means you can
also reason about object lifecycle, memory management, and clean API design.


What is a Constructor?

A constructor is a special method that is automatically invoked when an
object of a class is created using the new keyword. Its job is to initialize
the object's state.

Syntax

public class Car {
    // Instance variables
    String brand;
    int year;

    // Constructor β€” same name as class, no return type
    public Car(String brand, int year) {
        this.brand = brand;
        this.year = year;
    }

    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 2023); // constructor called here
        System.out.println(myCar.brand);     // Toyota
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Rules

  • The constructor name must exactly match the class name (case-sensitive).
  • Constructors have no return type β€” not even void.
  • They are called automatically when you use the new keyword.
  • Constructors can have access modifiers (public, private, etc.).
  • A class can have multiple constructors (that's overloading!).

⚠️ Common confusion: If you add a return type to a constructor (like
void Car()), Java treats it as a regular method, not a constructor. No error
is thrown, but your object won't be initialized as expected.


Types of Constructors

1. Default Constructor (No-arg Constructor)

A default constructor takes no parameters. If you don't define any constructor
in your class, Java automatically provides one. But the moment you define your
own, Java's version disappears.

public class Student {
    String name;
    int age;

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

    public static void main(String[] args) {
        Student s = new Student();
        System.out.println(s.name + ", " + s.age);
        // Output: Unknown, 0
    }
}
Enter fullscreen mode Exit fullscreen mode

2. Parameterized Constructor

This constructor accepts arguments so you can set custom values when creating
an object β€” much more flexible and commonly used in real applications.

public class Student {
    String name;
    int age;

    // Parameterized constructor
    public Student(String name, int age) {
        this.name = name; // 'this' refers to the current object
        this.age = age;
    }

    public static void main(String[] args) {
        Student s = new Student("Riya", 20);
        System.out.println(s.name + ", " + s.age);
        // Output: Riya, 20
    }
}
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ The this keyword: When a parameter has the same name as an instance
variable, this.name explicitly refers to the object's field, while name
alone refers to the local parameter. Without this, you'd just be assigning
the parameter to itself β€” a silent bug.


Constructor Overloading

Constructor overloading means defining multiple constructors in the same
class, each with a different parameter list. Java figures out which one to call
based on the arguments you pass.

Real-World Analogy

πŸ• Think of ordering pizza. You could say "give me a pizza" (defaults to
whatever the chef decides), or "give me a medium Margherita", or "give me a
large Pepperoni with extra cheese." These are three different "orderings" β€”
same concept (pizza), different inputs. Constructor overloading works the
same way.

public class Pizza {
    String size;
    String topping;
    boolean extraCheese;

    // Constructor 1: no arguments
    public Pizza() {
        size = "Medium";
        topping = "Margherita";
        extraCheese = false;
    }

    // Constructor 2: size and topping
    public Pizza(String size, String topping) {
        this.size = size;
        this.topping = topping;
        extraCheese = false;
    }

    // Constructor 3: all fields
    public Pizza(String size, String topping, boolean extraCheese) {
        this.size = size;
        this.topping = topping;
        this.extraCheese = extraCheese;
    }

    public static void main(String[] args) {
        Pizza p1 = new Pizza();
        Pizza p2 = new Pizza("Large", "Pepperoni");
        Pizza p3 = new Pizza("Large", "Pepperoni", true);
    }
}
Enter fullscreen mode Exit fullscreen mode

Rules of Constructor Overloading

What CAN differ

  • Number of parameters β€” e.g., Person() vs Person(String name)
  • Type of parameters β€” e.g., Box(int size) vs Box(double size)
  • Order of parameters β€” e.g., Point(int x, double y) vs Point(double x, int y)

What CANNOT differ

🚫 Two constructors with the exact same parameter list will cause a
compile-time error. Parameter names don't matter β€” only types and order do.

// βœ… VALID β€” different parameter types
public Box(int size) { ... }
public Box(double size) { ... }

// βœ… VALID β€” different number of parameters
public Box(int width) { ... }
public Box(int width, int height) { ... }

// ❌ INVALID β€” identical parameter lists β†’ compile error
public Box(int size) { ... }
public Box(int volume) { ... } // same as above, name doesn't matter
Enter fullscreen mode Exit fullscreen mode

Constructor Chaining

Constructor chaining means one constructor calls another constructor of the
same class using the this() keyword. This avoids repeating initialization
logic across multiple constructors.

πŸ“Œ Important rule: this() must always be the very first statement
inside a constructor. You cannot write anything before it.

public class Laptop {
    String brand;
    int ram;
    String os;

    // Constructor 1 β€” most specific (the "main" one)
    public Laptop(String brand, int ram, String os) {
        this.brand = brand;
        this.ram = ram;
        this.os = os;
        System.out.println("Full constructor called");
    }

    // Constructor 2 β€” calls Constructor 1 with a default OS
    public Laptop(String brand, int ram) {
        this(brand, ram, "Windows"); // must be first line!
        System.out.println("Two-arg constructor called");
    }

    // Constructor 3 β€” calls Constructor 2 with default RAM
    public Laptop(String brand) {
        this(brand, 8); // defaults to 8GB RAM
        System.out.println("One-arg constructor called");
    }

    public static void main(String[] args) {
        Laptop l = new Laptop("Dell");
        // Output:
        // Full constructor called
        // Two-arg constructor called
        // One-arg constructor called
        System.out.println(l.brand + ", " + l.ram + "GB, " + l.os);
        // Output: Dell, 8GB, Windows
    }
}
Enter fullscreen mode Exit fullscreen mode

The chain unwinds from the innermost constructor outward β€” the most specific
constructor runs first, then control returns to the calling constructors.


Common Mistakes

1. Recursive Constructor Call

public Person(String name) {
    this(name); // calls itself β†’ StackOverflowError at compile time!
}
Enter fullscreen mode Exit fullscreen mode

Constructor chains must always terminate. Java detects direct recursion at
compile time.

2. Forgetting to Initialize Critical Fields

public class BankAccount {
    String owner;
    double balance;

    public BankAccount(String owner) {
        this.owner = owner;
        // balance is never set β€” could cause bugs in complex objects
    }
}
Enter fullscreen mode Exit fullscreen mode

Always initialize every field that matters to the object's validity.

3. Confusing Constructor With Method

public class Dog {
    void Dog() { // ❌ This is a METHOD, not a constructor!
        System.out.println("Initializing...");
    }
    // Java silently ignores this as a constructor
}
Enter fullscreen mode Exit fullscreen mode

⚠️ Adding any return type (including void) turns your constructor into a
regular method. Java won't warn you β€” it will just never call it during
object creation.


Interview Questions & Answers

Q1. Can a constructor be private? What is the use case?

Yes. A private constructor is used in the Singleton design pattern to
prevent external code from creating more than one instance of a class. The
class controls its own instantiation through a static method.

Q2. What is the difference between a constructor and a method?

Feature Constructor Method
Name Same as class Any name
Return type None Must have one
Called Automatically via new Explicitly by programmer
Purpose Initialize object Define behavior
Inherited No Yes

Q3. Does Java provide a default constructor if you define your own?

No. Java only provides a default no-arg constructor if you haven't defined
any constructor at all. The moment you write even one constructor, Java's
default disappears. This trips up developers using Hibernate or Spring β€” always
add a no-arg constructor explicitly when needed.

Q4. Can constructors be inherited?

No. Constructors are not inherited. A subclass can call a parent
constructor using super(), which must also be the first line. If you don't
call super() explicitly, Java inserts a call to the parent's no-arg
constructor automatically β€” which will fail if no such constructor exists.

Q5. Can we call a constructor explicitly after object creation?

No. Constructors can only be invoked during object creation (new) or
from within another constructor via this() or super(). They cannot be
called like regular methods after the object exists.

Q6. What happens if a constructor throws an exception?

Object creation fails. The partially constructed object is immediately eligible
for garbage collection β€” Java never returns a partially built object. This
makes constructors a great place to validate inputs and throw
IllegalArgumentException for invalid values.

Q7. What is the role of this() in constructor chaining?

this() calls another constructor of the same class and must be the first
statement in the constructor. It enables chaining so that initialization logic
lives in one place, eliminating code duplication across multiple constructors.


πŸ” Reality Check for Learners

Here's something most tutorials won't tell you: in modern Java codebases
(especially Spring Boot), you'll rarely write constructors manually β€” frameworks
inject dependencies automatically. But you still need to understand constructors
deeply to debug those frameworks when things go wrong.

Libraries like Lombok (@AllArgsConstructor, @NoArgsConstructor) can
auto-generate constructors, but knowing what's being generated makes you a
much stronger developer.

Bottom line: knowing constructors deeply = knowing Java objects deeply.
That's never wasted knowledge.


Best Practices

1. Use constructor chaining
Delegate to one "master" constructor via this(). Initialization logic should
live in exactly one place.

2. Keep constructors simple
Don't do heavy computation, I/O, or complex logic inside a constructor. If
creation can fail, consider a static factory method instead.

3. Validate inputs early
Throw meaningful exceptions (IllegalArgumentException) for invalid inputs β€”
prevent objects from being created in a broken state.

4. Always add a no-arg constructor when needed
JPA, Hibernate, and serialization frameworks require one. Add it explicitly
whenever you define other constructors and use these frameworks.


Conclusion

Constructors are the foundation of every Java object. Here's what you now know:

  • A constructor initializes an object when it's created with new
  • It has the same name as the class and no return type
  • Java provides a default no-arg constructor only if you define none
  • Constructor overloading gives you flexible ways to create objects
  • Constructor chaining with this() reduces duplication and centralizes logic
  • Common pitfalls: adding a return type, recursive calls, missing no-arg constructor

Next up: Explore super() to understand how constructors work across
inheritance hierarchies β€” that's where it gets even more interesting.


Found this helpful? Drop a ❀️ and share it with someone preparing for Java
interviews. Questions or corrections? Leave a comment below!

Top comments (0)