【发布时间】:2021-05-14 22:13:55
【问题描述】:
编辑:这个问题措辞不好,提供的答案在字面上是正确的,但没有教我如何获得我需要的东西。如果您正在为同样的问题而苦苦挣扎,这就是最终帮助我的方法:How to enforce child class behavior/methods when the return types of these methods depends on the child class?
我正在尝试从我编写的样板抽象类中实现一个基本矩阵类。这个抽象类将有几个实现,每个都使用不同的数学库,然后我将测试它的速度。
每个实现都将其数据保存在该库的本机矩阵数据结构中。我认为这是泛型的一个用例。在这一点上,我认为我已经阅读了太多教程并观看了太多视频,因为我似乎无法找出所有正确的位置来放置 T 符号以使其正常工作。
所以我的问题是双重的:
- 我是否误用或错过了泛型的要点?
- 如果不是,它们的正确使用语法是什么?
我已经阅读了文档以及三个不同的教程,但仍然无法理解。
这是我尝试过的:
public abstract class BaseMatrix<T> {
protected int[] shape;
protected int nrows;
protected int ncols;
protected T data; // <--- Here is the generic data --->
public BaseMatrix(int rows, int cols){
this.nrows = rows;
this.ncols = cols;
this.shape = new int[]{nrows, ncols};
}
public abstract BaseMatrix mmul(BaseMatrix other);
这是我的实现:
public class ND4JDenseMatrix extends BaseMatrix{
// private INDArray data;
public ND4JDenseMatrix(int rows, int cols) {
super(rows, cols);
this.data = Nd4j.zeros(this.shape); <--- Here is the non-generic data --->
}
@Override
public ND4JDenseMatrix mmul(ND4JDenseMatrix other) {
ND4JDenseMatrix result = new ND4JDenseMatrix(nrows, ncols);
result.data = data.mmul(other.data);
return result;
}
错误是:Method does not override method from its superclass.
【问题讨论】:
-
注意你正在上线的警告
extends BaseMatrix。 -
很确定
mmul()应该在抽象类中返回T。 -
@chrylis-cautiouslyoptimistic- 这有点类似于@Override 警告:
Class 'ND4JDenseMatrix' must either be declared abstract or implement abstract method 'mmul(BaseMatrix)' in 'BaseMatrix'。我绝对没有正确实现 mmul 抽象类......但我似乎无法弄清楚我做错了什么。 -
@JustAnotherDeveloper 它应该!而且不应该!我想我明白你在说什么!让我尝试一些东西。
-
没错,但你也应该
extends BaseMatrix<ND4JDenseMatrix>。顺便说一句,您似乎正在尝试crtp,不幸的是,它无法用 Java 精确表达。
标签: java generics abstract-class