Constructors in Java With Examples

After the creation of the instance, it is important to initialize the variables of the classes. It becomes tough to initialize every variable of every instance as object creation is a very frequent event to happen. It would be convenient to initialize all the variables at the time of object creation. Java allows objects to be initialized with the help of constructors.

What is Constructor?

 A constructor is a block of code dedicated to initialize the object, which is implicitly called when the object of the class is created.

It initializes an object immediately at the time of its creation. It is a block of code with a syntactic resemblance to the method and having the same name as the class (The name is exactly the same, without any case differences). Once it is defined, the constructor is automatically called during the object created using the keyword new. There can exist one or more constructors for a class, and at least one version of the constructor is called, we instance is created using new.

Despite some resemblance to the method, it is still different. There is no return type of a constructor. In the case of methods, when nothing is to be returned, we mention void. But in the case of a constructor, the return type is not even void. It is because the return type of the class’s constructor is the class itself. The internal state of an object is initialized by the constructor to make it a usable object immediately after creation.

It is to be noted that keywords like abstract, static, final cannot be used with the constructor. Access specifiers can be used with constructors to control object creation.

General Format of Constructor

class Alpha{
<access specifier> Alpha(<parameter-list>){
//Code for initialization
}
}

Checklist for a Constructor

  • The name of the constructor is the same as of Class.
  • There is no return type.
  • The access specifier can be mentioned here. Not mentioning any, means default access specifier.

Calling of a constructor

The constructor is called implicitly whenever we create an object using new.

<ClassName> <myObjectName> = new <ClassName>();
<ClassName> <myObjectName> = new <ClassName>(parameter-list);

Types of Constructors

There are two types of constructor:

  • Default constructor(No-argument)
  • Parameterised Constructor

Default constructor(No-argument)

It is not the case, that we haven’t created any classes yet, but we dint define any constructor yet. So how was our object’s state initialized?  It is because, when there is no explicit mention of a constructor, the compiler provides a default constructor that provides the default value to very variable according to their individual data type.

But if we explicitly provide a default constructor, the compiler does not create any default constructor on its own. It is the developer’s version which is referred to.

Let us see an example to get a clearer vision.

Example:

public class TechieClues{
     //The variables
     int myId;
     String myName;
    
     public static void main(String []args){
        //Constructor calling
        TechieClues obj1 = new TechieClues();
        System.out.println("The ID of object obj1 is "+obj1.myId);
        System.out.println("The name of object obj1 is "+obj1.myName);
     }
}

Output:

The ID of object obj1 is 0
The name of object obj1 is null

We can see that, constructor was not mentioned, hence the compiler created a default constructor and assigned the default values to the variables according to their data type.

Now, let us look into the version, where we mention our own default constructor.

public class TechieClues{
     //The variables
     int myId;
     String myName;

     //The default constructor
     TechieClues(){
      System.out.println("This is the default constructor we created");
      myId=10;
      myName="Gopal";
     }

     public static void main(String []args){
        //Constructor calling
        TechieClues obj1 = new TechieClues();
        System.out.println("The ID of object obj1 is "+obj1.myId);
        System.out.println("The name of object obj1 is "+obj1.myName);
     }
}

Output:

This is the default constructor we created
The ID of object obj1 is 10
The name of object obj1 is Gopal

Here since the default constructor was mentioned, the value of variables is the ones we mentioned inside the constructors, unlike the default value in the previous case. The fact is, the compiler doesn’t even create any default constructor as we have mentioned one.

Parameterized Constructor

As the name indicates, the constructor with one or more parameters is called a parameterized constructor. 

Let us add a parameterized constructor to the existing class.

public class TechieClues{
     //The variables
     int myId;
     String myName;

     //The default constructor
     TechieClues(){
      System.out.println("This is the default constructor we created");
      myId=10;
      myName="Gopal";
     }

     //The parameterized constructor
     TechieClues(int id, String name){
      System.out.println("This is the parameterized constructor we created");
      myId=id;
      myName=name;
     }

     public static void main(String []args){
        //Constructor calling
        TechieClues obj1 = new TechieClues(22,"Madhurav");     
        System.out.println("The ID of object obj1 is "+obj1.myId);
        System.out.println("The name of object obj1 is "+obj1.myName);
     }
}

Output:

This is the parameterized constructor we created
The ID of object obj1 is 22
The name of object obj1 is Madhurav

As we can see, the values we pass in the constructor is used for initialization purpose. Do notice that, we are having multiple versions of the constructor at the same time. This is called overloading(We will discuss it in the Java Polymorphism section).

There is another variant of Constructor, called copy constructor. The constructor which takes the object of the same type as an input, and copies all the value to create an object with the exact same state is called a copy constructor.

Example:

public class TechieClues{
     //The variables
     int myId;
     String myName;
 
     //The default constructor
     TechieClues(){
      System.out.println("This is the default constructor we created");
      myId=10;
      myName="Gopal";
     }

     //The parameterized constructor
     TechieClues(int id, String name){
      System.out.println("This is the parameterized constructor we created");
      myId=id;
      myName=name;
     }

     //The Copy Constructor
      TechieClues(TechieClues objectToCopy){
      System.out.println("\nThis is the copy constructor we created");
      myId=objectToCopy.myId;
      myName=objectToCopy.myName;
     }

     public static void main(String []args){
        //Parameterized Constructor calling
        TechieClues obj1 = new TechieClues(22,"Madhurav");
        System.out.println("The ID of object obj1 is "+obj1.myId);
        System.out.println("The name of object obj1 is "+obj1.myName);

        //Copy Constructor calling to copy the values of obj1
        TechieClues obj2 = new TechieClues(obj1);
        System.out.println("The ID of object obj2 is "+obj2.myId);
        System.out.println("The name of object obj2 is "+obj2.myName);
     }
}

Output:

This is the parameterized constructor we created
The ID of object obj1 is 22
The name of object obj1 is Madhurav

This is the copy constructor we created
The ID of object obj2 is 22
The name of object obj2 is Madhurav

This was an overview of constructors, we will be discussing Access Specifiers in our next Lecture.