indexing a child class's fields in a mothers class's ArrayList and display all the fields

Viewed 26

Here is the code of the mother class

public class Media {

    private String reference;
    private int quota;
    private boolean disponibilite;
    private String type;

    public static List<Media> mediaList = new ArrayList<Media>();

    public Media(String reference, int quota, boolean disponibilite, String type) {
        this.reference = reference;
        this.quota = quota;
        this.disponibilite = disponibilite;
        this.type = type;
    }
    // getters and setters ... .
}

and the child class is (Livre)

public class Livre extends Media {
    private String cote;
    private String nomLivre;

    public Livre(String reference, int quota, boolean disponibilite, String type, String cote, String nomLivre) {
        super(reference, quota, disponibilite, type);
        this.cote = cote;
        this.nomLivre = nomLivre;
    }
}

As you can see, there's an ArrayList of Media in the Media's class

later on in the main code, I will add some media subclasses like (Livre) by doing

Livre l = New Livre(..........);
Media.mediaList.add(l); // everything is right here.

but my Issue Is, that when I try to display a field in the mediaList for a (Media) element, I'm not able to do it, for example

protected void IterateAndSeeAllMediaArrayElements(){
    for (int i =0; i< Media.mediaList.size(); i++){
    if(((Livre)Media.mediaList.get(i)).getNomLivre() != null) {
            System.out.println("\nLe nom :" + ((Livre)Media.mediaList.get(i)).getNomLivre());
            System.out.println("\nLa cote :" + ((Livre)Media.mediaList.get(i)).getCote());
        }
        Media.mediaList.get(i).getReference();
        Media.mediaList.get(i).getQuota();
        Media.mediaList.get(i).isDisponibilite();
        Media.mediaList.get(i).getType();
    }
    System.out.println("Fin de la recherche");
}

Error message :

 "class Media cannot be cast to class Livre"

Because the ArrayList contains some normal Media & some Livres. so how can I display all Livre fields, because I can't display the (NomLivre) field of a Media {because a simple Media has no NomLivre}

1 Answers

Determine if the Media instance is a Livre or not:

for (Media media : Media.mediaList) {
    if (media instanceof Livre livre) {
        System.out.println("\nLe nom :" + livre.getNomLivre());
        System.out.println("\nLa cote :" + livre.getCote());
    }
    media.getReference();
    media.getQuota();
    media.isDisponibilite();
    media.getType();
}

Note increase in readability with the use of a foreach loop and the pattern matching instanceof syntax introduced in Java 14.

For earlier Java versions, use:

if (media instanceof Livre) {
    Livre livre = (Livre)media;
Related