Java Constructor

What exactly is a constructor?

A Java constructor is a special method of a Java class. Its name is the same as the class name, and it has no return value of any type, not even void. The Java class constructor is automatically called when the object is created; no explicit call is required.

We create an object of a class by using new operator. The Java statement

Employee emp = new Employee();

creates an Employee object emp.

Now emp is created in the memory, but employee-specific details like name, date of birth, date of joining, dept, designation, and so on are still not assigned to emp. The object is incomplete and not usable unless we attach these values.

How do we do that? There are two ways.

  1. We may apply the set methods on object emp after it is created if the set methods are provided by the interface (Ex. 2). If not, we may directly initialize the member variables.
  2. We may use a special method known as a constructor (Ex. 1 and Ex. 3). Constructor provides a cleaner and more elegant solution to this problem. This is our subject of discussion in this article.

The following simple code illustrates the characteristics of constructors. The Test() method is a constructor of the Test class. When the code is run, Executing Constructor is printed, which shows the constructor has been executed when the object was created.

Here is simple example of a Constructor function

			

public class Test {

    Test() {System.out.println("Executing Constructor");}
    
    public static void main(String[] args) {
        Test t = new Test();
    }
}

				

Let us look at Ex. 2, where we use the set methods to initialize variables. Ex. 3 shows a changed version of Ex. 2, where we use a constructor to initialize. The code looks pretty compact and readable.

Here is an example use of set methods to initialize member variables of rect object.

			

class Rectangle {
    //  private variables
    private int length;
    private int breadth;
    //  public set methods
    public void setLength(int length)
    {
        this.length = length;
    }
    public void setBreadth(int breadth)
    {
        this.breadth = breadth;
    }
    public void area()
    {
        System.out.println("Area of the Rectangle is "+length*breadth);
    }
}
class Main {
  public static void main(String[] args) {
      Rectangle rect = new Rectangle();     // Object Created
      rect.setLength(10);                   // length is initialized
      rect.setBreadth(15);                  // breadth is initialized
      rect.area();
  }
}

				

The rect object is initialized when it is created. Rectangle (int, int) is a parameterized constructor. A class may have more than constructors with a varying number of arguments.

			

class Rectangle {
    //  private variables
    private int length;
    private int breadth;
    Rectangle (int length, int breadth) {
        this.length = length;
        this.breadth = breadth;
    }
    public void area()
    {
        System.out.println("Area of the Rectangle is "+length*breadth);
    }
}
 
class Main {
  public static void main(String[] args) {
      Rectangle rect = new Rectangle(10, 15);     // Object Created and initialized
      rect.area();
  }
}

				

Type of Constructors

Constructors are of two types. Constructors which take arguments are called parameterized constructors.

The following example shows a class Sum with two constructors. The one which has no argument is called the default constructor. Even if we do not declare a default constructor in a class, the compiler automatically creates one by default, and that is why it is known as the default constructor.

Class Sum has two constructors – with two parameters and three parameters.

			

class Sum {
    private int sum;    //  private variable
    Sum(int a, int b) {
        sum = a + b;
    }
    Sum(int a, int b, int c) {
        sum = a + b + c;
    }
    public void print()
    {
        System.out.println("Sum of the numbers is "+sum);
    }
}
class Main {
  public static void main(String[] args) {
      Sum tot = new Sum(10, 20);     // Object Created and initialized
      tot.print();
      tot = new Sum(10, 20, 30);     // Existing Object initialized
      tot.print();
  }
}