Java 使用继承定义nxn矩阵

Java 使用继承定义nxn矩阵,java,inheritance,processing,Java,Inheritance,Processing,我已经为nxn矩阵编写了一个类,我在processing中编写了这个类,但我希望这个想法仍然清晰 class Matrix { float[][] entries; Matrix(int n_) { n = n_; entries = new float[n][n]; } float[][] getEntries() { return entries; } void setEntries(float[][] k) { entries

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

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的东西,我如何才能做到这一点呢?

您可以有一个更通用的类型,它包含两个参数。下面是一个简单的例子:

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
  }
}
然后,您可以在以前可以使用矩形矩阵的任何位置使用方形矩阵。无耻的自我提升:是一个关于继承的教程


但老实说,我看不出更具体的类型有多大价值。只需使用常规类型并传入正确的参数。

在矩阵的构造函数中:supern,n;。注意,您应该验证setEntries中k的大小;拿一份防御性的副本;并在getEntries中返回一个防御性副本。@AndyTurner但在引用该类的代码中,我是否需要将矩阵a=new Matrix5替换为矩阵a=new Matrix5,5?不。您仍然要传递一个参数。我编写的大多数代码行列式等仅适用于nxn矩阵,所以我不想回去开始写throw everywhere和更新所有参数等等@AndresMejia,但是如果你有一个矩形矩阵的实例,它恰好是正方形的,那该怎么办呢?你不想计算它的行列式吗?或者您想先强制显式转换为平方矩阵吗?@AndresMejia好的,那么把代码放在SquareMatrix类中。我更新了我的答案,加入了一个例子。