Java编写一个接口程序,其中定义一个计算机体积的方法,然后再设计应用程序实现这个接口,分别计算矩形柱面体积和圆形柱面体积
public class Demo1 {
public static void main(String[] args) {
double volume = volume(5, 2, 3);
System.out.println("体积:" + volume);
double volume1 = volume(5, 2);
System.out.println("体积:" + volume1);
}
/**
* 计算矩形柱体体积
* @param length 长
* @param wide 宽
* @param high 高
* @return
*/
public static double volume(double length,double wide,double high) {
return length * wide * high;
}
/**
* 计算圆柱体体积
* @param length
* @param radius
* @return
*/
public static double volume(double length,double radius) {
return length * radius * radius * 3.14;
}
}
定义一个Shape接口,并且定义计算体积的方法
知道计算矩形柱面体积和圆形柱面体积的公式就可以了。
public interface TreeDim {
double volume();
class Cube implements TreeDim {
private final double height;
private final double width;
private final double length;
public Cube(double height, double width, double length) {
this.height = height;
this.width = width;
this.length = length;
}
@Override
public double volume() {
return height * width * length;
}
public double getHeight() {
return height;
}
public double getWidth() {
return width;
}
public double getLength() {
return length;
}
}
class Cylinder implements TreeDim {
private static final double PI = 3.14;
private final double radius;
private final double length;
public Cylinder(double radius, double length) {
this.radius = radius;
this.length = length;
}
@Override
public double volume() {
return PI * radius * radius * length;
}
public double getRadius() {
return radius;
}
public double getLength() {
return length;
}
}
public static void main(String[] args) {
TreeDim cube = new Cube(3,4,5);
System.out.println(cube.volume());
TreeDim cylinder = new Cylinder(6,7);
System.out.println(cylinder.volume());
}
}