Skip to content
Advertisement

How to cast an object of an ArrayList of objects (of type superclass) to an object of type subclass

If I have a superclass, let’s call it Car, with the constructor parameters String name, String color, double wheelSize, and a subclass of this, let’s call it Truck, with the constructor parameters String name, String color, double wheelSize, and double truckBedArea, and in the subclass (Truck), I have a method called modifyCar with the paramaters Car car, String newName, String newColor, double newWheelSize, and double newTruckBedArea, how can I find a way to take that Car object and specify that it is indeed a Truck, so I can then use a Truck setter (setTruckBedArea) to set the new truck bed area? This example isn’t a great comparison to my actual assignment, but I have an ArrayList field of my superclass (Cars) called “ArrayList cars” of “Car” objects, and I need to find a way to change that “Car” object in this ArrayList field, which I have already found a way of doing. I simply loop through each item in the ArrayList of “Cars” until it equals the instance of the Car put in as a parameter, and if it does, I then say “cars.get(i).//setter” (essentially). However, it would not work if I say “cars.get(i).setTruckBedArea(newTruckBedArea)”. I am not sure how to cast the Car object within this list of Cars to a Truck specifically, so I can then access the setter I want to use. The main issue is that I am required to implement an interface (let’s call it “Vehicle”) wherein the ArrayList cars has to be of type cars, since it is specified to be that in the Vehicle interface (otherwise I would just change the ArrayList field to be ArrayList trucks).

Example:

public class Truck implements Vehicle { //have to implement this interface
    //... other fields
    private ArrayList<Car> cars;
    //... other methods/constructors
    public void modifyCar(Car car, String newName, String newColor, double newWheelSize, double newTruckBedArea) { 
//have to have "Car car" as parameter for this method because of interface
        for (int i = 0; i < cars.size(); i++) {
            if (cars.get(i).equals(car)) {
                cars.get(i).setColor(newColor);
                cars.get(i).setName(newName);
                cars.get(i).setWheelSize(newWheelSize);
                cars.get(i).setTruckBedArea(newTruckBedArea); //will produce error
            }
        }
    }
}

Advertisement

Answer

As far as I understand the question, you can use “instanceof” operator:

   if(cars.get(i) instanceof Truck){
       Truck truck = (Truck) cars.get(i);
       truck.setTruckBedArea(newTruckBedArea);
   }

instanceof operator returns a boolean value in result of whether an object is an instance of given type or not.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement