Constructor:
A constructor
is a function which would be executed only at the time of creating an object.
When the object is created the
constructor will be executed.
Example:
Class A
{
int i,j;
A
()
{
System.out.println
(“inside constructor A()”);
I=5;
J=6;
}
Void
fun ()
{
system.out.println
(“i”);
system.out.println
(“j”);
}
Public
static void main (String args[])
{
A
a=new A();
a.fun
();
}
}
Comparisons between a constructor
and a function:
·
A
normal function can be called as and when we required to call it, but we can’t
call a constructor as and when we want.
·
Constructor
would be executed only once on the object and that too, only at a time of
object creation. A function can be called on an object as many number of times
as we want.
·
Name
of the function can be any name, but name of the constructor must and should be
the name of the class.
·
A
constructor will not have any return type, where as a function should have a
return data type (at least void).
·
The
keyword static can’t be used with constructors. It is applicable to functions
and other variables.
·
We know that whenever jvm encounters the new
operator, it creates an object of that class and loads the non-static members
of the class into that object and then the address of object is assigned to a
variable.
But something other than this
happens prior to this when JVM encounters the new operator, here we can see the
function of constructors.
There are three
types of constructors
1.
Parameterized constructor
2. Copy
constructor
3. Dafault
constructor
Normally copy constructor
does not used in java.
Parameterized constructor: the constructor which have the
arguments, that in any number of arguments.
Example:
Class X
{
Int a, b;
X(int i)
{
A=I;
s.o.p(“inside
constructor”);
}
X(int i, int j)
{
a=I;
b=j;
s.o.p(“inside constructor”);
}
Public static
void main(String args[])
{
X x= new X(6);
X x = new
X(7,9);
}
}
Default constructor: the constructor which doesn’t have
the arguments is known as default constructor.
Example:
A(){}
If you don’t
declare any constructor in a program it will take default constructor. We can’t
see the constructor the compile will automatically execute that statement. In
every constructor the first statement is super.