Design a class to overload a function volume() as follows: (i) double volume(double r) - with radius (r) as an argument, returns the volume of a sphere using the formula V = 4/3 x 22/7 x r^3 (ii) double volume(double h, double r) - with height (h) and radius (r) as arguments, returns the volume of a cylinder using the formula V = 22/7 x r^2 x h (iii) double volume(double l, double b, double h) - with length (l), breadth (b) and height (h) as arguments, returns the volume of a cuboid using the formula V = l x b x h
Topic: Method overloading — volume of three solids
Answer
class VolumeOverload { double volume(double r) { return 4.0 / 3 * 22.0 / 7 * r * r * r; }
double volume(double h, double r) { return 22.0 / 7 * r * r * h; }
double volume(double l, double b, double h) { return l * b * h; }
public static void main(String args[]) { VolumeOverload ob = new VolumeOverload(); System.out.println("Volume of sphere = " + ob.volume(7.0)); System.out.println("Volume of cylinder = " + ob.volume(10.0, 7.0)); System.out.println("Volume of cuboid = " + ob.volume(2.0, 3.0, 4.0)); } }
Three methods named volume(), distinguished by the NUMBER of parameters — one, two and three. That alone makes valid overloading; the fact that all three take doubles does not matter.
The critical detail is writing the fractions as 4.0 / 3 and 22.0 / 7 rather than 4 / 3 and 22 / 7. With two ints, 4 / 3 is integer division and gives 1, while 22 / 7 gives 3 — the sphere volume would come out badly wrong and the compiler would never complain. Making just ONE operand a double forces the whole expression into floating point.
Note that the second method takes (h, r) in that order, not (r, h). Follow the order the question gives, because a caller passing volume(10.0, 7.0) means height 10 and radius 7 — reversing them silently produces a wrong answer.
Check with r = 7: the sphere volume is about 1437.33, and a cylinder of radius 7 and height 10 gives exactly 1540.0.
r double - radius of the sphere or cylinder h double - height of the cylinder or cuboid l, b double - length and breadth of the cuboid ob VolumeOverload - object used to invoke the methods