Introduction to Constructors in Java

What is a Constructor?

A constructor is defined inside the class that contains the code to instantiate the class object. For example, the class MobilePhone has a constructor:

public class MobilePhone {
    private int imeiNumber;    
    public String name;
    
    //constructor
    public MobilePhone (int number, String brand) {
        imeiNumber = number;
        name = brand;
    }
    public String getName() {
        return name;
    }
}

Why a Constructor?

In general, we may want our object to get initialized with some specific properties, or we may need to do some operations every time an object is instantiated. To do such things, we use constructors.

Defining a Constructor

In java, a constructor has the following components:

  • First comes the access specifier having the usual meanings as that for methods and fields.
  • The second is the constructor’s name, which must be the class’s name.
  • The third is the parameter list enclosed within “()”. 
  • The last part is the body of the constructor.

Note: A constructor might look like a method, but it isn’t because it does not have a return type.

Calling a Constructor

All classes have an implicit default constructor provided by the compiler (discussed in the latter part). However, we can write constructors ourselves too.

A constructor is called to instantiate the object of the same class. E.g., to instantiate an object of MobilePhone with imeiNumber as “0” and name as “brand,” we call the constructor:

//syntax
<Class name> <variable name> = new <Constructor>;

//Example
MobilePhone mobile = new MobilePhone(0,"brand");

Note: The new operator always creates a fresh instance.

Types of Constructors

In java, there are four types of constructors:

1 . No-argument: A constructor whose parameter list is empty.

MobilePhone() {
    imeiNumber = 0;
    name = "";
    System.out.println("No-argument constructor");
}

2 . Parameterized: This constructor takes at least one argument.

MobilePhone (int number, String brand) {
      imeiNumber = number;
      name = brand;
      System.out.println("Parameterized constructor");
}

3 . Copy: Constructor with exactly one parameter of the same class type. It is used to create a copy of an existing object.

MobilePhone(MobilePhone mobile) {
    imeiNumber = mobile.imeiNumber;
    name = mobile.name;
    System.out.println("Copy constructor");
}

4 . Default (provided by the compiler): If there isn’t any explicitly defined constructor, the compiler will provide a no-argument constructor known as the default constructor.

Notes: 

  • If we define a constructor inside our class, the compiler will not build the default constructor.
  • No-arg constructor and default constructor are different.

What happens to objects with the default constructor?

The default constructor assigns default values to the instance variables.

  • Object data type: Null reference
  • byte, short, int data type: 0
  • boolean: false

Constructor overloading: Multiple constructors in a single class

Just like function overloading, java supports constructor overloading. We can write multiple constructor definitions for MobilePhone class as long as each definition has a unique argument list (or signature). The compiler will call the constructor with the appropriate argument list. E.g.-

class MobilePhone {
    //data members
     
    MobilePhone(){
    //same as before
    }
    MobilePhone(int number, String brand){
    //same as before
    }
    MobilePhone(MobilePhone mobile){
    //same as before
    }
    MobilePhone(int number) {
        imeiNumber = number;
        name = "";
    }
    //...
}
//calls no-arg constructor
    MobilePhone phone = new MobilePhone();
//calls parameterized constructor
    phone = new MobilePhone(0,"IQ");

NOTE: Unique signatures mean that any two argument lists must not have the same number and types of arguments and order in which they are written.

//invalid overloaded constructor (1,2) 
//because both have same argument list

MobilePhone(String var1, int var2)  -->1
MobilePhone(Sring str1, int int2)   -->2
MobilePhone(int int1, String str2)  -->3

Here, 1 and 2 have the same signature, whereas 3 has a unique signature.

Conclusion

Constructors are an integral part of classes and hence of OOPs. They are not some special methods but are like a sub-routine invoked whenever we create an object. In addition to the default constructor provided by the compiler, we can also define constructors. A single class can be overloaded with constructors having different signatures.

More from EnjoyAlgorithms

Our weekly newsletter

Subscribe to get free weekly content on data structure and algorithms, machine learning, system design, oops design and mathematics.

Follow us on:

LinkedinMedium

© 2020 EnjoyAlgorithms Inc.

All rights reserved.