Reputation: 4175
How can I specify that a particular parametrized type needs to have a particular method?
What I mean is: If I have my class public class SparseMatrix<type>
, and one of my methods in the class (the add
method) needs to use the add method of its members, how can I make it require that type
has an add
method? I need my SparseMatrix to be able to work with not only numbers and strings, but with other kinds of addable things too, even other matricies.
I would also be using it in my mul
and sub
methods.
Upvotes: 0
Views: 44
Reputation: 1502546
You can't just do it based on the presence of a method - the types would have to implement a common interface or superclass. For example:
public interface Addable<T>
{
T add(T lhs, T rhs);
}
Then:
public class SparseMatrix<T extends Addable<T>>
Of course you can't make existing types (numbers, strings) implement that interface - you'd have to write your own applicable wrapper type.
Upvotes: 3