Use polymorphism . Let's say you have the parent class Vehicle for Bus and Car .
ArrayList<Vehicle> list = new ArrayList<Vehicle>();
You can add objects of types Bus , Car or Vehicle this list, as the IS-A bus, IS-A car and IS-A car.
Extract an object from the list and work by its type:
Object obj = list.get(3); if(obj instanceof Bus) { Bus bus = (Bus) obj; bus.busMethod(); } else if(obj instanceof Car) { Car car = (Car) obj; car.carMethod(); } else { Vehicle vehicle = (Vehicle) obj; vehicle.vehicleMethod(); }
source share