
上QQ阅读APP看书,第一时间看更新
There's more...
Let's try to model a crew cab—a truck with multiple passenger seats that combines the properties of a car and a truck. Java does not allow multiple inheritances. This is another case where an interface comes to the rescue.
The CrewCab class may look like this:
public class CrewCab extends VehicleImpl implements Car, Truck {
private int payloadPounds;
private int passengersCount;
private CrewCabImpl(int passengersCount, int payloadPounds,
int weightPounds, int horsePower) {
super(weightPounds + payloadPounds + passengersCount * 250,
horsePower);
this.payloadPounds = payloadPounds;
this. passengersCount = passengersCount;
}
public int getPayloadPounds(){ return payloadPounds; }
public int getPassengersCount() {
return this.passengersCount;
}
}
This class implements both interfaces—Car and Truck—and passes the combined weight of the vehicle, payload, and passengers with their luggage to the base class constructor.
We can also add the following method to FactoryVehicle:
public static Vehicle buildCrewCab(int passengersCount,
int payload, int weightPounds, int horsePower){
return new CrewCabImpl(passengersCount, payload,
weightPounds, horsePower);
}
The double nature of the CrewCab object can be demonstrated in the following test:
public static void main(String... arg) {
double timeSec = 10.0;
int horsePower = 246;
int vehicleWeight = 4000;
Properties drivingConditions = new Properties();
drivingConditions.put("roadCondition", "Wet");
drivingConditions.put("tireCondition", "New");
SpeedModel speedModel =
FactorySpeedModel.generateSpeedModel(drivingConditions);
Vehicle vehicle = FactoryVehicle.
buildCrewCab(4, 3300, vehicleWeight, horsePower);
vehicle.setSpeedModel(speedModel);
System.out.println("Payload = " +
((Truck)vehicle).getPayloadPounds()) + " pounds");
System.out.println("Passengers count = " +
((Car)vehicle).getPassengersCount());
System.out.println("Crew cab speed (" + timeSec + " sec) = "
+ vehicle.getSpeedMph(timeSec) + " mph");
}
As you can see, we can cast the object of the CrewCub class to each of the interfaces it implements. If we run this program, the results will be as follows:
