Various subclasses instanciated in an Arraylist?

edited November 2015 in Questions about Code

Hello! I'm relatively new to Processing and OOP.

I'm currently developing a shoot'em'up and I'm using Arraylists to 'control' my enemies. So far, everything has been working fine. I'm starting to get problems when I try to mix different sub-classes in the same arraylist. I can access the methods of all my childs, but I keep getting the fields of my parent.

I've done a fair amount of research, but without success: for clarity's sake, instead of posting my code that is quite lengthy, here's an example of what I'm trying to achieve:

ArrayList shapes = new ArrayList();
void setup() {
  shapes.add(new Rect());
  shapes.add(new Circle());
  for(Shape s : shapes) {
    if(s instanceof Rect) {
      println("type is rect");;
      println("my ID is: "+s.ID);
    else if (s instanceof Circle) {
      println("type is circle");
      println("my ID is: "+s.ID);
class Rect extends Shape {
  String ID="I'm a rectangle";
  void show(){
class Circle extends Shape {
  String ID="I'm a circle";
  void display(){
class Shape {
  String ID="I'm nothing";
  void display(){};
  void show(){};

So, 2 questions:

1) how can I access the ID value of my subclass? I keep reaching for its parent value? I'm obviously missing something important... 2) I've read that using 'instanceof' is a bad bad thing: can someone explain why, and what I should do instead?

Thanks by advance!


Sign In or Register to comment.