Skip to content
APPCITORThe Tech Blog
Esc

Java OOP – Constructor

August 7, 2020 1 min read

Java OOP – Constructor

A constructor is a block of code that initializes newly created object. This is not a method because this doesn’t have a return type. But before you learn about constructors, make sure that you know about the methods. You can visit the articles of the Java Basics (Java Methods) tutorial.

When we create a constructor, usually class name and the constructor name should be same.

Let’s take examples to understand the working of different kinds of constructors.

Default Constructor

Default constructor means a constructor that doesn’t have any parameter. If you do not implement any constructor inside the class, java compiler inserts a default constructor into your code on your behalf. You would not find the default constructor in your source code because it would be inserted by the compiler during the compilation and exists in the .class file. Let’s see an example.

No-arg Constructor

No-arg constructor is a constructor with no arguments. This is same as the default constructor but can have any code inside the body of no-arg constructor unlike the default constructor. Let’s see an example.

Parameterized constructor

Parameterized constructor is a constructor with arguments(parameters). Let’s see an example.

Constructor Overloading:

Constructor overloading is a concept of having more than one constructor with different parameters list, in such a way so that each constructor performs a different task. You can see three overloaded constructors in the example given below.

Hope you guys understood the lesson about Constructors. Let’s meet with the next article on the topic “static variables and methods”.

Thank you.

Share this article

Keep reading