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= ...
}