有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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类之外可用(除了它的继承者)

有什么办法吗


共 (2) 个答案

  1. # 1 楼答案

    在这种情况下,您可以考虑使用组合而不是继承 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];
        }
      }
    
  2. # 2 楼答案

    不幸的是,这是不可能的,因为如果一个类继承了另一个类,那么必须能够调用所继承类的所有方法

    如果你不想这样做,因为索引将超出范围,那么向矩阵添加getRows()getColumns()方法,任何拥有向量实例的人都会检查,以确保在调用get(int row, int col)时不会抛出索引超出范围异常