Java继承和访问修饰符

3
我将尝试创建一个类似于这样的类系统:
public class Matrix {
    private int[][] m;
    public Matrix(int rows, int cols) {
        //constructor
    }
    public int get(int row, int col) {
        return m[row][col];
    }
}

public class Vector extends Matrix {
    public Vector() {
        //constructor
    }
    public int get(int index) {
        return super.get(0, index);
    }
}

我希望Matrix.get(row, col)函数是公共的,但我不希望通过Vector类使其公共化。我不想让这种情况发生:

Vector v = new Vector();
int x = v.get(1, 1);

私有访问修饰符对我没有帮助,因为它不会使该方法在Matrix类以外可用(除了它的继承者)。
有什么好的想法吗?

5
那么,Vector不应该扩展Matrix。你为什么想要实现这样的东西?听起来像是一个XY问题。 - RaminS
怎么样,试试protected关键字吧 ;) - nits.kk
不可能。但你可以做一件事情,就是重写Vector类中的get方法并将其标记为过时。 @Override @Deprecated /** * 不要使用该方法 */ public int get(int row, int col) { return -1; } - hanumant
1
你可以尝试更改包结构并使用默认访问修饰符。 - Mustafa Çil
“Matrix.mul(Matrix a, Matrix b)”这个方法看起来不太对,因为它似乎是一个静态方法。考虑到有一个“Matrix p”和一个“Matrix q”,该方法的签名应该是“Matrix mul(Matrix a)”。例如:“Matrix r = p.mult(q)”。这可以重载为“Matrix mul(Vector v)”方法。 - Andrew S
显示剩余6条评论
3个回答

1
很遗憾,这是不可能的,因为如果一个类继承另一个类,你必须能够调用所继承的类的所有方法。
如果您不想这样做,因为索引将超出范围,则可以在矩阵中添加一个getRows()getColumns()方法,任何拥有Vector实例的人都会检查当他们调用get(int row, int col)时,它不会抛出索引超出范围异常。

0

怎么样?

public class Vector extends Matrix {
  public Vector(int cols) {
    super(0, cols);
  }

  public int get(int index) {
    return get(0, index);
  }

  @Override
  public int get(int row, int col) {
    if (row > 0) {throw new IllegalArgumentException("row != 0");
    return super.get(0, index);
  }
}

?


0
在这种情况下,你可以考虑使用组合而不是继承。 Vector类将变为:
  public class Vector {
    private Matrix matrix;
    public Vector() {
      matrix = new Matrix();
    }
    public int get(int index) {
      return matrix.get(0, index);
    }
  }

另一种解决方案可能是反转继承关系:
 public class Matrix  extends Vector{
    private int[][] m;
    public Matrix(int rows, int cols) {
      super(0);
    }
    public int get(int row, int col) {
      return m[row][col];
    }

    @Override
    public int get(int index) {
      return m[0][index];
    }
  }

  public class Vector {
    private int[] v;

    public Vector(int length) {
      v = new int[length];
    }
    public int get(int index) {
      return v[index];
    }
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接