I'm trying to create a matrix library (educational purpose) and have reached an obstacle I'm not sure how to approach with grace. Adding two matrices is a simple task, using a method get() on each each matrices' elements individually.
However, the syntax I've used is wrong. NetBeans claims it's expecting a class, but found a type parameter; to me, a type parameter is just a set with 1:1 mapping to the set of classes.
Why am I wrong here? I've never seen a type parameter be anything else than a class before, so shouldn't the following bit imply M to be a class?
M extends Matrix
public abstract class Matrix<T extends Number, M extends Matrix>
{
private int rows, cols;
public Matrix(int rows, int cols)
{
this.rows = rows;
this.cols = cols;
}
public M plus(Matrix other)
{
// Do some maths using get() on implicit and explicit arguments.
// Store result in a new matrix of the same type as the implicit argument,
// using set() on a new matrix.
M result = new M(2, 2); /* Example */
}
public abstract T get(int row, int col);
public abstract void set(int row, int col, T val);
}
You cannot instantiate a type parameter M
directly because you don't know its exact type.
I suggest thinking about creating the following method
public abstract <M extends Matrix> M plus(M other);
and its implementation in the subclass.