Java Constructor3 min read

What is Constructor?

A constructor is a block of codes just like a method in Java. It is a special type of method that is called when an instance of the class is created and is used for the initialization of a newly created object.

There are some rules for Java constructor:

  • The constructor name must be the same as its class name.
  • It should not have any return type not even void.

Note: Default Constructor is used if the user does not define a constructor then the java compiler creates a default constructor and initializes the member variables to its default values. That is numeric data types are set to 0, char data types are set to null character.

There are two types Java Constructor:

  • Default constructor(no-argument constructor)
  • Parameterized constructor.

Default constructor(no-argument constructor):

This constructor does not have any parameter and hence called a no-argument constructor.

Syntax of default constructor in Java:

Basic Example: Program to create and call a default constructor in Java:

Output of Default constructor:

Basic Example  for displaying the default values in Java:


Java Parameterized Constructor:

A Parameterized Constructor is a constructor having a specific number of parameters. The parameter is added to a constructor as they are added to the methods that are inside the parentheses of the constructor.
The data-type must match with values that are passed and in that particular order and number.

Example of Parameterized Constructor in Java:


Constructor Overloading in Java:

Constructor Overloading is like a method overloading in Java. This is a technique in Java where a single class has more than one Constructor and each of them has a different parameter.
The number of parameters and its data-types differs each constructor by the compiler.

Example of Constructor Overloading in Java :


Inner Class.
OOP in java.