Constructor in Java || Types of Constructors (Default, No-arg, Parameterized) - In Details

Опубликовано: 17 Октябрь 2024
на канале: Learning and Teaching Coding
698
23

Constructor is a block of code that initializes the newly created object.

A constructor resembles an instance method in java but it’s not a method as it doesn’t have a return type.
In short constructor and method are different.

Constructor has same name as the class and looks like this in a java code.

Note that the constructor name matches with the class name and it doesn’t have a return type.

0:00 - Introduction
05:10 - Default Constructor
05:32 - No-arg Constructor
07:42 - Parameterized Constructor

=== How does a constructor work ===
To understand the working of constructor, lets take an example. lets say we have a class Demo.

When we create the object of Demo like this:
Demo d = new Demo()

The new keyword here creates the object of class Demo and invokes the constructor to initialize this newly created object.

-Here we have created an object d class Demo and then we displayed the instance variable name of the object.

As you can see that the output is "Learning and Teaching Coding" which is what we have passed to the name during initialization in constructor.

This shows that when we created the object d the constructor got invoked. - - In this example we have used this keyword, which refers to the current object, object d in this example.

=== Types of Constructors ===
[1] Default constructor :
If you do not implement any constructor in your class, Java compiler inserts a default constructor into your code on your behalf.

This constructor is known as default constructor.

You would not find it in your source code(the java file) as it would be inserted into the code during compilation and exists in .class file.

[2] no-arg constructor :
Constructor with no arguments is known as no-arg constructor.

The signature is same as default constructor, however body can have any code unlike default constructor where the body of the constructor is empty.

Although you may see some people claim that that default and no-arg constructor is same but in fact they are not, even if you write public Demo() { } in your class Demo it cannot be called default constructor since you have written the code of it.

[3] Parameterized constructor :
Constructor with arguments(or you can say parameters) is known as Parameterized constructor.

In this example we have a parameterized constructor with two parameters id and name. While creating the objects obj1 and obj2 I have passed two arguments so that this constructor gets invoked after creation of obj1 and obj2.

#LearningandTeachingCoding