ArrayList of Objects + Inheritance [duplicate]

0

Well, folks, I have a question 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 specific methods of each one by accessing .get (index)

I do not want to create a List for each car model. Suppose the accelerate method is only present in the chevete, so I did not create it in the Car class.

    
asked by anonymous 08.10.2018 / 14:16

1 answer

0

There are 2 ways to do this. The Cars class has the acelerar() astrato method having implementation in each car model:

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

Or you'll 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 given model, the latter applies.

    
08.10.2018 / 14:26