java ArrayList contains different objects

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

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

I mean add obje

5条回答
  •  长情又很酷
    2020-12-09 07:05

    Yes you can. But you need a common class to your object types. In your case this would be Vehicle.

    So for instance:

    Vehicle class:

    public abstract class Vehicle {
        protected String name;
    }
    

    Bus class:

    public class Bus extends Vehicle {
        public Bus(String name) {
            this.name=name;
        }
    }
    

    Car class:

    public class Car extends Vehicle {
        public Car(String name) {
            this.name=name;
        }
    }
    

    Main class:

    public class Main {
        public static void main(String[] args) {
            Car car = new Car("BMW");
            Bus bus = new Bus("MAN");
            ArrayList list = new ArrayList();
            list.add(car);
            list.add(bus);
       }
    }
    

提交回复
热议问题