Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to call methods from all the subclasses of an abstract class?

I want to make API calls to a bunch of different API services. I have an abstract class called ApiService that contains common methods for each subclass. Every new API will have to inherit and implement these methods.

My question is: how can I go through all the subclasses of ApiService and call their methods?

Right now, I have a static array of all the services instantiated already (which means that new services must be manually added to the array) that looks something like this:

ApiService[] services = {new SubService1(), new SubService2(), ...};

I was wondering if there was a better way of doing this.

like image 890
Andrew Hassan Avatar asked Dec 21 '25 06:12

Andrew Hassan


1 Answers

You want to call a method on each instances of subclasses of an abstract class. There is no automatic way to find all the instances of a class anyway, so you need to manage the list of all instances yourself.

You have to do one of the following:

  • manage the list manually, that is add instances to the list when you create them
  • make that more automated, by adding the instance to a static list in the constructor of your base class ApiService. But it makes the base class aware of the list of its instances, and it seems to me a bit of a code smell.

There is another alternative, when you know the number of instances in your application in advance: use an Enum instead of an abstract class. Each Enum value is an instance of the class, and it can implement interfaces and methods, and each instance can override a method differently.

like image 80
Cyrille Ka Avatar answered Dec 22 '25 20:12

Cyrille Ka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!