What is Constructor in Java?

What is Constructor in Java?

 
A constructor is a set of instruction that runs whenever a new object is created. The syntax for Constructor is:-
  1. < modifier > Class name() {}  
Modifier can be public, private, protected but commonly public is used.
 
The name of the constructor is same as the name of the class.
 
Constructor looks like a method but it is not a method, as it does not have a return type and its name can only be a class name.
 
There are 3 steps in creating an object of a class.
 
Example:-suppose there is a class with name Shape. To create an object of Shape class we write
  1. Shape one = new Shape();  
Step 1
 
We create a reference variable with name one that allocates memory for the object on the heap.
 
Step 2
 
We create an object with the new operator. Now here is an interesting thing, when we write a new operator the constructor for this class is called before the object is assigned to the reference variable. So, whatever is written in the constructor gets executed.
 
Step 3
 
Reference variable is assigned the newly created object.
 
One of the most frequent question heard is:- What is default constructor?
 
Default Constructor is the constructor that takes no argument. if you don't write the default constructor in your class, then compiler implicitly writes the default constructor for that class. Default Constructor looks like:-
  1. Public Shape() {}