Java 接口回调:实现形状面积计算
根据题目要求,我们需要创建一个直角三角形类(RTriangle)和一个圆形类(Circle),这两个类都需要实现IShape接口中的getArea()方法。然后创建一个Machine类的对象,使用其checkArea()方法来测试不同形状的面积并输出结果。
首先,我们需要创建IShape接口:
interface IShape {
double getArea();
}
然后创建RTriangle类和Circle类,实现IShape接口:
class RTriangle implements IShape {
private double base;
private double height;
public RTriangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getArea() {
return 0.5 * base * height;
}
}
class Circle implements IShape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
接下来,创建Machine类并实现checkArea()方法:
class Machine {
public void checkArea(IShape shape) {
double area = shape.getArea();
System.out.println('The area of the shape is: ' + area);
}
}
最后,在ShapeTest类中进行测试:
public class ShapeTest {
public static void main(String[] args) {
IShape shape1 = new Circle(3.2);
IShape shape2 = new RTriangle(3.0, 4.0);
Machine machine = new Machine();
machine.checkArea(shape1);
machine.checkArea(shape2);
}
}
运行上述代码,将会输出以下结果:
The area of the shape is: 32.169908772759484
The area of the shape is: 6.0
这样就完成了接口回调的需求,通过接口IShape实现了多态性,使得我们可以通过Machine的checkArea()方法测试不同形状的面积并输出结果。
原文地址: https://www.cveoy.top/t/topic/bZh6 著作权归作者所有。请勿转载和采集!