Looping different class instances

Abstract classes and reflection are fine solutions given your constraint (no interface!) but I’m a bit confused about why this is an issue.

If you don’t want to map a large method list up from Helper to A / B / C, then don’t. You can still use an interface.

Just create an interface Helpful with only one method – Helper getHelper(), which returns the Helper object of that A/B/C object. Your classes A B C each implement that one method which makes them Helpful (class A implements Helpful … class B implements Helpful …) – and then in your main code you loop through a list of Helpful objects, call Helper h = obj.getHelper() on each of them, and then access h.printHello() or whatever method(s) you need on that Helper that was returned. No need to touch your underlying hairy utility class at all – just give your heterogeneous collection of classes the simplest possible interface to return that object.

Code or it didn’t happen:

void setup() {
  Helpful[] helpers = { new A(), new B(), new C() };
  for (Helpful obj : helpers) {
    // single method quick access
    obj.getHelper().printHello();
    // or retrieve the helper for multiple method calls
    Helper h = obj.getHelper();
    h.printHello();
  }
}

interface Helpful {
  Helper getHelper();
}

class A implements Helpful {
  Helper h = new Helper("A");
  Helper getHelper() { 
    return h;
  }
}

class B implements Helpful {
  Helper h = new Helper("B");
  Helper getHelper() { 
    return h;
  }
}

class C implements Helpful {
  Helper h = new Helper("C");
  Helper getHelper() { 
    return h;
  }
}

class Helper {
  String hello = "hello ";
  Helper (String s) { 
    hello+=s;
  }
  void printHello() { 
    println(hello);
  }
}

Note that, depending on the details of what you are trying to do, this Breaks Encapsulation. However if you are trying to access an arbitrary list of methods on this object without adding them to your wrapper classes then it sounds like you are already fine with this.

2 Likes