Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 659
Sagiv Oulu Avatar asked Sep 25 '26 10:09

Sagiv Oulu


1 Answers

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.

like image 167
retodaredevil Avatar answered Sep 28 '26 00:09

retodaredevil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!