- 1
Write a program
create a abstract class shape with method calculate area and volume .derive 3 classes Sphere(radius),cone(radius,height) and cylinder(radius,height),Box(lengthy,breadth,height) from it .calculate area and volume of all .(use method overriding).
1 Resposta
0
import java.util.*;
import java.math.*;
abstract class shape{
protected double area,vol,rad,height,length,breadth;
abstract void area();
abstract void volume();
public void show()
{
System.out.println("area= "+area+" volume= "+vol);
}
}
class cone extends shape{
cone(double r,double h)
{
rad=r;
height=h;
}
@Override
void area() {
area=Math.PI*rad*(rad+Math.sqrt((height*height+rad*rad)));
}
@Override
void volume() {
vol=Math.PI*rad*rad*(height/3);
}
}
class sphere extends shape{
sphere(double r)
{
rad=r;
}
@Override
void area() {
area=4*Math.PI*rad*rad;
}
@Override
void volume() {
vol=(4/3)*Math.PI*rad*rad*rad;
}
}
class box extends shape{
box(double l,double b,double h)
{
height=h;
length=l;
breadth=b;
}
@Override
void area() {
area=2*length*height+2*height*breadth+2*length*breadth;
}
@Override
void volume() {
vol=length*height*breadth;
}
}
class cylinder extends shape{
public cylinder(double r,double h) {
rad=r;
height=h;
}
@Override
void area() {
area=2*Math.PI*rad*height+2*Math.PI*rad*rad;
}
@Override
void volume() {
vol=Math.PI*rad*rad*height;
}
}
public class solo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter radius of sphere");
sphere s=new sphere(sc.nextDouble());
System.out.println("enter radius and height of cone");
cone c=new cone(sc.nextDouble(), sc.nextDouble());
System.out.println("enter radius and height of cylinder");
cylinder cy=new cylinder(sc.nextDouble(),sc.nextDouble());
System.out.println("enter length breadth height of box");
box b=new box(sc.nextDouble(), sc.nextDouble(), sc.nextDouble());
s.area();
s.volume();
System.out.println("sphere");
s.show();
c.area();
c.volume();
System.out.println("cone");
c.show();
cy.area();
cy.volume();
System.out.println("cylinder");
cy.show();
b.area();
b.volume(