In our earlier post we learnt about method overloading.Today we shall apply that technique to overload constructors.A method is said to be constructor if the name of the method and the name of the class where it presents is same.During the declaration of the object some times we need to declare different types of object.One may take one parameter as input, other may take two parameters of as inputs,it is dependent of the user.Therefore we need to write to different constructors to initialize different types of objects.
The demo program which follows constructor overloading is:
import java.util.Scanner; class construover { int x; double y; construover() //default consturctor with zero parameters. { x=0; y=0; } construover(int a) //Constructor with one parameter. { x=a; } construover(int a,double b) //Constructor with two parameters. { x=a; y=b; } void display() { System.out.println("X value is:" + x); System.out.println("y value is:" + y); } } class construoverdemo { public static void main(String arg[]) { construover ob = new construover(); //Invokes default constructor. construover ob1 = new construover(10); //Invokes constructor with one parameter. construover ob2 = new construover(10,5.35); //Invokes constructor with one parameter. ob.display(); System.out.println("Variables invoked through single parameter consturctor"); ob1.display(); System.out.println("Variables invoked through double parameter consturctor"); ob2.display(); } }
The output of the above program is:
You can download the program.