Constructor Overloading and Constructor Chaining

Naveen AnamaneniUpdated · 4 min read

A bank lets you open an account in different ways: with just your name (zero balance), with a name and an opening deposit, or with a name, a deposit and an account type. That's constructor overloading: several constructors with different parameter lists. To avoid writing the same setup three times, the shorter ones call the fullest one with this(...). That's constructor chaining.

Overloaded Constructors

Overloaded.java▶ Try it
public class Overloaded {
    static class BankAccount {
        String holder;
        long balance;
        String type;
 
        BankAccount(String holder) {
            this(holder, 0);
        }
 
        BankAccount(String holder, long balance) {
            this(holder, balance, "Savings");
        }
 
        BankAccount(String holder, long balance, String type) {
            if (balance < 0) throw new IllegalArgumentException("Bad balance");
            this.holder = holder;
            this.balance = balance;
            this.type = type;
        }
 
        String show() { return holder + " | " + type + " | Rs. " + balance; }
    }
 
    public static void main(String[] args) {
        System.out.println(new BankAccount("Navika").show());
        System.out.println(new BankAccount("Srihitha", 12000).show());
        System.out.println(new BankAccount("Advitha", 50000, "Current").show());
    }
}
Output
Navika | Savings | Rs. 0
Srihitha | Savings | Rs. 12000
Advitha | Current | Rs. 50000

How it works

  1. Three constructors share the name BankAccount but take 1, 2 or 3 parameters. Java picks one by the arguments in each new, exactly like method overloading (see "Method Signature").
  2. Line 8: the one-parameter constructor calls the two-parameter one with this(holder, 0).
  3. Line 12: the two-parameter constructor calls the three-parameter one, adding the default type "Savings".
  4. Only the last constructor contains the validation and the field assignments. Every route ends there.
Every constructor ends at the one that does the real work

Try it yourself: call new BankAccount("Navika", -5). Which constructor's check stops it?

Rules for this(...)

RuleDetail
Calls another constructor of the same classthis(...)
Calls a constructor of the parent classsuper(...) (see "Java Super Keyword")
Only one per constructorA constructor can call this(...) or super(...), not both
Can't form a loopThe compiler rejects constructors that call each other in a circle
PositionBefore Java 25, it had to be the first statement. From Java 25, simple statements may come before it (see "Flexible Constructor Bodies")

A loop of constructor calls is caught at compile time:

Compiler output
Recur.java:1: error: recursive constructor invocation
class A { A() { this(1); } A(int n) { this(); } }
                                      ^

Common Mistakes

Copying the setup into every constructor. When a rule changes, one copy gets missed. Chain instead.

Calling a constructor by name. BankAccount(holder, 0); inside a constructor doesn't compile; write this(holder, 0);.

Creating a new object instead of chaining. new BankAccount(holder, 0); inside a constructor makes a second, separate object and leaves the current one unset.

Interview Corner

What is constructor chaining?

Calling one constructor from another: this(...) calls another constructor of the same class, and super(...) calls a constructor of the parent class. It lets overloaded constructors share one place for validation and setup.

Can a constructor call both this() and super()?

No. A constructor may contain at most one explicit constructor call, either this(...) or super(...). If it calls this(...), the constructor it calls will eventually call super(...).

Practice

  1. Easy: Add a no-arg constructor to BankAccount that chains to this("Unknown").
  2. Harder: Write a Pizza class with constructors for (size), (size, crust) and (size, crust, extraCheese), chained so that defaults live in one place, and print three pizzas.

Quick check: Constructor chaining

4 questions
1What is constructor overloading?
2What does this(holder, 0) inside a constructor do?
3Why put validation only in the most complete constructor?
4What does the compiler report for A() { this(1); } A(int n) { this(); }?

Key Takeaways

Was this tutorial helpful?

Lesson 100 of 482