题目:
有三个立方体,球体,长方体,圆柱体,用接口实现计算每个立方体的体积并输出结果的程序
1.首先是测试类
//package com.Lsheng.java;
import java.util.Scanner;
public class c5_18 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //这是为了体验从控制台输入
double n = sc.nextDouble();
c5_18 c = new c5_18();
Sphere sphere = new Sphere(n); //这是正常的直接调用
System.out.println("球的体积="+ sphere.volume());
Cuboid cuboid = new Cuboid(15.0,9.0,8.0);//这是体现一下多态的使用,接口也是引用数据类型
System.out.println("立方体体积" + c.getVolume(cuboid));
//Cylinder cylinder = new Cylinder(7.0,8.0);
//这里是体验一下匿名方法的使用,也是多态的使用
System.out.println("圆柱体体积"+c.getVolume(new Cylinder(7.0,8.0)));
}
public double getVolume(Solid solid) {
return solid.volume();
}
//也可以直接一点,比较方便, 静态方法
//public static double getVolume(Solid solid)
// return solid.volume();
}
2.用到的接口 ,每个需求面积都需要用到的方法
//package com.Lsheng.java;
/*
* 有三个立方体,球体,长方体,圆柱体,用接口实现计算每个立方体的体积并输出结果的程序
*/
interface Solid{//立方体
public static final double PI = 3.14159;
public abstract double volume();
}
//定义球体类
class Sphere implements Solid{
private double radius;
public Sphere(double r) {
this.radius = r;
}
public double volume() {//重写求体积的方法
return 4.0/3.0 * PI * Math.pow(radius, 3);
}
}
3.以及需求面积的类
//package com.Lsheng.java;
public class Cuboid implements Solid{
private double length, width, height;
public Cuboid(double l, double w, double h) {
this.length = l; this.width = w; this.height = h;
}
public double volume() {
return length*width*height;
}
}
package com.Lsheng.java;
public class Cylinder implements Solid{
private double radius, height;
public Cylinder(double r, double h) {
this.radius = r; this.height = h;
}
public double volume() {
return PI * radius *radius*height;
}
}
输出结果
有疑问留言,谢谢