使用继承来定义nxn矩阵

时间:2018-05-07 21:47:43

标签: java inheritance processing

我已经为nxn矩阵写了一个类(我已经在处理中写了这个,但我希望这个想法仍然清晰)

class Matrix {
  float[][] entries;

  Matrix(int n_) {

    n = n_;
    entries = new float[n][n];
  }

  float[][] getEntries() {
    return entries;
  }

  void setEntries(float[][] k) {
    entries = k;
  }
}

但是现在想要推广nxm矩阵,但是想保留已经为nxn矩阵编写的代码的代码,而不改变它,我有了编写新类Gmatrix的想法:

class Gmatrix {
  float[][] entries;
  int row;
  int col;

  Gmatrix(int row_, int col_) {
    row = row_;
    col = col_;
    entries = new float[row][col];
  }

  float[][] getEntries() {
    return entries;
  }

  void setEntries(float[][] k) {
    //  entries = k;

  }
}

但我基本上只想在Matrix类中编写类似row = n,col = n的内容,我该如何实现呢?

1 个答案:

答案 0 :(得分:1)

你可以有一个更通用的类型,它接受两个参数。这是一个更简单的例子:

class RectangularMatrix{
  int rows;
  int columns;

  public RectangularMatrix(int rows, int columns){
    this.rows = rows;
    this.columns = columns;
  }

  public void printRowsAndColumns(){
    println(rows + ", " + columns);
  }
}

然后是一个更具体的类型,它扩展了这个类,只接受一个参数:

class SquareMatrix extends RectangularMatrix{
  public SquareMatrix(int length){
    super(length, length);
  }

  public void onlyApplicableToSquareMatrix(){
    // put code specific to SquareMatrix here
  }
}

然后,您可以在之前使用SquareMatrix的任何地方使用RectangleMatrix。无耻的自我推销:here是继承的教程。

但老实说,我不会在更具体的类型中看到很多价值。只需使用常规类型并传入正确的参数。