by Dinesh Thakur

Initializing a variable is considered very helpful while making programs. We can initialize variables of primitive types at the time of their declarations. For example:

int a = 10;

In Object Oriented Programming language (OOPL) like Java, the need of initialization of fields of a new object is even more common. We have already done this using two approaches.

In the first approach, we used a dot operator to access and assign values to the instance variables individually for each object. However, it can be a tedious job to initialize the instance variables of all the objects individually. Moreover, it does not promotes data hiding.

r1.length = 5;

r2.length = 7;

where rl, r2 are objects of a Rectangle class.

In another approach, we made use of method setData () to assign values to fields of each object individually. But it would have to be called explicitly for each object. This would become inconvenient if the number of objects are very large.

rl.setData(5,6) ;//sets length and breadth of rl Rectangle object

r2.setData(7,8) ;

The above two approaches does not simulate the problem properly. A better solution to the above problem is to initialize values to the object at the time of its creation in the same way as we initialize values to a variable of primitive data types. This is accomplished using a special method in Java known as constructor that enables an object to initialize itself at the time of its creation without the need to make separate call to the instance method.

A constructor is a special method that is called whenever an object is created using the new keyword. It contains a block of statements that can be used to initialize instance variables of anobject before the reference to this object is returned by new. A constructor does look and feel a lotlike a method but it is different from a method generally in two ways. A constructor always has thesame name as the class whose instance members they initialize. The constructor does not have areturn type, nor even void. It is because the constructor is automatically called by the compiler wheneveran object of a class is created.

The syntax for constructor is as follows,

constructorName([parameterList])

{

//constructor body

}

Here, the ConstructorName is same as the class name it belongs to.

The parameterList is the list of optional zero or more parameter(s) that is specified after the classname in parentheses. Each parameter specification, if any, consists of a type and a name and is separated from each other by commas.

Now let us consider a example,

// use of constructor

class Rectangle

       int length;
       int breadth;
       //constructor to initialize length and breath of rectangle
       Rectangle()
       { 
          length  = 5;
          breadth= 6;
       }
       //method to calculate area of rectangle
       int area()
       {
          int rectArea = length * breadth;
          return rectArea ;
       }
}
     //class to create rectangle objects and calcuats area
      class ConstructorExample
     {
            public static void main(String[] args)
         {
               Rectangle firstRect = new Rectangle();
               System.out.println("Area of Rectantangle  : "+ firstRect.area());
         }
     }

Constructor in Java Example

In this example, when the statement

Rectangle firstRect = new Rectangle();

is executed, the new operator creates a new but uninitialized object of the class. Then the constructor (Rectangle ()) is called and the statements in its body are executed. As a result, the instance variables length and breadth of object firstRect will be initialized to integer literals 5 and 6 respectively. Then the address of the allocated Rectangle object is returned and assigned to the reference variable f'irstRect. This method of initializing instance variable(s) of an object(s) using constructor is very simple and concise as there is no need to explicitly call the method for each object separately.