Abstract class method. To instantiate an object of a child class?

I am trying to create a matrix library (educational goal) and have reached a barrier. I'm not sure how to approach with grace. Adding two matrices is a simple task using the get () method for each element of each matrix.

However, the syntax I used is incorrect. NetBeans claims to be expecting a class, but has detected a type parameter; for me, a type parameter is just a set with a 1: 1 mapping to a set of classes.

Why am I wrong here? I have never seen a type parameter be anything other than a class before, so should the next bit not imply that M is a class?

M expands the 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);
}
+4
4

M , .


public abstract <M extends Matrix> M plus(M other); 

.

+2

, , - Matrix .

public abstract class Matrix<T extends number> {
  ...
  public abstract Matrix plus(Matrix other);
  ...
}

. , .

+2

, M .

M Matrix, Matrix .

public abstract class Matrix<T extends Number>
{
    private int rows, cols;
    public Matrix(int rows, int cols)
    {
        this.rows = rows;
        this.cols = cols;
    }

    public Matrix<T> plus(Matrix<T> other)
    {
    }

    public abstract T get(int row, int col);
    public abstract void set(int row, int col, T val);
}
0

:

 M result = new M(2, 2);

M , .

Basically, you need to slightly modify the data structure, because your Matrixclass abstractcannot be created either!

I suggest you change the return type plusto Matrixand leave it abstract.

0
source

All Articles