How to go through Arraylist with daughter class

Asked

Viewed 466 times

4

Next, I have one ArrayList student type (which is an abstract class), and I have two daughter classes (EstudanteGraduacao and EstudantePosGraduacao), when I’ll add them to ArrayList it’s quiet, but how do I walk it with an object of the daughters?
For example when I do:

for(Estudante e : estudantes){
    return e.getX();
    // considerando getX um metodo de Estudante
}

it works, the problem is that I do not know how to access the methods of EstudanteGraduacao...

Anyway, I hope I’ve been clear, I appreciate the help

  • Wouldn’t it be the case that you add abstract methods to the student superclass that represent the common operations of each subclass? If the superclass is an empty class, it may be that your model using inheritance is not the most suitable.

2 answers

0

An alternative is to use the instanceof before performing any operation. If the array element is instanceof(EstudanteGraduacao) then it is possible to call a method of the type EstudanteGraduacao.

0

You have to cast the student cast

((EstudanteGraduacao) e).getX()

But be careful, if all students in the array are not Student.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.