Constructor Overloading

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:
construc_over
You can download the program.

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java and tagged , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s