0% found this document useful (0 votes)
28 views1 page

Documentb

The document discusses improving a volume() method in a Box class to return the calculated volume rather than just displaying it. The improved volume() method returns the width * height * depth of the box, allowing the calling code to store the volume in a variable or use it elsewhere rather than just printing it. This allows other parts of the program to know the volume of a box without having to display it. The example code shows defining Box and BoxDemo classes, creating two Box objects, calling volume() on each to calculate and return the volume, and printing out the volumes.

Uploaded by

Shaista Saeed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views1 page

Documentb

The document discusses improving a volume() method in a Box class to return the calculated volume rather than just displaying it. The improved volume() method returns the width * height * depth of the box, allowing the calling code to store the volume in a variable or use it elsewhere rather than just printing it. This allows other parts of the program to know the volume of a box without having to display it. The example code shows defining Box and BoxDemo classes, creating two Box objects, calling volume() on each to calculate and return the volume, and printing out the volumes.

Uploaded by

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

Returning a Value

While the implementation of volume( ) does move the computation of a box’s volume
inside the Box best way to do it.
For example, what if
another part of your program wanted to know the volume of a box, but not display its
value? A better way to implement volume( ) is to have it compute the volume of the box
and return the result to the caller. The following example, an improved version of the
preceding program, does just that:
// Now, volume() returns the volume of a box.
class Box {
double width;
double height;
double depth;
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 2 to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

You might also like