Create an abstract class Shape with methods calc_area and calc_volume. Derive three classes
Sphere(radius) , Cone(radius, height) and Cylinder(radius, height), Box(length, breadth, height)
from it. Calculate area and volume of all. (Use Method overriding).
Shape.java
import java.util.*;
abstract class Shape1
{
abstract public double cal_area();
abstract public double cal_volume();
}
class Cylinder extends Shape1
{
double r,h;
Cylinder(double r,double h)
{
this.r=r;
this.h=h;
}
public double cal_volume()
{
double v;
v=3.142*r*r*h;
return v;
}
public double cal_area()
{
double a;
a=2*3.142*r*(r+h);
return a;
}
}
class Cone extends Shape1
{
double r,h;
Cone(double r,double h)
{
this.r=r;
this.h=h;
}
public double cal_volume()
{
double v;
v=(3.142*r*r*h)/3;
return v;
}
public double cal_area()
{
double a,x;
x=(h*h)+(r*r);
a=3.142*r*(r+Math.sqrt(x));
return a;
}
}
class Sphere extends Shape1
{
double r;
Sphere(double r)
{
this.r=r;
}
public double cal_volume()
{
double v;
v=(4/3)*3.142*r*r*r;
return v;
}
public double cal_area()
{
double a;
a=4*3.142*r*r;
return a;
}
}
/*class Box extends Shape1
{
double l,b,h;
Box(double l,double b,double h)
{
this.l=l;
this.b=b;
this.h=h;
}
public double cal_volume()
{
double v;
v=r*h*z;
return v;
}
public double cal_area()
{
double a,x1,y1,z1;
x1=z*h;
y1=h*r;
z1=r*z;
a=(2*x1)+(2*y1)+(2*z1);
return a;
}
}*/
class Shape
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter radius");
double r1=sc.nextDouble();
System.out.println("enter height");
double h1=sc.nextDouble();
System.out.println("enter breadth");
double w1=sc.nextDouble();
Shape1 s1;
s1=new Cylinder(r1,h1);
System.out.println("area of cylinder =" +s1.cal_area());
System.out.println("VOLUME OF CYLINDER=" +s1.cal_volume());
s1=new Cone(r1,h1);
System.out.println("area of cone ="+s1.cal_area());
System.out.println("volume of cone ="+s1.cal_volume());
s1=new Sphere(r1);
System.out.println("area of sphere ="+s1.cal_area());
System.out.println("volume of sphere ="+s1.cal_volume());
}
}
0 Comments
If anyone has Doubts or suggestions please let me know