3

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.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107

1 Answers1

7

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?

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • Ah, I see. I had forgotten that I could create functions outside of classes. Thanks for your help! – Drew Christensen May 29 '17 at 22:37
  • @DrewChristensen Technically it's inside the main sketch class, but the Processing editor hides that from you. – Kevin Workman May 29 '17 at 22:40
  • Ah, yes. Technicalities. – Drew Christensen Jun 01 '17 at 20:50
  • I want to use them for the same reason you'd ever want to use class methods/variables - information hiding. If I've got a particle class that has particular properties of the particle system that noone on the outside of the class needs to know about then I'd rather keep that information interior to the particle class and not have it hanging around at what appears as our outer level polluting the namespace and making it appear like that info should be manipulated outside of the class when it shouldn't. – Darrell Plank Oct 08 '21 at 17:42