Explain the concept of constructor overloading with an example.

Short Answer
Views 15

Answer:

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.

Related Articles:

This section is dedicated exclusively to Questions & Answers. For an in-depth exploration of Java Programming Language, click the links and dive deeper into this subject.

Join Our telegram group to ask Questions

Click below button to join our groups.