Constructor is a member function that takes the same name as that of the class and it is called automatically when the objects are created.
Constructor can be mainly of three types:
1. Default Constructor
2. Parameterized (overloaded) Constructor
3. Copy Constructor
Default Constructor is a constructor that takes no arguments. When an object is declared without any arguments this is called. It is best used for initialization of data members.
Parameterized (overloaded) Constructor is a constructor that takes arguments. When an object is declared with arguments this is called. If there are more than one constructor of this type, the constructors are called depending on the number of arguments supplied.
Copy Constructor is a constructor that takes the object of same class as argument. If all the properties of an object has to be assigned to another object, this is advisable.
class box
{
private int l,b,h;
box() // Default Constructor
{
l=b=h=0;
}
box(int ll, int bb, int hh) // Parameterized Constructor
{
l=ll;
b=bb;
h=hh;
}
box(box k) // Copy Constructor
{
l=k.l;
b=k.b;
h=k.h;
}
}
class Test
{
public static void main(String as[])
{
box b1,b2,b3;
b1=new box();
b2=new box(4,5,6);
b3=new box(b2);
}
}
Explanation:
In the above example, there are three constructors: constructor without arguments (default constructor), constructor with three arguments (parameterized constructor), and constructor with same type of object as argument (copy constructor).
§ For the first object “b1” the constructor without arguments is called and values of ‘l’, ‘b’, and ‘h’ will be “0”
§ For the second object “b2” the constructor with three arguments is called and values of ‘l’, ‘b’, and ‘h’ will be “4”, “5” and “6”.
§ For the third object “b3” the constructor with same type of object is called and values of ‘l’, ‘b’, and ‘h’ will be same as that of the object “b2” i.e. “4”, “5” and “6”.
0 comments:
Post a Comment