Java-Constructor Overloading

Constructor Overloading

A class shall have several constructors, provided they have different signatures. As we know, the signature of a constructor is a combination of its name and the sequence of its parameter types. The names of all the constructors of a class should be same as the name of that class. Therefore the overloaded constructors should necessarily have different sequences of parameter types. The following program illustrates constructor overloading.

Program

31

Program Source

class Data{
    
    Data()
    {
        System.out.println("Constructor without Parameter");
    }
    
    Data(int i)
    {
        System.out.println("Constructor with Integer");
    }
    
    Data(String str)
    {
        System.out.println("Constructor with String");
    }
}

public class Javaapp {

    public static void main(String[] args) {
       
        Data d1  = new Data();
        Data d2  = new Data(15);
        Data d3  = new Data("String");
    }
}

Leave a Comment