Mark Mark - 17 days ago 7
Java Question

How to call a getter from another class, when the object is not given?

For the code below I have a constructor Puzzle with a corresponding getter.

public class Puzzle {

private int [][] array;

public Puzzle(int[][] array) {
this.array = array;
}

public int[][] getArray() {
return this.array;
}

}


In another class I want to have a non static method that solves the puzzle. But I need to use the getter to get the 2D array...

public class Solver {

public void solve() {
int[][] a1 = getArray();
}
//...More Code here ...
}


I want it to be solved so that in a main method it can be called as such ...

puzzle.solve();


However the getArray() method is said to be undefined in the class Solver. Is there any way around this without having to accept the puzzle to be solved using solve(puzzle)?

Answer

You've to create an instance of the class:

public class Solver {

    public void solve() {
        int[][] a2 = { {1, 2, 3}, {1, 2, 3} };
        Puzzle puzzle = new Puzzle(a2);
        int[][] a1 = puzzle.getArray();
    }
    //...More Code here ...
}

The following code answers your question, but it doesn't make much sense. You've to ask yourself, an array from which object I want to get? Do you have such object in your code? Than you have to pass this object to solve method and call getArray() on that object.

public class Solver {

    public void solve(Puzzle puzzle) {
        int[][] a1 = puzzle.getArray();
    }
    //...More Code here ...
}