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?
Performance-wise, instanceof is really fast; it's definitely faster than comparing our own type field; it may even be faster than comparing Class with == .
The problem with instanceof is that if you have a large amount of Animal s, you'll end up with a long if-else-if for every one of them. It's hard to maintain and prone to errors where e.g. a new type of Animal is added, but you forget to add it to the if-else-if chain.
The isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if the type is to be checked at runtime then use the isInstance method otherwise instanceof operator can be used.
As the name suggests, instanceof in Java is used to check if the specified object is an instance of a class, subclass, or interface.
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:
abstract class Base{
public void doSomething(){}
}
public class B0 extends Base{
@Override
public void doSomething(){//actually do something}
}
public class B1 extends Base{}
An example of using this could be something like:
public class SomeOtherClass{
public void something(List<Base> bases){
for(Base base:bases)
base.doSomething();
}
}
abstract class Base;//abstract function doSomething()
class Foo extends Base;//implements doSomething()
class Bar extends Base;//dito
List<Base> bases;
for (Base base : bases) {
base.doSomething();
}
To answer your question: it is not a good idea to use instanceof.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With