I have a list of objects which extend from a base class. Now I want to apply a specific operation only on one instance of classes in the list.
Is the use of instanceof a good practice there? Or should I rather differ the objects by eg a custom enum?
abstract class Base;
class Foo extends Base;
class Bar extends Base;
List<Base> bases;
for (Base base : bases) {
if (base instanceof Bar.class) {
//execute my custom operation on the base object
doSomething((Bar) base);
}
}
If that approach is not that nice in general, how could I do better?
There does not really seem to be any reason to use instance of here. It might make sense to have the base class default the behavior to doing nothing and override it in extending classes when needed. This way you only override it if needed (I on.y left this as an abstract class to follow with the question its not needed for this example).
For example:
An example of using this could be something like: