抽象 class 方法 - 实例化子 class 对象?

Abstract class method - To instantiate child class object?

我正在尝试创建一个矩阵库(教育目的),但遇到了一个障碍,我不确定如何使用 grace。添加两个矩阵是一项简单的任务,对每个矩阵的元素分别使用 get() 方法。

但是,我使用的语法是错误的。 NetBeans 声称它期待 class,但找到了一个类型参数;对我来说,类型参数只是一个 1:1 映射到 classes.

的集合

为什么我这里错了?我以前从未见过类型参数是 class 以外的任何东西,所以下面的位不应该暗示 M 是 class 吗?

M 扩展矩阵

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);
}

我认为您的 M 没有必要。

如果 MMatrix 的子类,那么只需在您的定义中使用 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);
}

下面的代码是错误的:

 M result = new M(2, 2);

M 不是您可以实例化的 class。

基本上,你需要稍微改变一下你的数据结构,因为你的Matrix class是abstract,也不能被实例化!

我建议您将 plus 的 return 类型更改为 Matrix 并保留抽象。

您不能直接实例化类型参数M,因为您不知道它的确切类型。


我建议考虑创建以下方法

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

及其在子类中的实现。

从你的代码来看,我猜你想从 Matrix 扩展一些 child class 并对它们进行计算。

改为

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

在每个 child class 中,添加 plus 的实现。因为那里定义了childclass的构造函数