Navigate array accessing attributes of child classes

1

I have an array of type Relacion , which is filled with objects of type Binario .

Binario inherits Relacion . How can I get the values of the attributes of binary objects?

  Relacion exprs[] = { new Binario(Operador.MENORQUE,
                                new Falso(),
                                new Verdadero()),
                       new Binario(Operador.MAYORQUE,
                                   new Falso(),
                                   new Verdadero()),
                       new Binario(Operador.MENORQUE,
                                   new Verdadero(),
                                   new Verdadero()),
                       new Binario(Operador.MAYORQUE,
                                   new Verdadero(),
                                   new Falso())
  };

Relationship class

 public abstract class Relacion {
 }

Binary Class:

  public class Binario extends Relacion {

   private Relacion izq;
   private Relacion der;
   private Operador oper;

 public Binario(Operador oper, Relacion izq, Relacion der) {

    this.oper = oper;
    this.izq  = izq;
    this.der  = der;
 }

 public Relacion obtIzq() {

    return this.izq;
 }

 public Relacion obtDer() {

    return this.der;
 }

 public Operador obtOper() {

    return this.oper;
 }
}
    
asked by Eduard Damiam 26.08.2017 в 02:45
source

1 answer

1

Your array is defined on the type Relación , so you can access the attributes and methods of that class, not the one of your child classes.

To be able to access members of the child classes of Relación you must cast to a of those classes, for example, Binario

The cast operation is not a secure operation and can result in ClassCastException at run time.

Example:

public class Vehiculo{
 }

public class Auto extends Vehiculo{
     public void abrirPuertas(){
     }
 }

public class Moto extends Vehiculo{
     public void wheele(){
     }
 }

Situation where cast would produce ClassCastException:

List<Vehiculo> vehiculos = new ArrayList<Vehiculo>();
vehiculos.add(new Moto());
vehiculos.add(new Auto());

for(Vehiculo v : vehiculos){
   Moto m = (Moto) v; //Casteo
   m.wheele();
}

The first iteration of the loop would have no disadvantages, since the first aggregate vehicle is effectively a Moto , however, in the second iteration it would try to cast a Auto to Moto and as Auto is not subtype of Moto ClassCastException occurs.

How to safely cast and access child class members?

Using the instanceof operator to first check if the particular type of iteration variable is Binario prior to performing the cast operation:

for(Relacion rel : exprs){
     if(rel instanceof Binario){ // chequeo si rel es Binario.
         Binario bin = (Binario) rel; // si es Binario puedo castear
         // acceso a sus miembros y metodos
         bin.obtIzq(); 
         bin.obtDer();
         bin.obtOper();
     }
}
    
answered by 26.08.2017 / 03:04
source