Constructor:
-
It
is a specialized method od a class which
is invoked when an object is created for the class.
-
The
difference occurs in the following areas:
o Name
o Return
Type
o Type
of Calling
o Time
of Calling
o Frequency
of Calling
o Purpose
Name:
Constructor Name and Class Name should be same.
Ex:
Return Type:
Constructor name shouldn't have any return type.
Type of Calling:
Constructor is called as soon as object is created.
It is the first method called by the Object.
Time of Calling:
A Constructor is Called Implicitly.
Frequency of Calling:
A constructor will be called
when the object of the respective class is created and also when the objects of
the derived class are created.
Purpose:
The Main purpose of the
constructor is, It carries the code which need to executed as soon as object is
created.
There
are 2 types of constructors:
a) Parameterized
constructor.
b) Un-parameterized
constructor/ Zero argument constructor/ Default/ Block
Ex:
-
In
this case, by default Jcompiler calls EMP() i.e default constructor. If you
want to call the parameterized constructor first, pass parameters while Object
declaration.
-
One
constructor of a class can call another constructor of the same class. This is
called constructor chaining.
No comments:
Post a Comment