Problem with Java-interface

4

When I implement an interface in different classes I do not know how to access a variable of any of the classes

public interface Enganchable {

    void enganchar(Enganchable E);

    void desenganchar();
}
public class Locomotora implements Enganchable {
    public int numero;
    public Enganchable primerVagon;
}
public class Tren {
    public Enganchable locomotora;
    public Enganchable ultimoVagon;
}   

assuming I would like to do this later

t1.locomotora.numero = Integer.valueOf(kboar.nextLine());

I have an error in number and I do not know how to access it to modify it ...

    
asked by Shiki 09.04.2018 в 11:16
source

2 answers

4

The only way would be to modify the attribute type:

Class Tren has two attributes Enganchable : locomotora and ultimoVagon .

Assuming the wagons are of the class Vagon and meet the interface Enganchable , but do not have número , you could do something like

Tren t= new Tren();
t.locomotora= new Vagon();

As you can see, nothing ensures that the attribute object locomotora has the attribute numero , so Java will not let you try to use it.

The solution is simple:

It is logical that Locomotora implement Enganchable , but if the attribute is already named like this, locomotora , it is logical to think that you should only accept the% Locomotora :

public class Tren {
    public Locomotora locomotora;
    public Enganchable ultimoVagon;
}

This forces you to have a locomotive (which sounds logical), but it allows you to put a second locomotive as an Engachable object more.

You could also do a casting, but since the locomotive will always be a locomotive, I see it as unnecessary:

Locomotora loco = (Locomotora) t1.locomotora;

If you go through the list of Enganchables , you can search the locomotives like this:

Enganchable aux=... //asignas el siguiente Enganchable de tu tren

if (aux instanceof Locomotora) {
    Locomotora l = (Locomotora) aux;
    l.numero= ...
}
    
answered by 09.04.2018 / 11:32
source
0

To access the ates of a class you have to generate the Gets and Sets,

Ex;

public class Tren {
public Enganchable locomotora;
public Enganchable ultimoVagon;

public Enganchable getLocomotora(){
return locomotora;
 }
}  

and to access, from another class, you have to create an instance towards the object of that class;

 Enganchable nombreVariable;
 Tren miTren = new Tren();
 nombreVariable =   miTren.getLocomotora();
    
answered by 09.04.2018 в 11:35