How to access a method of a subclass from an ArrayList of the superclass?

0

I have the following code:

public class SeleccionFutbol{

protected int carnetIdent;
protected String nombre;
protected String apellidos;
protected int edad;

public SeleccionFutbol(int id, String n, String a, int edad){
  carnetIdent =   id;
  nombre      =    n;
  apellidos   =    a;
  this.edad   = edad;
   }
    //getters y setters
}

and the subclasses:

public class Entrenador extends SeleccionFutbol{
private String codEntrenador;

public Entrenador(int id, String n, String a, int edad, String cod){
 super(id,n,a,edad);
 codEntrenador = cod;
  }
  //getters y setters
}

And I have an ArrayList of the Football Selection type, from which I must show the coach's data, which I did like this:

System.out.println("El entrenador que dirigira el partido es: ");
    for(SeleccionFutbol s : integrantes){
        if(s instanceof Entrenador){
        System.out.println(s.getNombre() + " "+ s.getApellido() + ",edad: " + getEdad());
      }
    }

But I do not know how to show the coach's code.

    
asked by Morokei 30.11.2017 в 00:33
source

2 answers

0

Convert s to Entrenador to be able to access the coach's code:

System.out.println("El entrenador que dirigira el partido es: ");
for(SeleccionFutbol s : integrantes){
    if(s instanceof Entrenador){

    // convertimos s en Entregador
    Entrenador en = (Entrenador)s;

    // accedemos las propiedades de en
    System.out.println(en.getCodEntregador())
    System.out.println(s.getNombre() + " "+ s.getApellido() + ",edad: " + getEdad());
  }
}
    
answered by 30.11.2017 / 00:37
source
0

Daughter classes inherit the methods of the parent class, so if you have the getters in Trainer with doing

s.getId();

you'll get it

One important thing and one opinion I do not think Football Selection is a child of the Coach class, rather I would think that Coach is an attribute of Football Selection.

Take a look at the inheritance once more

    
answered by 30.11.2017 в 00:37