Types of Constructors in Java

When you listen to the name Constructor, then what comes to your mind? Something like making or creating or building something. A constructor is also similar, it initializes an object immediately after its creation.

You can compare constructors with the methods. They are similar while differing in some aspects. Constructors don’t have any return type, unlike the methods. Also, the Constructor name must be the same as the class name, which is not possible when declaring methods. 

Rules for Writing Constructors

  • The Constructor name should match with the name of the class in which it resides.
  • In Java, the constructors can never be abstract, synchronized, static, and final.
  • It should not have any return type and value.
  • Constructors can have access modifiers to restrict their usage and for maintaining security.

Note: Even though you don’t use any constructor, JVM will construct a default constructor for your program during the time of compilation. 

Types of Constructors in Java

Types of Constructors in Java

In general, there are three types of constructors:

  1. Default Constructor
  2. No-Argument Constructor
  3. Parameterized Constructor

Let’s understand each one of them in brief.

Default Constructor

If a programmer does not or forget to implement the constructor inside the class, the Java compiler creates a default constructor in your code. Even though you will not see it in your source code, but during the compilation, it will be there. The body remains empty for the default constructor.

A default constructor looks like this:

No-Argument Constructor

As the name suggests, the constructors with no arguments are called no-argument constructors. The signature matched with the default constructor, but unlike default constructors, the body can contain code. 

Example:

Parameterized Constructor

Constructors with parameters or arguments fall under the category of the parameterized constructor. You can pass multiple arguments. If you want to initialize the class fields with default values, then use a parameterized constructor.

Example:

Note: programmers can make many parameters with the same name but different parameters.

Leave a Comment

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