Skip to lesson

Constructor overloading

A ticket for a registered customer needs only a name, but a booking with a seat needs more details. One class has to be created in more than one way.

Why more than one constructor?

Constructor overloading means having more than one constructor in the same class, each with a different parameter list (a different number, type or order of parameters), so objects can be created in different ways.

A train ticket may be booked with a berth choice or without one. Overloaded constructors give the class one constructor for each way of creating it, so every caller passes only what it knows.

Example 1 · A ticket with or without a berth

TicketDemo.javaJava
class Ticket {    String passenger;    String berth;
    Ticket(String passenger) {        this.passenger = passenger;        this.berth = "No preference";    }
    Ticket(String passenger, String berth) {        this.passenger = passenger;        this.berth = berth;    }}
public class TicketDemo {    public static void main(String[] args) {        Ticket t1 = new Ticket("Priya");        Ticket t2 = new Ticket("Arjun", "Lower");        System.out.println(t1.passenger + ": " + t1.berth);        System.out.println(t2.passenger + ": " + t2.berth);    }}
Output
Priya: No preference
Arjun: Lower

What this code does

  • One argument → the one-parameter constructor runs and fills in No preference itself.
  • Two arguments → the two-parameter constructor runs and uses the berth given.

It is the same idea as Method overloading (opens in a new tab), applied to constructors. It also brings back new Student() after you add a constructor with parameters: write a no-argument one next to it.

How Java picks the constructor

Java looks at the arguments in new: how many there are, their types and their order. It picks the one constructor whose parameter list matches, and javac makes this choice at compile time, before the program runs.

Example 2 · Three ways to create a student

ThreeWaysDemo.javaJava
class Student {    String name;    int marks;
    Student() {        this.name = "New student";        System.out.println("Ran Student()");    }
    Student(String name) {        this.name = name;        System.out.println("Ran Student(String)");    }
    Student(String name, int marks) {        this.name = name;        this.marks = marks;        System.out.println("Ran Student(String, int)");    }}
public class ThreeWaysDemo {    public static void main(String[] args) {        Student a = new Student();        Student b = new Student("Kavya");        Student c = new Student("Rohan", 78);        System.out.println(a.name + " " + a.marks + " | " + b.name + " " + b.marks + " | " + c.name + " " + c.marks);    }}
Output
Ran Student()
Ran Student(String)
Ran Student(String, int)
New student 0 | Kavya 0 | Rohan 78

What this code does

  • Each new runs exactly one constructor, chosen by the arguments it passes.
  • Fields a constructor does not set keep their default value, so a and b have 0 marks.

Example 3 · No constructor matches the call

NoMatchDemo.javaJava
class Ticket {    String passenger;    String berth;
    Ticket(String passenger) {        this.passenger = passenger;        this.berth = "No preference";    }
    Ticket(String passenger, String berth) {        this.passenger = passenger;        this.berth = berth;    }}
public class NoMatchDemo {    public static void main(String[] args) {        Ticket t = new Ticket("Priya", "Lower", 42);        System.out.println(t.berth);    }}
Sample compiler output
NoMatchDemo.java:18: error: no suitable constructor found for Ticket(String,String,int)
        Ticket t = new Ticket("Priya", "Lower", 42);
                   ^
    constructor Ticket.Ticket(String) is not applicable
      (actual and formal argument lists differ in length)
    constructor Ticket.Ticket(String,String) is not applicable
      (actual and formal argument lists differ in length)
1 error

What this code does

  • With several constructors, javac lists each one it tried and why it did not fit.
  • Fix: call one that exists, or add Ticket(String, String, int) if a seat number is really needed.

An exact type match wins: with Fee(int) and Fee(double), new Fee(500) calls the int one and new Fee(500.0) calls the double one.

What makes two constructors different

Every constructor has the class name, so only the parameter list can tell them apart. Java compares the parameter types, in order; the parameter names do not count.

Example 4 · Same count, different types

RechargeDemo.javaJava
class Recharge {    String plan;    int price;
    Recharge(int price) {        this.price = price;        if (price >= 299) {            this.plan = "Unlimited";        } else {            this.plan = "Basic";        }    }
    Recharge(String plan) {        this.plan = plan;        if (plan.equals("Unlimited")) {            this.price = 299;        } else {            this.price = 199;        }    }}
public class RechargeDemo {    public static void main(String[] args) {        Recharge r1 = new Recharge(349);        Recharge r2 = new Recharge("Basic");        System.out.println(r1.plan + " for Rs. " + r1.price);        System.out.println(r2.plan + " for Rs. " + r2.price);    }}
Output
Unlimited for Rs. 349
Basic for Rs. 199

What this code does

  • Both constructors take one argument, so the type decides: 349 is an int, "Basic" is a String.
  • Each constructor works out the missing value in its own way.

Example 5 · Same parameter types twice: already defined

DupDemo.javaJava
class Student {    String name;    String city;
    Student(String name) {        this.name = name;    }
    Student(String city) {        this.city = city;    }}
public class DupDemo {    public static void main(String[] args) {        Student s = new Student("Priya");        System.out.println(s.name);    }}
Sample compiler output
DupDemo.java:9: error: constructor Student(String) is already defined in class Student
    Student(String city) {
    ^
1 error

What this code does

  • Both constructors are Student(String). The names name and city do not make them different.
  • Java could never tell which one new Student("Priya") means, so it refuses the class.
  • Different number: Student(), Student(String), Student(String, int) → allowed.
  • Different types: Recharge(int) and Recharge(String) → allowed.
  • Same types in a different order: Item(String, int) and Item(int, String) → allowed, but easy to confuse.
  • Only the names differ: Student(String name) and Student(String city) → already defined.

Predict the output

Which constructor runs?

Read the code and pick what it prints.

Round 1 of 2

Box has two constructors. Which one does new Box("5") run?

class Box {
Box(int size) {
System.out.println("B");
}
Box(String label) {
System.out.println("C");
}
}
public class BoxDemo {
public static void main(String[] args) {
new Box("5");
}
}

The hidden cost: repeated code

Two constructors each copy the same assignments, and later a marks check is added to only one of them. Repeated code drifts apart, so a bad object can come in through the constructor that was forgotten.

Example 6 · Repeated code lets a bad object in

RepeatBugDemo.javaJava
class Student {    String name;    int marks;
    Student(String name, int marks) {        if (marks < 0 || marks > 100) {            throw new IllegalArgumentException("Bad marks: " + marks);        }        this.name = name;        this.marks = marks;    }
    Student(int marks) {        this.name = "Unknown";        this.marks = marks;      // the check was not copied here    }}
public class RepeatBugDemo {    public static void main(String[] args) {        Student s = new Student(150);        System.out.println(s.name + ": " + s.marks);    }}
Output
Unknown: 150

What this code does

  • The two-parameter constructor checks the marks, but the one-parameter constructor has its own copy of the code without the check.
  • So 150 marks gets in through the second door. Nothing warns you: it compiles and runs.

The next lesson, Call one constructor from another with this() (opens in a new tab), removes this repetition: all the constructors then share one set of assignments and one check.

Next step

Check your understanding

12 quick questions