interface Computable <T> { T add(T obj); T substract(T obj); T multiply(T obj); T divide(T obj); }
时间: 2024-03-28 12:38:44 浏览: 13
这是一个泛型接口 `Computable<T>`,其中定义了四个方法 `add`、`subtract`、`multiply`、`divide`,分别用于对两个泛型对象进行加、减、乘、除运算,并返回运算结果。这个接口可以被其他类实现,实现类需要提供具体的泛型类型,并实现接口中的四个方法。这样,我们就可以在不同的场景下使用该实现类来进行加减乘除运算。
相关问题
接口Computable的使用方法
接口`Computable`是一个泛型接口,它有一个泛型类型参数`A`表示输入类型,有一个泛型类型参数`V`表示输出类型。该接口有一个`compute`方法,用于接收输入参数并返回输出值。
以下是一个示例代码:
```java
public interface Computable<A, V> {
V compute(A arg) throws InterruptedException;
}
```
该接口表示一个计算器,接收一个输入参数`arg`,返回一个结果值`V`。具体的计算逻辑由实现该接口的类来实现。
以下是一个实现了`Computable`接口的类的示例代码:
```java
public class ExpensiveFunction implements Computable<String, BigInteger> {
public BigInteger compute(String arg) throws InterruptedException {
// 计算逻辑
return new BigInteger(arg);
}
}
```
该类实现了`Computable`接口,接收一个字符串类型的参数并返回一个`BigInteger`类型的结果值。
以下是一个使用`Computable`接口的示例代码:
```java
public class Memoizer<A, V> implements Computable<A, V> {
private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();
private final Computable<A, V> c;
public Memoizer(Computable<A, V> c) {
this.c = c;
}
public V compute(final A arg) throws InterruptedException {
Future<V> f = cache.get(arg);
if (f == null) {
Callable<V> eval = new Callable<V>() {
public V call() throws InterruptedException {
return c.compute(arg);
}
};
FutureTask<V> ft = new FutureTask<>(eval);
f = ft;
cache.put(arg, ft);
ft.run();
}
try {
return f.get();
} catch (ExecutionException e) {
throw new RuntimeException(e.getCause());
}
}
}
```
该类实现了一个缓存功能,用于缓存计算结果,避免重复计算。在构造函数中传入一个实现了`Computable`接口的类,调用`compute`方法时,首先从缓存中查找结果,如果缓存中不存在,则调用传入的`Computable`实例的`compute`方法进行计算,并将结果缓存起来,然后再返回计算结果。如果缓存中已经存在结果,则直接返回缓存中的结果。
这就是`Computable`接口的使用方法,通过实现该接口,可以实现各种不同的计算逻辑,并且可以通过缓存优化计算性能。
error: divide() in Complex cannot implement divide() in Computable void divide(){ ^ attempting to assign weaker access privileges; was public
这个错误是因为在类 `Complex` 中定义的 `divide()` 函数的访问修饰符是 `public`,而在类 `Computable` 中定义的 `divide()` 函数的访问修饰符是更弱的 `protected` 或 `private`。因为在派生类中,重载的成员函数的访问权限不能比基类中更宽松。所以你需要将类 `Complex` 中的 `divide()` 函数的访问修饰符改为 `protected` 或 `private`,以匹配类 `Computable` 中的访问修饰符。