by Dinesh Thakur Category: Introduction to Java

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 r1,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.

r1.setData(5,6);//sets length and breadth of r1 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 an object before the reference to this object is returned by new. A constructor does look and feel a lot like a method but it is different from a method generally in two ways.

A constructor always has the same name as the class whose instance members they initialize. The constructor does not have a return type, nor even void. It is because the constructor is automatically called by the compiler whenever an object of a class is created.

The main purpose of a constructor is to initialize a new object. Java does not allocates memory for objects at application startup time but rather when the instance is created by keyword new. When new is invoked, Java allocates enough memory to hold the object and then initializes any instance variables to default values.

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 are separated from each other by commas.

Now let us consider a program

// use of Constructor

Class Rectangle{

    int length;

    int breath;

    Rectangle(){ length =5; breath =6;}

    int area(){int rectArea = length * breath; Return rectArea;}

}

Class Constructordemo {

      Public staticvoidmain(String args[]){

          Rectangle firstRect =newRectangle();

          System.out.println(“Area of Rectangle=+ firstrect.area());

      }

}

Output: Area of rectangle = 30

Explanation : In this program, 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 firstRect. 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.

There are three types of Constructor as follows:-

1)Default Constructor:-  Each time an object is created, a constructor is always invoked. In the above program, the constructor we created was invoked. But in the programs that we made earlier, we did not create any constructor. So in such situations, the compiler automatically writes one for you. This constructor is known as the default constructor. It does not contain any parameters nor does it contain any statements in its body. Its only purpose is to enable you to create object of class type. The default constructor looks like
                                                  public Rectangle(){ }
When the compiler creates a default constructor; it does nothing. The objects created by the default constructor will have fields with their default values.
It should be remembered that constructors are invoked only after the instance variables of a newly created object of the class have been assigned their default initial values and after their explicit initializers are executed.

2)Parameterized Constructor :- Unlike default constructor which do not have any parameters, it is however possible to have one or more parameters in a constructor. This type of constructor which have parameters is known as parameterized constructor. Using parameterized constructor, it is possible to initialize objects with different set of values at the time of their creation. These different set of values initialized to objects must be passed as arguments when constructor is invoked. The parameter list can be specified in the parentheses in the same way as parameter list is specified in the method.

In order to understand the concept of parameterized constructor, let us again consider the Rectangle class in which we defined a zero parameter constructor to assign the same set of values to all the objects of the Rectangle class. But if we want to create objects of Rectangle class and initialize different set of values then we need to create a parameterized constructor as illustrated in the following program.

class Rectangle {

     int length;

     int breadth;

     Rectangle(int l, int b) { length = l; breath = b; }

     int area() { return(length * breath); }

     class ParaConstructor {

        public static void main(String[] args) {

           Rectangle firstRect = new Rectangle(5,6);

           Rectangle secondRect = new Rectangle(7,8);

           System.out.println("Area of first rectangle ="+firstRect.area());

           System.out.println("Area of second rectangle="+secondRect.area()) ;

        }

}

3)Copy Constructor:- This is also Another type of Constructor. InConstructor object of another Constructor is passed As name Suggests you Copy means Copy values of another Class object This is used for Copying the values of class object into an another object of class So For Calling Copy Constructor We have to pass the name of object whose values we wants to Copying .

Destructor:

1. It is a member function whose name is same as the class. But preceded by a ~ (tilde) symbol.

2. It has no return type.

3. It cannot have parameters.

4. It is implicitly called when object is no longer required.

5. It is used to release the memory and close files and database conversions.

( No Destructor concept in java )

Note :- java does not support destructor. But it is supported by C,C++.





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.