Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods unallowed in Processing?

I apologize in advance if I'm not doing something correctly, or if I didn't see something that I should have.

I began programming with Java and am currently using Processing, which is a more user-friendly and easier-to-understand version of Java, at its core. I am attempting to define a static method on a class (allowed by Java), but it gives me the error "The method cannot be declared static; static methods can only be declared in a static or top level type."

My code, simplified to demonstrate the problem, is as follows:

class Item {
  static void test() {
    print("Hello");
  }
}

It will not run or compile, and as far as I can see, the only workaround would be to make it non-static and call it on specific objects.

Is there a way that I could define it such that I can keep it a static method?

Thanks in advance for any help with this problem.

like image 547
Drew Christensen Avatar asked Jan 19 '26 18:01

Drew Christensen


1 Answers

This is because all classes in Processing are inner classes of your main sketch class. You can't have static classes inside an inner class. See here for more info.

To get around this, you could create a new Item.java tab, which would create a separate top-level class. But then you'd have to pass in the sketch instance to use any Processing functions inside that class. Whether that's worth gaining the ability to use static is up to you.

I will say that I don't see a ton of benefits to using a static function inside a class in a Processing sketch. Can you use a sketch-level function instead?

like image 105
Kevin Workman Avatar answered Jan 21 '26 08:01

Kevin Workman