Constructors are basically the mould to objects. They give the object its shape and meaning. They are particularly useful for initializing the object with default values.

Hi Comrades,

Let’s begin this read by understanding on what are constructors and what is it that makes it different from any other method in Java. A constructor in Java is similar to a method which gets invoked when an object of a class is created. In other words, we can say a constructor is a special method that is called when an object is instantiated, i.e. when we use ‘newkeyword. The purpose of a constructor is to initialise the newly created object before it can be used. But unlike Java methods, constructors are denoted as a special method which has no return type and the constructor name should always match to that of the class name.

Eg: Class human{                     //class
human(){ //constructor
// constructor body
}
}

The constructor is typically used to assign values to the class variables at the time of object creation either explicitly(no-arg /parameterised constructors) or implicitly(default constructors). Each time an object is created using the new() keyword, a constructor is invoked to assign the initial values to the data members of the same class. Explaining the same in a layman’s terminology, consider of a class “humanBeing”, here birth of a new born is eqivalent to initializing of an object of the class in Java. We as a human being have our names for sure, so the naming ceremony is the functionality inside the constructor which is done at the time of initilaization(when a baby is born).

Now you must be wondering why is that we don’t have any return type for a constructor? Understanding on what actually happens in here is that, runtime uses the datatypes generated by the compiler to analyse how much of space will be needed to store the object instance in the memory [memory being heap or stack]. Once the space allocation is done, the constructor gets called as an internal part of instantiation and initialisation process. Now when the constructor exists, the runtime returns the newly created instance of the object. So as we understood here, the constructor is called at the time of memory allocation and object initialization and not directly by our code. Hence its return value is opaque to the user and therefore a user cannot specify the return type of it.

Types of Constructors:

Constructors are broadly classified as No-Arg Constructors, Parameterized Constructors and Default Constructors. As mentioned earlier, constructors are like methods, hence may or may not have parameters in their definitions. If any constructor doesnt accept an argument(parameter), it is said to be no-arg [No-argument] constructor. Java constructors accepting one or more parameters are termed as Parameterized constructors and the constructor that is automatically created during the execution of program is termed as Default constructor.

Note: A constructor cannot be abstract or static or final or synchronised. It can be overloaded but not overridden. Access modifiers are used to control the declaration of the constructors i.e. allowing which other classes to call the constructor.

Eg: creating a private constructor

Creating a private constructor disables us to create the object of “class A” outside of the class. Hence we created a static method “methodA()” inside class A which helps us create the object of “class A”.

Why private constructors? The Java Singleton Design Pattern ensures that there should be only one instance of a class, to achieve this we use private constructors.

Contructors Overloading:

Why we need constructor overloading? We need it to initialize the object in different ways as per the requirement for which we use Java constructor overloading. If we do not specify anything about a thread, then we can use the default but if do want to specify then we use this syntax. Constructor overloading allows us to create two or more constructors with different parameters.

Eg: Constructor overloading 

Here based on how we have passed the parameters the respective constructors are being called.With the constructor overloading, every constructor can perform a different task.

Constructor chaining:

It is the linking of multiple constructors. Calling off one constructor from another constructor can be achieved in two ways: calling it within the same class[can be achieved by using “this” keyword] or calling it from the base class[can be achieved by using “super” keyword].The constructor chaining concept is used when we have multiple tasks to be performed in a single constructor, here rather than creating set of code for each task, we create separate constructor for each task and make a chain call to these constructor making the code more readable. Two major points to keep a note on, while creating a constructor chaining in same class is that firstly; this() should always be the first line of the constructor and secondly; atleast one constructor in the constructor chaining has to be without the this() keyword. Similar to the constructor chaining happening in the same class, super() should be the first line in the constructor and super class’s constructor is to be invoked before the sub class’s constructors.

class MyConstructor{
MyConstructor(){
this(5);
System.out.println("The Default constructor");
}

Note: As an alternative to these, we can also make use of init blocks() here. Having said that, when we want a certain common resources to be executed with every constructor we can put it in the init block; as init block is always executed before the constructors. Initializer blocks always gets exceuted whenever an instance is created. It is used to declare or say initialize the common parts of various constructor of a class.

Throwing of exceptions from a constructor:

We can also throw an exception from the constructor block, this can be used if a user wants to prevent an object creation in any invalid state. i.e. if the constructor detects an invalid input parameter, it can throw an exception and thereby prevent the assignment of the object to any variables.

Note: We cannot invoke a constructor without creating an object.The onky way we could have invoked it, if constructor as static, but in Java constructors cannot be static. Hence you have to create an object to invoke the constructor.

Some important points to know : You cannot explicitly inherit a constructor. The compiler would not insert a default constructor in the child class if the superclass doesn’t have a default constructor. this() allows you to chain constructors together. The main difference between methods and constructors is that methods can return values and have a different name; But constructors have the same name as the class itself and can only return references and they cannot return values. Also, there are no constructors in interfaces.One cannot instantiate abstract classes. But they do have constructors. These constructors will be invoked when the class which implements the abstract class gets instantiated.

Hope i was fair enough in this article clearing the concept of Constructors in Java.

Until next time…

Peace Out!

Rupam Pawan Jha

Software Development Engineer | Java | Object Oriented Programming | Multi threading | Data Structures and Algorithms | Design Patterns

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store