Limited access

Upgrade to access all content for this subject

Consider the following classes.

public class Car
{
    private String make;
    private String model;    
    private int distance;
    private int gallons;

    public Car(String mk, String md, int dist, int gals)
    {
        make = mk;
        model = md;
        distance = dist;
        gallons = gals;
    }

    public String getMake()   // Get the Car make
    {
        return make;
    }

    // other methods not shown
}

public class Baby 
{
    private String firstName;
    private String lastName;
    private double weight;

    public Baby(String firstName, String lastName, double weight)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.weight = weight;
    }

    public double getWeight()
    {
        return weight;
    }

    // other methods not shown
}

And given this method:

public static String processArrayList(ArrayList list)
{
    String sentence = "";
    for (int i=0; i<list.size(); i++)
    {
        if (list.get(i) instanceof Car)
            sentence += ((Car) list.get(i)).getMake();
        else
        if (list.get(i) instanceof String)
            sentence += (String) list.get(i);
        else
        if ( ! (list.get(i) instanceof Baby)) 
            sentence +=list.get(i);
    }
    return sentence;
}

What will the following code segment print?

ArrayList list = new ArrayList();
list.add("doctor");
list.add(10);
list.add(new Car("Honda", "Accord", 120, 4));
list.add(new Baby("Kristen", "Powell", 7.0));
System.out.println(processArrayList(list));
A

An error will be thrown when adding multiple data types to the array list.

B

An error will occur when trying to cast an element to either a Car or Baby object.

C
Hondadoctor10
D
doctor10Honda
E
doctor10HondaKristen
Select an assignment template