Tell me, please, how is it possible to initialize the matrix in the init() method of the Matrix class so that the rows and columns have values from the main method? It turns out that the constructor of the RunnableTask parent class is immediately called, then it goes to the Matrix class’s init() method and the matrix has a size of zero. And it is necessary that in the init() method of the Matrix class, the matrix has a size of 5*5 .
public static void main(String[] args) { RunnableTask matrix = new Matrix(5, 5); } public abstract class RunnableTask { public abstract void runTask(); public abstract void init(); public void run() { runTask(); } public RunnableTask() { init(); } } public class Matrix extends RunnableTask { int rows; int cols; int matrix[][]; public Matrix(int rows, int cols) { this.rows = rows; this.cols = cols; } @Override public void init() { matrix = new int[rows][cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { matrix[i][j] = i * j; } } } @Override public void runTask() { for (int i = 0; i < rows; i++) { System.out.println(); for (int j = 0; j < cols; j++) { System.out.print(" " + matrix[i][j] + " "); } } } }
initmethod fromRunnableTask? In essence, it duplicates the constructor’s functionality. - diraria