Constructor Overloading
In addition to overloading normal methods, you can also overload constructor
methods.
Since Box( ) requires three arguments, it’s an error to call it without them. This raises
some important questions. What if you simply wanted a box and did not care (or know)
what its initial dimensions were? Or, what if you want to be able to initialize a cube by
specifying only one value that would be used for all three dimensions?. class is currently
written, these other options are not available to you. Fortunately, the solution to these
problems is quite easy: simply overload the Box constructor so that it handles the
situations just described.
class Box
{
double width; double height; double depth;
Box(Box ob)
{
width = [Link]; height = [Link]; depth = [Link];
}
Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}
Box()
{ width = -1; height = -1; depth = -1;
}
Box(double len)
{
width = height = depth = len;
}
double volume()
{
return width * height * depth;
}
}
class OverloadCons2
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1);
double vol;
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
vol = [Link]();
[Link]("Volume of cube is " + vol);
vol = [Link]();
[Link]("Volume of clone is " + vol);
}
}