0% found this document useful (0 votes)
18 views2 pages

Constructor Overloading

Uploaded by

Thomachan Antony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views2 pages

Constructor Overloading

Uploaded by

Thomachan Antony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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 = ob.width; height = ob.height; depth = ob.depth;
}
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 = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}

You might also like