Computer Science, asked by Ashvi16, 1 year ago

write a class with the name 'volume' using function overloading which can compute the volume of a cube a sphere and a cuboid
(in java)

Answers

Answered by ritikaraj967
84
class volume
{
public void vol(int side)
{
int area=side*side*side;
System.out.println("area of the cube="+area);
}
public void vol(int l,int b,int h)
{
int are=l*b*h;
System.out.println("area of the cuboid ="+are);
}
public void vol(double r)
{
double sp=4.0/3*3.14*r*r*r;
System.out.println("area of the sphere="+sp);
}
public static void main()
{
volume ob = new volume();
ob.vol(4);
ob.vol(2,4,3);
ob.vol(2.0);
}
}
Answered by QGP
59
import java.util.*;
public class Volume
{
        static void vol(int cl)
    {
        double v = cl*cl*cl;
        System.out.println("Volume of the cube is: "+v);
    }
    static void vol(float r)
    {
        double v = (4*22*r*r*r)/(3*7);
        System.out.println("Volume of the sphere is: "+v);
    }
    static void vol(int l, int b, int h)
    {
        double v = l*b*h;
        System.out.println("Volume of the cuboid is: "+v);
    }
        public static void main(String[] args)
    {
        int ch,l,b,h;
        float r;
        Scanner in = new Scanner(System.in);
                System.out.println("1) Volume of Cube");
        System.out.println("2) Volume of Sphere");
        System.out.println("3) Volume of Cuboid");
        System.out.print("Enter your choice: ");
        ch = in.nextInt();
                switch(ch)
        {
            case 1:
            System.out.print("Enter the length: ");
            l = in.nextInt();
            vol(l);
            break;
           
            case 2:
            System.out.print("Enter the radius: ");
            r = in.nextFloat();
            vol(r);
            break;
               
            case 3:
            System.out.print("Enter the length, breadth and height: ");
            l = in.nextInt();
            b = in.nextInt();
            h = in.nextInt();
            vol(l,b,h);
            break;
     
            default:
            System.out.println("Invalid choice.");
            break;
        }
    }
}        

Ashvi16: can u explain...the previous answer to this ques is quite short...why this one is so lengthy
QGP: I have written a complete working program. Plus, as you didn't mention how to take input, I thought to make it menu-driven. This makes it lengthier
QGP: The previous answer is parallel to the function vol() in my answer
QGP: However, in the previous answer, the main function gives values by itself. It doesn't ask you for input
QGP: My program asks for input. That makes it lengthier
Ashvi16: thnkewh
Similar questions