Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instanceof correct usage in java

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?

like image 483
StasKolodyuk Avatar asked Mar 30 '26 23:03

StasKolodyuk


1 Answers

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);
like image 120
Peter Lawrey Avatar answered Apr 02 '26 04:04

Peter Lawrey