Home / Questions / Explain the concept of constructor overloading with an example.
Explanatory Question

Explain the concept of constructor overloading with an example.

👁 115 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Constructor overloading:

Constructor overloading occurs when a class has more than one constructor with different parameter lists. Each constructor initializes the object in different ways depending on the provided arguments.

Example:


class Student {
    String name;
    int age;

    // Constructor with no arguments
    Student() {
        name = "Unknown";
        age = 0;
    }

    // Constructor with one argument
    Student(String n) {
        name = n;
        age = 0;
    }

    // Constructor with two arguments
    Student(String n, int a) {
        name = n;
        age = a;
    }
}

In this example, the class Student has three constructors, each with different parameter lists. This is constructor overloading.