What is Constructor in Java?
Constructor is a set of
instruction that runs whenever a new object is created. The syntax for
Constructor is :-
<modifier> Class name ()
{
}
Modifier can be public,
private, protected but commonly public is used.
The name of 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 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
Shape one= new Shape ();
Step 1
We create a reference
variable with name one that allocates memory for the object on heap.
Step 2
We create an object with new
operator. Now here is an interesting thing, when we write new operator the
constructor for this class is called, before the object is assigned to reference
variable. So, whatever is written in 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 default constructor in
your class , then compiler implicitly write the default constructor for that
class. Default Constructor looks like:-
Public Shape()
{
}