Instance of is considered to be a bad practice in java. But I don't know how to avoid it in such situation.
Let's say I have an abstract class ArtObject and there are some subclasses such as Painting, Engraving, etc. And I have a class Museum which contains an ArrayList of ArtObjects.
For example, I'd like to print information about all Painting objects in the Museum.
Should I do something like this?:
public void printAllPaintingsInfo() {
for (int i = 0; i < artObjects.size(); i++) {
if (artObjects.get(i) instanceof Painting) {
System.out.println(artObjects.get(i));
}
}
}
Or a better approach exists?
You can add a method isPainting() to ArtObject which is return false; by default and override to return true; in Painting.
Then you can write
public void printAllPaintingsInfo() {
for (ArtObject ao : artObjects)
if (ao.isPainting())
System.out.println(ao);
}
Or in Java 8 you can write
artObjects.filter(ArtObject::isPainting).forEach(System.out::println);
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