In this interface, I have default implementations:
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
}
Naturally, one would think there is one more default implementation to be had here:
default T minus(T subtrahend) {
return this.plus(subtrahend.negate());
}
But the problem is that the compiler doesn't know negate() can be called on subtrahend. In fact it's a human assumption that T implements Arithmeticable<T>. It could just as easily be implemented by a class other than T.
The only thing we can count on T to have is what Object and AlgebraicInteger define. Is there a way to require T to implement Arithmeticable<T>?
I have this vague memory of doing something like this in Scala. Can it be done in Java?