Sagiv Oulu
Sagiv Oulu

Reputation: 132

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(row, 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);

The private access modifiers doesn't help me, because it doesn't make the method available outside of the Matrix class (except for its inheritors)

Any ideas on how it could be done?

Upvotes: 3

Views: 167

Answers (3)

Luigi Papino
Luigi Papino

Reputation: 408

In this case you could think to use composition over inheritance The Vector class will 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 the 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];
    }
  }

Upvotes: 0

Lew Bloch
Lew Bloch

Reputation: 3433

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

?

Upvotes: 0

retodaredevil
retodaredevil

Reputation: 1382

Unfortunately, that's not possible because if a class inherits another, you must be able to call all of the methods of the class you are inheriting.

If you don't want to be able to do this because the index will be out of bounds, then add a getRows() and getColumns() method to matrix and anyone who has an instance of a Vector will check to make sure when they call get(int row, int col) it won't throw an index out of bounds exception.

Upvotes: 1

Related Questions