1
0

Overloading of Constructors in Java

Like methods, constructors can also be overloaded. Since the constructors in a class have the same name as the class, their signatures are differentiated by their parameter lists. In the following example, the class Light now provides both an explicit default constructor and a non-default constructor with arguments within the same class. The non-default constructor is called when an object of class Light is created and the default constructor is called automatically. Overloading of constructors allows appropriate initialization of objects on creation, depending on the constructor invoked.

Program to demonstrate to constructor overloading

class Light
{
    int Watts;
    boolean indicator;
    String location;
    Light()
    {
        Watts=40;
        indicator=true;
        location="Wall";
    }
    Light(int a, boolean b, String s)
    {
        Watts=a;
        indicator=b;
        location=s;
    }
    void display()
    {
        System.out.println("No. of watts = "+Watts);
        System.out.println("Switch indicators = "+indicator);
        System.out.println("Locatiob of the Bulb = "+location);
    }
}
class Greenhouse
{
    public static void main(String st[])
    {
        Light oneLight=new Light(); // Call of explicit default constructors
        oneLight.display();
        // Call of parameterized Constructor
        Light otherLight=new Light(60, true, "Kitchen");
        otherLight.display();
    }
}

Output:

No. of watts = 40
Switch indicators = true
Locatiob of the Bulb = Wall
No. of watts = 60
Switch indicators = true
Locatiob of the Bulb = Kitchen

The above code will create an object oneLight using new operator with the help of an Explicit default constructor and will initialize the fields of the object with their default values. (i.e. 0 for Watts, false for indicator, and null for location). The above code will also create an object otherLight using new operator with the help of parameterized constructor and will initialize the fields of the object with their values 60 for Watts, true for indicator, and Kitchen for location.

Leave a Reply