Practice Problems: Working with Interfaces – Solutions
1 Setting up Classes with Interfaces
Here is the collection of shape classes.
2 Understanding Interfaces
Here’s a basic setup of classes and an interface for vehicles. Use this to answer the following question about interfaces.
interface IVehicle { |
// indicate how much a basic tune-up costs |
public double tuneUpCost(); |
|
// determine whether vehicle can hold given num of passengers |
public boolean canCarry(int numPassengers); |
} |
|
class Car implements IVehicle { |
int mileage; |
int year; |
int numDoors; |
|
// constructor goes here |
|
// indicate whether car was built before given year |
boolean builtBefore(int otherYear) { |
return this.year < otherYear; |
} |
} |
|
class Bicycle implements IVehicle { |
int mileage; |
int numGears; |
|
// constructor goes here |
} |
Question: What methods do you need to add to each of Car and Bicycle to get this code fragment to compile (setting aside the missing constructors)?
Answer: The two methods listed in the interface (tuneUpCost and canCarry).
Question: Does having a class implement an interface change how you write its constructor?
Answer: No. Interfaces affect what method you must provide in a class, but they do not impact the constructors.
Question: Should builtBefore be added to the IVehicle interface? Why or why not?
Answer: No. Only methods that make sense for all classes that implement the interface should be included in the interface. builtBefore is not meaningful for bicycles (since they have no information about when they were built).
Question: In the Examples class, you want to define a Bicycle as follows:
___________ newKidsBike = new Bicycle(0, 1);
Which types can you use in the blank line (without causing a compile error just with this single line)?
Answer: Either Bicycle or IVehicle.
Question: Assume you defined a Car object as follows:
IVehicle oldCar = new Car(200000, 1995, 2);
Which methods can you call on oldCar, given the type that you gave it?
Answer: Since oldCar has type IVehicle, you can only call methods that are listed in IVehicle. So you can call tuneUpCost and canCarry, but not builtBefore, even though the builtBefore method is within the oldCar object.
Question: Assume you defined a Car object as follows:
Car oldCar = new Car(200000, 1995, 2);
Which methods can you call on oldCar, given the type that you gave it?
Answer: Since oldCar has type Car, you can only call methods that are defined in the Car class, which must include those listed in IVehicle. You can call each of tuneUpCost, canCarry, and builtBefore,