CodeBlanks Logo Icon CodeBlanks

Constructor overloading

Learn multiple constructors in the same class.

Constructor overloading

A class can have more than one constructor; this is called overloading. Each constructor must have a different parameter list: the number, type or order of parameters can vary. Which constructor is called depends on the values in the parentheses.

Example: class Rectangle { int w, h; Rectangle() { w = 0; h = 0; } Rectangle(int s) { w = s; h = s; } }. Here two constructors exist. new Rectangle() calls the first, new Rectangle(5) the second. Overloading provides flexible instantiation; it prepares the instance with different values in different situations.

Which constructor is called?

Java decides which constructor to run by looking at the number and types of arguments in the call. If exactly one constructor matches, it calls it. If none matches or the match is ambiguous, a compile error occurs.

Example: new Rectangle() calls the no-arg constructor, new Rectangle(5) the single-parameter one. new Rectangle(5, 3) works only if a two-parameter constructor exists. Type conversion is also considered; new Rectangle(5.0) does not match an int parameter.

Practice Add two constructors to Rectangle

Define a class named Rectangle. Add int w and int h fields. Write two constructors: the first takes no arguments and sets both to zero; the second takes an int s and assigns s to both w and h. In main call both constructors and print the w fields on separate lines.

Starter code

Main.java
// Define the Rectangle class
// Add two constructors
// Call both in main

Sample solution

Main.java
class Rectangle {
    int w;
    int h;
    Rectangle() {
        w = 0;
        h = 0;
    }
    Rectangle(int s) {
        w = s;
        h = s;
    }
    public static void main(String[] args) {
        Rectangle a = new Rectangle();
        Rectangle b = new Rectangle(5);
        System.out.println(a.w);
        System.out.println(b.w);
    }
}

Expected output

0
5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is true about overloading?

  • Two constructors must have the same parameter list
  • Constructors must have return types
  • A class must have only one constructor
  • Two constructors must have different parameter lists Correct answer

Explanation: In overloading, each constructor must have a different parameter list.

2 Complete the second constructor

Question
class Rectangle {
    int w, h;
    Rectangle() { w = 0; h = 0; }
    ____(int s) { w = s; h = s; }
}
Answer
class Rectangle {
    int w, h;
    Rectangle() { w = 0; h = 0; }
    Rectangle(int s) { w = s; h = s; }
}

Explanation: The second constructor is also defined with the class name.

3 Match call to constructor

Term Meaning
new Rectangle() No-arg constructor
new Rectangle(5) Single-param constructor
new Rectangle(5, 3) Two-param constructor

All lessons in Intermediate