This was a hard problem to try and search for as I've seen no other specific issues like this, so I apologize if there turns out to be a duplicate thread I haven't found. This is a programming problem that is not related to homework in a class, that I am having issues implementing exactly according to spec.
If I want to create a
Function<T>
generic abstract class, whose only abstract method is
Apply<T>(T input1, input2)
and then extend into other derived function classes like an AddTwoNumbers class, to which Apply would return the sum of those input1 and input2 of type T (in practice this should be Integer or Double), how can I implement this?
I run into a problem when I first have
public abstract class Function<T1 extends Number> {
public abstract T1 apply(T1 input1, T1 input2);
}
public class AddTwoNumbers<T1 extends Number> extends Function<T1> {
public T1 apply(T1 input1, T1 input2) {
return input1.intValue() + input2.intValue(); //Error, needs to return type T1, not int or even Integer()
}
}
It is required that Function be generic that allows types, but inpractice it can be expected that AddTwoNumbers will be using Integers exclusively for the sake of this problem. Is there a way I can write the apply() method in AddTwoNumbers, such that
- AddTwoNumbers implements the abstract methods inherited from Function exactly
- Somehow add the two T1 values and return a T1 value properly?
The fact that I can't safely cast a T1 to an Integer, and also retain the overriding of Apply is the troublesome part.
This is generalization of the issue I was looking into.