java ArrayList contains different objects

前端 未结 5 1297
攒了一身酷
攒了一身酷 2020-12-09 06:28

Is it possible to create ArrayList list = new ArrayList();

I mean add obje

5条回答
  •  悲哀的现实
    2020-12-09 06:48

    Get use of polymorphism. Let's say you have a parent class Vehicle for Bus and Car.

    ArrayList list = new ArrayList();
    

    You can add objects of types Bus, Car or Vehicle to this list since Bus IS-A Vehicle, Car IS-A Vehicle and Vehicle IS-A Vehicle.

    Retrieving an object from the list and operating based on 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();
    }
    

提交回复
热议问题