0
All right guys I’m having a doubt about inheritance, for example:
List<Carros> carros = new ArrayList<>();
Chevete chevete = new Chevete();
chevete.acelerarMuito(); //Até aqui ok
carros.add(chevete);//Adicionando chevete numa lista de carros
carros.get(0).??? //Não consigo mais usar o método acelerar
How to proceed? My intention is to have a List with inherited objects, but I need to use the methods specific to each accessing by . get(index)
I don’t want to create a list for every car model. Suppose the accelerator method exists only in Chevete, so I didn’t create in the Car class.
Look, if I understand correctly, you want to store subtypes in the same list and access their unique methods from the list. This will give you trouble! From the moment you generalize the type of the list, there is no way to guarantee if the Car object is Chevete, Corsa, or whatever. If you need more specifics, make the method common to everyone in the superclass. A solution, very dirty by the way, would be to check if the current object accessed is an instance of Chevete, and if so, force the cast, but I don’t remember now if java will allow it.
– user28595
Carros
can be an interface with the methods you want to make available in a generic way. In classChevete
you implement the interface.– Camilo Santos