Skip to main content
JAVA PROGRAM TO OVERLOADING CONSTRUCTOR WORK
//program to overloading constructor ----how overloading constructor actually work
PROGRAM CODE-----
class Box
{
double width;
double height;
double depth;
Box() //constructor when no dimensions specified
{
width=1;
height=1;
depth=1;
}
Box(double x) // constructor used when one dimensions specified like a cube
{
width=height=depth=x;
}
Box(double w , double h, double d ) // constructor used when three dimensions specified
{
width=w;
height=h;
depth=d;
}
Box(Box b) // pass object to constructor
{
width=b.width;
height=b.height;
depth=b.depth;
}
double volume() //calculate volume of box
{
return width*height*depth;
}
}
class CallBox
{
public static void main(String ar[])
{
Box mybox1=new Box(); //no parameter
Box mybox2=new Box(4.0); //one parameter
Box mybox3=new Box(1.2,2.2,5.1);
Box mybox4 = new Box(mybox2); // pass copy of one parameter object
double vol;
vol=mybox1.volume();
System.out.println("Volume of first box is"+vol);
vol=mybox2.volume();
System.out.println("Volume of second box is"+vol);
vol=mybox3.volume();
System.out.println("Volume of third box is"+vol);
vol=mybox4.volume();
System.out.println("Volume of fourth box is"+vol);
}
}
OUTPUT OF ABOVE PROGRAM---
Comments
Post a Comment