Help with static methods!

I’m getting an error that says ‘No enclosing instance of type ____ is accessible’. I basically want a class that has both non-static and static variables but Processing doesn’t allow that for some reason. I tried putting static methods in the Matrix class but I still got an error.

static class Matrix_Static {
   // Multiply Matrix m1 by Matrix m2
  static Matrix multiply(Matrix m1, Matrix m2) {
    // Matrix Product (a • b)
    if(m1.cols == m2.rows) {
       Matrix result = new Matrix(m1.rows, m2.cols);
      for(int i = 0; i < result.rows; i++) {
        for(int j = 0; j < result.cols;j++) {
          float sum = 0;
          for(int k = 0; k < m1.cols; k++) {
            sum += m1.data[i][k] * m2.data[k][j];
          }
          result.data[i][j] = sum;
        }
      }
      return result;
    } else {
      println("error - conflicting dimensions");
      return null;
    }
  }
}

class Matrix extends Matrix_Static {
  int rows, cols;
  float[][] data;
  
  // Constructor 1
  Matrix(int rows, int cols) {
    this.rows = rows;
    this.cols = cols;
    this.data = new float[rows][cols];
    
    for(int i = 0; i < rows; i++) {
      for(int j = 0; j < cols;j++) {
        this.data[i][j] = 0;
      }
    }
  }

Assuming this is Java, it sounds like you’re more concerned with how static methods and variables in Java.

Can I ask what you already know about building classes and using static methods/variables?

Also, to add code, surround the code with triple tildes

Hi!
Can you please format your code using the </> button please?

Also, you can go have a look here for more general informations about posting:

1 Like

Thanks for replying so quickly! So I have this Matrix class with a bunch of non-static methods that can only be called with an instance of a matrix class, but I want to add a static classes within the Matrix class so I can add, say, a method which is called multiply which takes 2 matrices and multiplies them together. This static method would be called by: Matrix.multiply(m1, m2); which would return a new Matrix. Processing does not allow me to do this for some reason…

Have you got it to work without implementing the class as a static class? I’ll be honest, I’m not an expert, but from my understanding, using static methods is generally a performance thing.

My advice? Try to get it working without static elements, and then implement static elements.

In Java the keyword static does not have the same meaning as in c# for example and you can’t create an outer static class. The keyword should be used only for inner classes. See that link for further explanation:

PS: Again, can you please format your code in your first post? It is not because I was not giving you solution in my previous post that you need to ignore what is writtent in it…

1 Like