Suppose I have a parent class called MotorVehicle and it has some data members. Then I have two more sub classes called Car, and Truck that extends the parent class MotorVehicle.
Now, in my main method, I have an ArrayList of type MotorVehicle
ArrayList<MotorVehicle> myList = new ArrayList<MotorVehicle>();
Now, my main method is to use methods to ADD, REMOVE, LIST, SAVE, SORT objects from all four classes in an ArrayList of type MotorVehicle.
Will I be able to add an object of type CAR to this list? I am really confused. Below is a sample input (and the object that is created is stored in the 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
The above series of questions create an object of type CAR, and is stored in myList. How does that work? myList isn't of type Car.
I am really confused.
Yes.
As
CarhasMotorVehicleas a parent it will inherit it's methods unless overridden within your declaration ofCar.myListisn't of typeCarbut it is of typeMotorVehicleand sinceCaris a type ofMotorVehicleit could be used.Conversely you could not say
ArrayList<Car> myList = new ArrayList<Car>();and then add aMotorVehicleto the list because some types ofMotorVehiclearen'tCar. All cars are motor vehicles but not all motor vehicles are cars. So if you are grouping motor vehicles then cars can be part of that.It's the same idea as if you had a parent named
Fruitand you hadApplesandOrangesas subclasses. They are bothFruitand may have acolour,tasteetc... but if you have an array ofApplesthen anOrangecannot belong.