Saving objects from different classes into the same array

Looks like you understand all the concepts but you’re syntax might be a little off in places. So If you get stuck check the reference page because it’s good examples on most of what you can do. I suggest working on getting something like 5 levels done and running, before working on the rest because it’s a pain to do a bunch of work and then have to throw it away because you realize it’s not working right. But it’s easy to expand on code you already know works.

There’s something called an interface that will allow you to put a bunch of different things in a ArrayList (or an array). It’s a bit more advanced but if you want to check it out it can be really useful. Here’s a tutorial on interfaces. And here’s an example in processing. This is how I would do it in your project:

interface GameElement {
  void show();
}

class Level {
  ArrayList<GameElement> elements = new ArrayList<GameElement>();
  // Anything that implements GameElement can go in this list
  // Add constructor
  void show() {
    for (GameElement g : elements) {
      g.show(); // can call show because every GameElement is forced to have a show method
    }
  }
 // Add whatever else you need
}

class Key implements GameElement {
  // Whatever you have in this class
  void show() {
    // should get an error if the Key class doesn't have a show method because it implements GameElement
    // however you would show your key
  }
}
1 Like