【发布时间】:2014-11-12 04:03:04
【问题描述】:
假设我有一个名为 MotorVehicle 的父类,它有一些数据成员。 然后我还有两个子类 Car 和 Truck,它们扩展了父类 MotorVehicle。
现在,在我的主要方法中,我有一个 MotorVehicle 类型的 ArrayList
ArrayList<MotorVehicle> myList = new ArrayList<MotorVehicle>();
现在,我的主要方法是使用方法从 MotorVehicle 类型的 ArrayList 中的所有四个类中添加、删除、列表、保存、排序对象。
我能否将 CAR 类型的对象添加到此列表中?我真的很困惑。 下面是一个示例输入(并且创建的对象存储在 arrayList 中):
Enter what you want to do-ADD,REMOVE,LIST,SAVE,SORT: aDd Enter vehicle type- CAR, BUS, TRUCK, OTHER: CaR
Enter the number of wheels: 4
Enter the engine size in cc: 300
Enter true for power steering else false: false
Enter the purchase date as mm/dd/yyyy: 11/22/2002 Enter the vehicle serial number: ADT13478
Enter the number of doors: 2
Enter the car's color: White
以上一系列问题创建了一个CAR类型的对象,并存储在myList中。这是如何运作的? myList 不是 Car 类型。
我真的很困惑。
【问题讨论】:
-
您为什么不尝试将
Car添加到您的ArrayList<MotorVehicle>并查看它是否有效?
标签: java class inheritance extends