Java: create objects and call their methods in loops

B/c outside of methods, we can only declare fields. :raising_hand_man:
However, we can use initialization curly blocks {} outside methods and run statements there: :man_singer:

final Obj[] arr = new Obj[10];

{
  for (int i = 0; i < arr.length; ++i) { 
    final Obj ob = arr[i] = new Obj();
    ob.x = (int) random(600); 
    ob.y = (int) random(320);
  }
}

void setup() {
  size(600, 320);

  // blah, blah, blah...
}

class Obj {
  int x, y;

  void render() {
    // blah, blah, blah...
  }
}
1 Like