Questions on static methods

  • You should know by now that all classes & interfaces inside “.pde” files are nested to a PApplet subclass.
  • But when we declare them as static they behave pretty much like any other vanila top classes like those found in a “.java” file.
  • B/c inner classes in “.pde” files belong to a PApplet subclass, we can access its members directly w/o using the dot . operator.
  • However, when they’re declared as static, non-static members demand a PApplet reference.
  • And if you really need to have static members inside your nested classes, those classes gotta be declared as static as well.
  • Unless they’re merely static compile-time constants.
  • If the above is the case, even inner classes can have those static final fields.
  • But fret not! I’ve got an “elegant” workaround for ya. :joy_cat:

Do like Processing’s 3rd-party libraries: Request a PApplet argument as 1 of its constructor’s parameters: :bulb:

static class MyVector {
  final PApplet p;
  float v1, v2;

  MyVector(final PApplet pa) {
    p = pa;
  }

  void randomize() {
    v1 = p.random(1);
    v2 = p.random(1);
  }
}
3 Likes