KnowledgeBoat Logo
|

Computer Applications

Explain the concept of constructor overloading with an example.

Java Constructors

ICSE 2011

9 Likes

Answer

Constructor overloading is a technique in Java through which a class can have more than one constructor with different parameter lists. The different constructors of the class are differentiated by the compiler using the number of parameters in the list and their types. For example, the Rectangle class below has two constructors:

class Rectangle {
    int length;
    int breadth;

    //Constructor 1
    public Rectangle() {
        length = 0;
        breadth = 0;
    }

    //Constructor 2
    public Rectangle(int l, int b) {
        length = l;
        breadth = b;
    }

    public static void main(String[] args) {
        //Constructor 1 called
        Rectangle obj1 = new Rectangle();

        //Constructor 2 called
        Rectangle obj2 = new Rectangle(10, 15);
    }
}

Answered By

4 Likes


Related Questions