Java inheritance and access modifiers

I am trying to create a class system like this:

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);
    }
}

      

I want the Matrix.get (string, col) function to be public, but I don't want it to be public through the Vector class. I don't want this to be possible:

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

      

Private access modifiers don't help me because it doesn't make the method accessible outside of the Matrix class (other than its inheritors)

Any ideas on how this can be done?

+3


source to share


3 answers


Unfortunately, this is not possible, because if a class inherits from another, you must be able to call all the methods of the class that you inherit.



If you do not want to do that, because the index is out of bounds, and then add the method getRows()

and getColumns()

the matrix, and anyone who has a copy of the Vector, will check to make sure that they produce get(int row, int col)

, it will not raise an index outside ...

+1


source


What about

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


source


In this case, you might consider using composition over inheritance. The Vector class would become:

  public class Vector {
    private Matrix matrix;
    public Vector() {
      matrix = new Matrix();
    }
    public int get(int index) {
      return matrix.get(0, index);
    }
  }

      

Another solution could be to invert inheritance:

 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];
    }
  }

      

0


source







All Articles