簡體   English   中英

抽象類方法 - 實例化子類對象?

[英]Abstract class method - To instantiate child class object?

我正在嘗試創建一個矩陣庫(教育目的)並且已經遇到了障礙我不知道如何接近優雅 添加兩個矩陣是一項簡單的任務,在每個矩陣的元素上單獨使用方法get()

但是,我使用的語法是錯誤的。 NetBeans聲稱它期望一個類,但發現了一個類型參數; 對我來說,類型參數只是一組與1到1的映射到類的集合。

我為什么在這里錯了? 我以前從未見過類型參數是除了類以外的任何東西,所以下面的一點不應該暗示M是一個類嗎?

M擴展了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);
}

您無法直接實例化類型參數M ,因為您不知道其確切類型。


我建議考慮創建以下方法

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

及其在子類中的實現。

從你的代碼中,我想你想從Matrix擴展一些子類並對它們進行計算。

改成

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

在每個子類中,添加plus的實現。 由於子類的構造功能在那里被定義。

我不認為你的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不是可以實例化的類。

基本上,您需要稍微更改一下數據結構,因為您的Matrix類是abstract ,也無法實例化!

我建議你將plus的返回類型更改為Matrix並將其保留為抽象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM