§ 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 overloading is a kind of Method Overloading. This concept is useful when objects are required to perform similar tasks but using different parameters.
§ Constructor overloading is having any number of constructors provided they take different number or types of arguments.
§ Compiler has no confusion in identifying which constructor to call. The call is based on number of arguments supplied when creating the objects.
The following program has three constructers that demonstrate constructor overloading.
Example:
class box
{
private int l,b,h;
box()
{
l=b=h=0;
}
box(int x)
{
l=b=h=x;
}
box(int ll, int bb, int hh)
{
l=ll;
b=bb;
h=hh;
}
}
class Test
{
public static void main(String as[])
{
box b1,b2,b3;
b1=new box();
b2=new box(3);
b3=new box(4,5,6);
}
}
Explanation: In the above example, there are three constructors: constructor without arguments (default constructor), constructor with one argument, constructor with three arguments.
§ 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 one argument is called and values of ‘l’, ‘b’, and ‘h’ will be “3”
§ For the third object “b3” the constructor with three arguments is called and values of ‘l’, ‘b’, and ‘h’ will be “4”, “5” and “6”.
0 comments:
Post a Comment