I want to make a two-dimensional vector that is holding two numeric values. As usual vectors (even of different numerical type) should e.g. be addable. In C++ you can just do something like:
template<typename T>
class vector2d{
T x{0};
T y{0};
public:
template<typename U> vector2d& operator+=(const vector2d<U>& vec){
x += vec.x;
y += vec.y;
return *this;
}
...
template<typename U>
friend class vector2d;
};
But when I try to achieve this in Java I am coming across some problems. Here is what I tried to do:
class vector2d<T extends Number>{
private T x;
private T y;
public <U extends Number> vector2d add(vector2d<U> vec){
x += vec.x;
y += vec.y;
return this;
}
...
}
But this does not work. It would if i would use Integer or Float or whatever directly (because of Autoboxing). But this seems not to be the case when you just use the Number class directly. As I think there is no other interface that would satisfy the requirements, I am kind of stuck here. So my question is if there are ways to make this work in Java.