How do i pass a class type into a function

That worked


// https://Discourse.Processing.org/t/
// parent-function-not-using-overwritten-array-from-child/22796/3

// https : // discourse.processing.org/t/how-do-i-pass-a-class-type-into-a-function/30337/5 

// parts by GoToLoop (2020/Jul/23)

final Parent[] children = {
  new Child1(), 
  new Child2(), 
  new Child3(), 
  new Child1(), 
  new Child1() 
};

void setup() {
  size(660, 660);
  printArray(children);
  println();
  for (final Parent child : children) {  
    println(child.isArrayTrue(4));
  }

  print("counting...   "); 
  println(count(children, Child1.class ));
}

void draw() {
  //
}//

// ------------------------------------------------------------------------------------------

int count(Parent[] list, Class cls  ) {
  int n = 0;

  for (int i = 0; i < list.length; i++) {
    if (cls.isInstance(list[i] ) ) {
      n++;
    }
  }
  return n;
}

//==========================================================================================

abstract class Parent {
  boolean[] array;

  boolean isArrayTrue(final int index) {
    return array[index];
  }

  @Override String toString() {
    return java.util.Arrays.toString(array);
  }
}

class Child1 extends Parent {
  {
    array = new boolean[] { true, true, true, true, true, true, true };
  }
}

class Child2 extends Parent {
  {
    array = new boolean[] { false, true, false, true, false, true, false };
  }
}

class Child3 extends Parent {
  {
    array = new boolean[] { false, true, true, false, true, true, false };
  }
}

1 Like