constructor overloading in java

Like method overloading you can also overload a constructor in java. A constructor is a special purpose class member function for initializing the objects of a class.  A constructor is overloaded on the basis of the arguments or parameters available with it.
Ads by Google


Consider the following class.
     class ConstructorTest  
{
int a,b;
public ConstructorTest()
{
a = 10;
b = 20;
System.out.println("From the default constructor a = "+a+ " and b ="+b);
}
public ConstructorTest(int a,int b)
{
this.a = a;
this.b = b;
System.out.println("From the parameterised constructor a = "+a+ " and b ="+b);
}
}


In this class you can see that there is two constructors present. One is with no arguments and other is with two integer parameters. The compiler will invoke the appropriate constructor when a compatible object initialization found.

For example the statement "ConstructorTest t1 = new ConstructorTest();" will invokes the default constructor, while the statement" ConstructorTest t2 = new ConstructorTest(30,40);" will invoke a constructor with two integer parameters.

Method overloading                                           Index                                Pass by reference