interface Addable<E> {
public E add(E x);
public E sub(E y);
public E zero();
}
class SumSet<E extends Addable> implements Set<E> {
private E element;
public SumSet(E element) {
this.element = element;
}
public E getSum() {
return element.add(element.zero());
}
}
It seems that element.add() doesn’t return an E extends Addable but rather an Object. Why is that? Has it anything to do with Java not knowing at run-time what the object types really are, so it just assumes them to be Objects(thus requiring a cast)?
Thanks
It should be:
Your original code specifies that each element of SumSet must be an instance of E, a class that implements
Addable(which is equivalent toAddable<Object>). By changingAddabletoAddable<E>, you’re specifying that add, sub, and zero methods of the E class must accept and return instances of E (rather than just Object).Note that the E type variable in SumSet has nothing to do with the above E variable. So:
works fine too.