Constructor overloading

 

Constructor Overloading 



Constructor in Java

 

A constructor is a special method of a class which is automatically invoked when an object of the class is created.

Constructors

  1. Have the same name of the class
  2. Are always public
  3. Has no return type (not even void)
  4. Generally used for Object Initialization – Set default values, Allocate resources and prepare object state
  5. Cannot be abstract, static or final.
  6. Can be overloaded

Syntax for Creating a Constructor

class <class_name>
{
        // constructor
        <class_name>()
        {
            // code for initializing the object
        }
}

Types of Constructors in Java

Java has three main types of constructors:

  • Default Constructor (No-Argument Constructor) – used to initialize object with default values
  • Parameterized Constructor – Takes arguments to initialize the object
  • Copy constructor – Takes another object of the same class as argument and initializes the new object its values

 


 

Example

// Types of constructors in Java

// Constructor overloading

 

class Rectangle

{

         int l, b;

        

         // Default Constructor

         Rectangle()

         {

                 l = 5;

                 b = 7;

         }

        

         // Parameterized Constructor

         Rectangle(int x, int y)

         {

                 l = x;

                 b = y;

         }

        

         // Copy Constructor

         Rectangle(Rectangle R)

         {

                 this.l = R.l;

                 this.b = R.b;

         }

        

         void fnArea()

         {

                 System.out.println("Area of Rectangle = "+(l*b));

         }

}

 

 

 

class Constructor_Overloading

{

         public static void main(String as[])

         {

                 Rectangle r1 = new Rectangle();

                 System.out.println("Calling Default Constructor.");

                 r1.fnArea();

                

                 Rectangle r2 = new Rectangle(10,20);

                 System.out.println("Calling Parameterized Constructor.");

                 r2.fnArea();

                

                 Rectangle r3 = new Rectangle(r2);

                 System.out.println("Calling Copy Constructor.");

                 r3.fnArea();

         }

}

 

Sample output

 

>javac Constructor_Overloading.java

>java Constructor_Overloading

 

Calling Default Constructor.

Area of Rectangle = 35

Calling Parameterized Constructor.

Area of Rectangle = 200

Calling Copy Constructor.

Area of Rectangle = 200

 

 



No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu