Java继承和访问修饰符
我试图创建一个这样的课堂体系:
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);
}
}
我想要矩阵。get(row,col)函数是公共的,但我不希望它通过Vector类是公共的。我不希望这成为可能:
Vector v = new Vector();
int x = v.get(1, 1);
私有访问修饰符对我没有帮助,因为它不能使方法在Matrix类之外可用(除了它的继承者)
有什么办法吗
# 1 楼答案
在这种情况下,您可以考虑使用组合而不是继承 Vector类将成为:
另一个解决方案可能是反转继承:
# 2 楼答案
不幸的是,这是不可能的,因为如果一个类继承了另一个类,那么必须能够调用所继承类的所有方法
如果你不想这样做,因为索引将超出范围,那么向矩阵添加
getRows()
和getColumns()
方法,任何拥有向量实例的人都会检查,以确保在调用get(int row, int col)
时不会抛出索引超出范围异常