Java计算以三角形,矩形,圆形为底的柱形的体积
代码如下:
Geometry.java:
public abstract class Geometry {
public abstract double getArea();
}
Circle.java:
public class Circle extends Geometry{
double i;
Circle(double i){
this.i=i;
}
public double getArea() {
return 3.14*i*i;
}
}
Rectangle.java:
public class Rectangle extends Geometry{
double i,j;
Rectangle(double i,double j){
this.i=i;
this.j=j;
}
public double getArea() {
return i*j;
}
}
Triangle.java:
public class Triangle extends Geometry{
double i,j;
Triangle(double i,double j){
this.i=i;
this.j=j;
}
public double getArea() {
return i*j/2;
}
}
Pillar.java:
public class Pillar {
Geometry bottom;
double height;
Pillar(Geometry bottom,double height){
this.bottom=bottom;
this.height=height;
}
public double getVolume() {
if(bottom==null) {
System.out.println("没有底,无法计算体积");
return -1;
}
return bottom.getArea()*height;
}
}
text.java:
public class text {
public static void main(String[] args) {
Pillar pillar;
Geometry bottom=null;
pillar=new Pillar(bottom,100);
System.out.println(pillar.getVolume());
bottom=new Circle(3);
pillar=new Pillar(bottom,100);
System.out.println(pillar.getVolume());
bottom=new Rectangle(3,4);
pillar=new Pillar(bottom,100);
System.out.println(pillar.getVolume());
bottom=new Triangle(3,4);
pillar=new Pillar(bottom,100);
System.out.println(pillar.getVolume());
}
}
运行结果: