Can we overload the constructors?

Solution:

Yes, the constructors can be overloaded by changing the number of arguments accepted by the constructor or by changing the data type of the parameters. Consider the following example.

class Test   
{  
    int i;   
    public Test(int k)  
    {  
        i=k;  
    }  
    public Test(int k, int m)  
    {  
        System.out.println("Hi I am assigning the value max(k, m) to i");  
        if(k>m)  
        {  
            i=k;   
        }  
        else   
        {  
            i=m;  
        }  
    }  
}  
public class Main   
{  
    public static void main (String args[])   
    {  
        Test test1 = new Test(10);  
        Test test2 = new Test(12, 15);  
        System.out.println(test1.i);  
        System.out.println(test2.i);  
    }  
}  

In the above program, The constructor Test is overloaded with another constructor. In the first call to the constructor, The constructor with one argument is called, and i will be initialized with the value 10. However, In the second call to the constructor, The constructor with the 2 arguments is called, and i will be initialized with the value 15.

0 answers