Access a method of a subclass from an arraylist?

2

I'm doing a pretty simple program to learn some things from java and I have the following super class:

  public abstract class Persona {
    //Atributos
    protected String nombre;
    protected String apellido;
    protected int edad;

    //Metodos
    public Persona(String nombre, String apellido, int edad) {
       this.nombre = nombre;
       this.apellido = apellido;
       this.edad = edad;
    }

    public abstract void viajeDeEquipo();
    public abstract void partidoDeFutbol();
 }

later I have the SubClase:

 public class Entrenador extends Persona{
 //Atributos
 private final String estrategia;

 //Metodos
public Entrenador(String estrategia, String nombre, String apellido, int edad)  {
     super(nombre, apellido, edad);
     this.estrategia = estrategia;
 }

  @Override
  public void viajeDeEquipo(){
    System.out.println("El entrenador prepara sus antoaciones de estrategias 
    y esta listo para viajar.");
  }

 @Override
  public void partidoDeFutbol(){
     System.out.println("El entrenador"
            +apellido+" se sienta en el banquillo y esta listo para 
dirigir.");   
  }

   public void planificarEntrenamiento(){
     System.out.println("El entrenador "
             +nombre+"revisa su estrategia: "+estrategia);
   }
}

and in the main I made an array of type Person in which I store the subclasses in each position (there are other subclasses as footballer or doctor but have no relation to my problem):

static ArrayList<Persona> p1 = new ArrayList<Persona>();

public static void main(String[] args) {
    Futbolista f1 = new Futbolista(10,"Mediocampista","Javier","Pastore",28);
    p1.add(f1);
    Entrenador e1 = new Entrenador("Jugar al contraataque", "Marcelo", "Bielsa",62);
    p1.add(e1);
    //el codigo sigue...

The problem is that I want through a menu to select certain action to be performed but trying to access the method of the subclass 'Trainer' of the arrayList does not recognize the methods of that class if not only those of the super class 'Person'.

switch(opcion){
            case 1:
                for (Persona pers : p1) {
                    pers.viajeDeEquipo();
                    System.out.println("");
                }
                System.out.println("");
                break;

            //Siguen los cases...

            //Aca es donde no me reconoce el metodo
            case 4:
                System.out.println(p1.get(1).planificarEntrenamiento());
                break;
        }

It is assumed that the arrayList in this position is of the Trainer type (I even verify it with the method 'getClass ()') but I can not access this method, I do not know what I will be doing wrong ...

    
asked by Hernan Rodriguez 01.02.2018 в 18:46
source

1 answer

4

The problem is that p1 is a list of Personas , so p1.get(n) always returns an object Persona . Even the following would give you an error:

Persona entrenador= new Entrenador(...); //correcto, un Entrenador es una persona

entrenador.planificarEntrenamiento(); //error de compilación

The solution is the following:

if (p1.get(1) instanceof Entrenador) {
    Entrenador e = (Entrenador) p1.get(1); //Casting explícito
    e.planificarEntrenamiento();
}
    
answered by 01.02.2018 / 18:58
source