Access the daughter class from the father | Java

0

I have an abstract class Publicaciones and two child classes: Libro and Revista .

I have a ArrayList of Publications, where I keep objects Libro and objects Revista , but when accessing the attributes of libro and revista (those that do not inherit from the parent class) through publications .get(i) recognizes the objects as Publications and not as what they are, class Libro and Revista , respectively.

I know that the type of objects that are stored in ArrayList are Publicaciones , but I do not want to do a ArrayList for each type of publication.

Is there any way to do this? Or maybe he's posing the exercise badly.

public void listarLibrosAutor() throws IOException{
    BufferedReader teclado = new BufferedReader(new InputStreamReader(System.in));
    String autor;

    System.out.println("Introduce el autor: ");
    autor = teclado.readLine();

    for (int i = 0; i < publicaciones.size(); i++) {

        if(publicaciones.get(i) instanceof Libro && publicaciones.get(i).getNombreAutor()){


        }
    }
}

The method is to list the books from an author, at the moment I try to access the attribute nombreAutor is when I get the error.

    
asked by Daniel Plata 03.12.2016 в 16:20
source

1 answer

4

To access the parameters of each daughter class you would have to cast the specific class. Example:

Publicaciones p = list.get(i);
if (p instanceof Libro){
    Libro l = (Libro) p;
    l.getXXX();
}
else if (p instanceof Revista){
    Revista r = (Revista) p;
    r.getYYY();
}

Warning: this is not an "elegant" way to solve the problem (let's say it is not 100% object oriented).

    
answered by 03.12.2016 / 18:50
source