Constructors in Java

In this post, we will learn about Constructors in Java.

Constructors in Java are special member functions whose task is to initialize the objects of its class. It is treated as a special member function because its name is the same as the class name. A constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type. The constructor is automatically called immediately after the object is created.

A Constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type. The constructor is automatically called immediately after the object is created. Every class has a constructor. When we don’t declare a constructor for any java class, the compiler creates a default constructor for that class which doesn’t have any return type.

Types of Java Constructors:

There are two types of constructors. These are

Default constructor (no-arg constructor):

A constructor having no parameter is known as default constructor or no-arg constructor.
The structure of a default constructor is:

Parameterized constructor: 

A constructor having an argument list is known as a parameterized constructor. Parameterized constructors are used to supply dissimilar values to the distinct objects.
The structure of a parameterized constructor in Java is:

Example of Default Constructor:

In the above program, we haven’t created any default constructor. The jvm has provided the default constructor.

Example of Parameterized Constructor:

In the above program, we have created two parameterized constructors and passed the values.

Other Tutorials:

Related posts

Leave a Comment