有没有一种方法可以使该接口具有另一个默认实现?

时间:2020-10-03 00:12:27

标签: java types

在此界面中,我具有默认的实现:

public interface Arithmeticable<T extends AlgebraicInteger> {
    
    T plus(T addend);
    
    T plus(int addend);
    
    default T negate() {
        return this.times(-1);
    }
    
    T minus(T subtrahend);
    
    default T minus(int subtrahend) {
        return this.plus(-subtrahend);
    }
    
    T times(T multiplicand);
    
    T times(int multiplicand);
    
    T divides(T divisor) throws NotDivisibleException;
    // may also throw a runtime exception for division by 0
    
    T divides(int divisor) throws NotDivisibleException;
    // may also throw a runtime exception for division by 0
    
}

自然,人们会认为这里还有另外一个默认实现:

    default T minus(T subtrahend) {
        return this.plus(subtrahend.negate());
    }

但是问题是编译器不知道可以在negate()上调用subtrahend。实际上,人为假设T实现Arithmeticable<T>。除了T之外的其他类也可以轻松实现它。

我们唯一可以依靠的TObjectAlgebraicInteger所定义的。有没有办法要求T实施Arithmeticable<T>

我对在Scala中做类似的事情有这种模糊的记忆。可以用Java完成吗?

0 个答案:

没有答案