按要求编写Java程序: (1)编写一个接口:InterfaceA,只含有一个方法int method(int n); (2)编写一个类:ClassA来实现接口InterfaceA,实现int method(int n)接口方法时,要求计算1到n的和; (3)编写另一个类:ClassB来实现接口InterfaceA,实现int method(int n)接口方法时,要求计算n的阶乘(n!); (4)编写测试类E,在测试类E的main方法中使用接口回调的形式来测试实现
时间: 2024-02-06 11:04:29 浏览: 26
下面是按照要求编写的Java程序:
```
// InterfaceA.java
public interface InterfaceA {
int method(int n);
}
// ClassA.java
public class ClassA implements InterfaceA {
public int method(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return sum;
}
}
// ClassB.java
public class ClassB implements InterfaceA {
public int method(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * method(n - 1);
}
}
// TestE.java
public class TestE {
public static void main(String[] args) {
InterfaceA a1 = new ClassA();
System.out.println("1 + 2 + ... + 10 = " + a1.method(10));
InterfaceA a2 = new ClassB();
System.out.println("5! = " + a2.method(5));
}
}
```
在测试类E的main方法中,我们先创建了一个类ClassA的实例对象a1,再创建了一个类ClassB的实例对象a2,然后使用接口回调的方式,即通过接口类型InterfaceA来调用实现类的方法。最后输出计算结果。