Arraylist of Objects + Inheritance

Asked

Viewed 268 times

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.

  • Carros can be an interface with the methods you want to make available in a generic way. In class Chevete you implement the interface.

1 answer

0

There are two ways to do that. The Cars class has the method acelerar() astrato possessing implementation in each car model:

public abstract class Carro {
   public abstract void acelerar();
}

Or you will need a cast for the specific vehicle model when using the method:

if (carros.get(0) instanceof Chevete) {
   ((Chevete)carros.get(0)).acelerar();
}

As every car accelerates, the first approach makes more sense in this example, but there may be methods specific to a particular model, so the second applies.

  • preciso usar os métodos específicos de cada um acessando pelo .get(index) - I guess you didn’t read this excerpt from the question.

  • I did, so I suggested the second approach with the cast ((Chevete)carros.get(0)).acelerar();

  • The cast in this case is not guaranteed, since he himself said that he will keep different subtypes in the list.

  • He would have to secure the specific type through a if (carros.get(0) instanceof Chevete) to be able to use the cast without risks. Otherwise only using the superclass method.

  • Actually no. Through an interface approach to do this. but escapes the scope of doubt.

  • Certainly interfaces make sense because it would be possible to define methods of a set of models, as Carrosesportivos or something of the genre. But still it would fall into the problem of a generic List and it would be necessary a cast for the interface for the methods to be used.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.