I was practicing for AP computer science and came across this question:
Consider the following interface and class declarations. Which of the following can be used to replace /* expression */ so that getTotalMileage returns the total of the miles traveled for all vehicles in the fleet?
public interface Vehicle
{
/** @return the mileage traveled by this Vehicle */
double getMileage();
}
public class Fleet
{
private List<Vehicle> myVehicles;
/** @return the mileage traveled by all vehicles in this Fleet */
public double getTotalMileage()
{
double sum = 0.0;
for (Vehicle v : myVehicles)
{
sum += /* expression */;
}
return sum;
}
// There may be instance variables, constructors, and methods are not shown.
}
Options:
(a) v.getMileage()
(b) getMileage(v)
(c) Vehicle.get(v).getMileage()
(d) myVehicles.get(v).getMileage()
(e) This code will not compile because no methods can be called from a List interface reference variable.
The list myVehicles stores objects of type vehicle right?
If so, Shouldn't there be a compile time error while running this? As we are creating objects of type Vehicles which is an interface.