Constructor In Java With Example

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 is used to initialize instance variables of an object before the reference of this object is returned by new. Constructor can be defined as a method having same name as class name without any return type.

Important Note: A constructor does look and feel a lot like a method but it is different from a method in two ways:

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

Need of Constructor:

Initializing a variable is 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. It can be done by using following two approaches:

  • In the first approach we use a dot operator to access and assign values to the instance variables for each object individually. However it can be tedious job to initialize the instance variables of all objects individually. Moreover, it does not promote data hiding.
  • In second approach we make use of method to assign values to fields of each object individually. But it would have to be called explicitly for each object. This would be inconvenient if the number of objects is very large.

A better solution to the above problems is to initialize values to the object at a time of its creation in the same way as we initialize values to the variable of primitive data types. This is accomplished using a special method in java known as constructor that makes an object to initialize itself at the time of its creation without the need to make separate call to the instance method.


Syntax of Constructor:

The syntax of constructor is as follows:

ConstructorName([parameterList])

{

  //constructor body

}

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

The parameterList is the list of optional zero or more parameters that are specified after the class name in the parenthesis. Each parameter specification, if any, consists of a type and a name and are separated from each other by commas.

Let us consider the program that gives us the use of constructor to initialize the instance variables of the newly created object.

Firstly we make a class Rectangle in which we declare constructor and method to show how to use it:

//use of constructor

class Rectangle

{

  int length;

  int breadth;

  //declare constructor to initialize length and breadth of rectangle

  Rectangle()

  {

    length=5;

    breadth=6;

  }

  //declare method to calculate area of rectangle

  int area()

  {

    int rectArea=length*breadth;

    return rectArea;

  }

}

Then we create a class ConstructorDemo which inherits the above class Rectangle and is used to create objects of the Rectangle class and calculate its area:

//class to create a rectangle objects and calculate area

class ConstructorDemo

{

  public static void main(String args[])

  {

    Rectangle r=new Rectangle();

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

  }

}

Output:

Area of rectangle= 30

Explanation:

  • In the above program when the statement: Rectangle r=new Rectangle(); is executed the new operator creates a new but object of the class that is uninitialized.
  • Then the constructor(Rectangle()) is called and the statements in its body are executed.
  • Then the address of the allocated Rectangle object is returned and assigned to the reference variable r. This method of initializing instance variables of an objects using constructor is very simple and concise as there is no need to explicitly or directly call the method of each object separately.

 Types of Constructor:

There are three types of constructors. These are:

  • Default Constructor – Compiler automatically creates one constructor if we don’t create
  • Parameterized Constructor – Constructor with parameter which make possible to initialize objects with different set of values at time of their creation
  • Copy Constructor – Constructor which creates a new object using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument

Below we have describe all three constructor in detail with example:


Default Constructor:

Each time an object is created, a constructor is always invoked. But in some programs if we don’t create any constructor. So in such situations, the compiler automatically creates one constructor which is known as default constructor. It does not contain any parameters and doesn’t even 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(){}

Important Note: 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.

Program Example of Default Constructor:

Let us consider a program to demonstrate the use of the default values, initialize expressions and constructors.

Firstly we create a class Display in which we declare default constructor:

class Display

{

  int a=6; //initializer expression

  int b=5; //initializer expression

  int c; //assigned default value

  Display()

  {

    a=4; //override default and initializer expression

  }

  void show()

  {

    System.out.println("Value of a="+a);

    System.out.println("Value of b="+b);

    System.out.println("Value of c="+c);

  }

}

Then we create a class DisplayDemo which inherits the methods from above class Display:

class DisplayDemo

{

  public static void main(String args[])

  {

    Display data=new Display();

    data.show();

  }

}

Output:

Value of a= 4
Value of b= 5
Value of c= 0

Parameterized Constructor:

The constructor which has parameters is known as parameterized constructor. Using parameterized constructor, it is possible to initialize objects with different set of values at 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 parenthesis in the same way as parameter list is specified in the method.

Program Example of Parameterized Constructor:

Let us consider a program to understand the concept of parameterized constructor.

First we make a class Rectangle in which we declare the parametrized constructor:

class Rectangle

{

  int length;

  int breadth;

  //constructor to initialize length and breadth of rectangle

  Rectangle(int l, int b)

  {

    length=l;

    breadth=b;

  }

  //method to calculate area of rectangle

  int area()

  {

    return (length*breadth);

  }

}

Second we create a class ParamConstructorDemo which inherit the methods of above class Rectangle and create the object of Rectangle class and calculate its area:

//class to create a rectangle objects and calculate area

class ParamConstructorDemo

{

  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());

  }

}

Output:

Area of first rectangle= 30
Area of second rectangle= 56

Copy Constructor:

Sometimes a programmer wants to create an exact but separate copy of an existing object so that any changes to the copy should not alter the original or vice versa. This is made possible by using the copy constructor. A copy constructor is a constructor that creates a new object that is using an existing object of the same class and initializes each instance variable of newly created object with corresponding instance variables of the existing object passed as argument. This constructor takes a single argument whose type is that of the class containing the constructor.

Program Example of Copy Constructor:

Let us consider a program in which we create a copy of an existing object.

First we create a class Rectangle in which we declare the copy constructor to initialize length and breadth:

class Rectangle

{

  int length;

  int breadth;

  //constructor to initialize length and breadth of rectangle

  Rectangle(int l, int b)

  {

    length=l;

    breadth=b;

  }

  //copy constructor

  Rectangle(Rectangle obj)

  {

    System.out.println("copy constructor invoked");

    length=obj.length;

    breadth=obj.breadth;

  }

  //method to calculate area of rectangle

  int area()

  {

    return (length*breadth);

  }

}

Second we create a class CopyConstructorDemo which inherit the methods of above class Rectangle and create its object and calculate area:

//class to create a rectangle objects and calculate area
class CopyConstructorDemo

{

public static void main(String args[])

{

Rectangle firstRect=new Rectangle(5,6);

Rectangle secondRect=new Rectangle(firstRect);

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

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

}

}

Output:

Copy constructor invoked
Area of first rectangle= 30;
Area of second rectangle= 30;

 Constructor Overloading:

Constructor can be overloaded in the same way as you can overload methods. Constructor overloading allows a class to have more than one constructor that have same name as that of the class but differs only in terms of number of parameters or parameter’s data type or both. By overloading a constructor for a class, we make the class more versatile as it allows you to construct objects in a variety of ways.

Program Example of Constructor Overloading:

In order to understand the concept of constructor overloading, let us consider the following program.

First we create class Rectangle in which we declare more than one constructor of same name to show constructor overloading:

//constructor overload

class Rectangle

{

  int length;

  int breadth;

  Rectangle()

  {

    System.out.println("Constructor with zero parameter called");

    length=breadth=0;

  }

  Rectangle(int side)

  {

    System.out.println("constructor with one parameter called");

    length=breadth=side;

  }

  Rectangle(int l,int b)

  {

    System.out.println("constructor with two parameters called");

    length=l;

    breadth=b;

  }

  int area()

  {

    return(length*breadth);

  }

}

Second we create class ConstructorOverload which inherits the above class Rectangle:

class ConstructorOverload

{

  public static void main(String args[])

  {

    Rectangle r1=new Rectangle();

    Rectangle r2=new Rectangle(5);

    Rectangle r3=new Rectangle(7,8);

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

    System.out.println("Area of square="+r2.area());

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

  }

}

Output:

Constructor with zero parameter called
Constructor with one parameter called
Constructor with two parameters called
Area of first rectangle= 0
Area of square= 25
Area of second rectangle= 56

Explanation of Example:

In the above program, the class Rectangle contains three constructor with the same name Rectangle which differ only in the number of parameters and hence overloaded.


 Important Points to Remember About Constructor:

  • No class can exist without any constructor.
  • If there is no constructor in a class then one non parameterized (default) constructor is inserted in that class by the compiler.
  • Copy constructor is used to create a duplicate copy of existing object.

Leave a Reply

Your email address will not be published. Required fields are marked *