Johny Wong
Johny Wong

Reputation: 11

2d array passing in java

Class file:I use 2d int array to store the value then i set the setter and getter

public class SquareMatrix implements SquareMatrixInterface{
    int[][] squareMatrix; 

    public int[][] getSquareMatrix() {
        return squareMatrix;
    }

    public void setSquareMatrix(int[][] squareMatrix) {
        this.squareMatrix = squareMatrix;
    }
}

Interface file

public interface SquareMatrixInterface {
    public int[][] getSquareMatrix();
    public void setSquareMatrix(int[][] squareMatrix);
}

Main: I put a value and try to set the value to the setter but it gives me error

public class test {

    SquareMatrixInterface matrixA = new SquareMatrix();
    SquareMatrixInterface matrixB = new SquareMatrix();

    public static void main(String[] args) {
        int[][] m1 = {{1,2},{3,4}};
        matrixA.setSquareMatrix(m1);

    }
}

why it give me error when i try to pass in the array to the setter how to pass a 2d array without include java library

Upvotes: 1

Views: 248

Answers (1)

J-J
J-J

Reputation: 5871

you cant access non static properties inside static block.. [Cannot make a static reference to the non-static field] so you need to rewrite your main method to..

    public static void main(String[] args) {
        SquareMatrixInterface matrixA = new SquareMatrix();
        int[][] m1 = {{1, 2}, {3, 4}};
        matrixA.setSquareMatrix(m1);
    }

OR

static SquareMatrixInterface matrixA = new SquareMatrix();

public static void main(String[] args) {
    int[][] m1 = {{1, 2}, {3, 4}};
    matrixA.setSquareMatrix(m1);
}

Upvotes: 3

Related Questions