Error trying to add super class objects to subclass arraylist

I have an ArrayList that stores instances of the subclass (SubClass) of another class (SupClass). I have already defined the classes, SupClass and SubClass (with SubClass extending SupClass) and there is already a SupClass ArrayList (called superArray) that I want to extract any SubClass instances from. Here is the code that I am struggling with:

ArrayList<SubClass> array = new ArrayList<SubClass>();
for (SupClass s : superArray) {
  try {
    array.add(s);
  } catch (Exception e) {
  }
}

The problem is that Processing knows that the objects that the for loop is iterating through are not necessarily SubClass objects so displays the message [The function “add()” expects parameters like: “add(SubClass)”] and does not allow the code to even begin running. Is this a problem with Processing, or is there some way that I need to rewrite my code so that Processing allows it to run?

I understand that instances of a subclass can be added to an ArrayList of their super class, but in this scenario I need the ArrayList to be made of SubClass.

1 Like

This is really a limit in how classes operate.
Processing (Java) knows how to look at a subclass as a super but not the other way around.

"All cars are vehicles but not all vehicles are cars."

If you needed to access a subclass-only function from your list of superclasses you can use something like this:

if (s instanceof SubClass)
{
  ((SubClass)s).subfunc();
}

See this note on subclasses

3 Likes

For 99% of cases, it’s wrong to have Java containers w/o specifying its generic <datatype>: :radioactive:

import java.util.List;

static final int SUPS = 5;
final List<SupClass> supsOrSubs = new ArrayList<SupClass>(SUPS);

void setup() {
  noLoop();

  for ( int i = 0; i++ < SUPS; supsOrSubs.add(
    random(1) < .5? new SupClass() : new SubClass()) );
}

void draw() {
  for (final SupClass sc : supsOrSubs)  println(sc);
}

class SupClass {
  @Override String toString() {
    return getClass().getSimpleName();
  }
}

class SubClass extends SupClass {
}
2 Likes

You’re absolutely right. I actually did type that but forget to block text the code so the formatting emitted that part of the code.

Thank you for pointing my mistake out.

I suspected this might be the case. I was unaware of Java’s ‘explicit casting’ functionality but have now educated myself on the concept after reading through the note you provided.

Thank you very much for responding to my query; it is much appreciated.