Can we overload the constructors in Java?

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.

  1. class Test
  2. {
  3.     int i;
  4.     public Test(int k)
  5.     {
  6.         i=k;
  7.     }
  8.     public Test(int k, int m)
  9.     {
  10.         System.out.println(“Hi I am assigning the value max(k, m) to i”);
  11.         if(k>m)
  12.         {
  13.             i=k;
  14.         }
  15.         else
  16.         {
  17.             i=m;
  18.         }
  19.     }
  20. }
  21. public class Main
  22. {
  23.     public static void main (String args[])
  24.     {
  25.         Test test1 = new Test(10);
  26.         Test test2 = new Test(1215);
  27.         System.out.println(test1.i);
  28.         System.out.println(test2.i);
  29.     }
  30. }

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.