I have a interface Vector from a library that I use in my project and I cannot modify...
interface Vector<T> {
public Vector<T> plus(Vector<T> v);
}
Then I implemented it with a class FourVector
but the problem arise in overriding method plus. I want FourVector
may add only with FourVector
, not with all types of Vector! What I try to do is a thing like this (but is obviously wrong)
class FourVector<T> implements Vector<T> {
public Vector<T> plus(FourVector<T> v) {
...
}
}
There is some pattern or a workaround that permits the realization of this idea?
If you have a Vector<T>
, you will be able at compile time to pass any types of Vector<T>
to its add
method. That is how the interface is designed.
So your FourVector
is not a real Vector
in that respect:
Vector
if (!(v instanceof FourVector)) throw new UnsupportedOperationException("Only FourVector allowed here");