Area 接口:
public interface Area {
//面积
//圆锥表面积公式:S=πr^2+Πrl
public abstract double area();
}
volume 接口:
public interface Volume {
//体积
//圆锥体的体积公式:V=1/3πr?h
public abstract double volume();
}
实现接口的类:
public class shixian implements Comparable<shixian> ,Area,Volume {
//成员变量
//半径
public double radius;
//高度
public double height;
//构造方法
public shixian(double radius, double height) {
this.radius = radius;
this.height = height;
}
@Override
public double area() {
return Math.PI * radius * radius + Math.PI * radius * height;
}
@Override
public double volume() {
return 1.0 / 3.0 * Math.PI * radius * radius * height;
}
@Override
public int compareTo(shixian c) {
if (this.volume() > c.volume()) {
return 1;
} else if (this.volume() < c.volume()) {
return -1;
} else {
return 0;
}
}
}
测试类:
import java.util.Scanner;
//测试类
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入半径:");
double radius = sc.nextDouble();
System.out.print("请输入高度:");
double height = sc.nextDouble();
shixian p = new shixian(radius, height);
System.out.println("面积为:" + p.area());
System.out.println("体积为:" + p.volume());
System.out.print("请输入第二个的半径和高度:");
shixian b = new shixian(sc.nextDouble(), sc.nextDouble());
if (p.compareTo(b) > 0) {
System.out.println("第一个圆锥体积大 " + "体积是 " + p.volume());
} else if (p.compareTo(b) < 0) {
System.out.println("第二个圆锥体积大 " + "体积是 " + b.volume());
} else {
System.out.println("两个圆锥体积相等 " + "体积是 " + b.volume());
}
}
}
运行结果: