JAVA - Constructor

Constructor in Java : Beginner's Guide

In Java, One of the important concepts is Constructor, which plays a crucial role in object-oriented programming. In this blog post, let's take look on constructor in Java, their syntax, and how they can be used.

So What are Constructor in Java?

Constructor is a specialized setter that is used to initialize an Object of an class. Constructor will be called immediately when we create the Objects. Constructor says that you supply the data to me, and then I will create Objects for you.

Rules for defining a Constructor

1. Constructor name must be the same as the ClassName.

2. Constructor will never return anything explicitly.

3. Constructors can be overloaded.

4. Access specifiers we can use public, private, protected or default types based on our requirements.

Please refer to the below example

In this example, I have defined a class called University with 3 Constructors, one is a default constructor and the rest 2 of them are parameterized.

Creating an Object using a Constructor

In this example, I have created 3 different objects for 3 different constructors. Constructor will be called immediately at the time of Object creation and assigns the respective values to the respective fields.

Final Output

Types of Constructors

Default constructors: These constructors do not take any arguments and are automatically created by the compiler if no other constructors are defined.

Parameterized constructors: These constructors take one or more arguments and are used to initialize the fields of the object with specific values.

In summary, Constructors are fundamental concept in Java that plays an important role in Object Oriented programming. Constructors will construct the Objects according to our requirements.

"Thanks for reading! I hope you found this post informative and helpful."