Java 11 Cookbook
上QQ阅读APP看书,第一时间看更新

How it works...

The preceding application produces the following output:

It's worth noticing that the getSpeedMph(double timeSec) method of the Vehicle class relies on the presence of a value assigned to the engine field. This way, the object of the Vehicle class delegates the speed calculation to the object of the Engine class. If the latter is not set (null passed in the Vehicle() constructor, for example), NullPointerException will be thrown at the runtime and, if not handled by the application, will be caught by JVM and force it to exit. To avoid this, we can place a check for the presence of the engine field value in the Vehicle() constructor:

if(engine == null){ 
throw new RuntimeException("Engine" + " is required parameter.");
}

Alternatively, we can place a check in the getSpeedMph(double timeSec) method of the Vehicle class:

if(getEngine() == null){ 
throw new RuntimeException("Engine value is required.");
}

This way, we avoid the ambiguity of NullPointerException and tell the user exactly what the source of the problem was.

As you may have noticed, the getSpeedMph(double timeSec, int weightPounds) method can be removed from the Engine class and can be fully implemented in the Vehicle class:

public double getSpeedMph(double timeSec){
double v = 2.0 * this.engine.getHorsePower() * 746 *
timeSec * 32.17 / this.weightPounds;
return Math.round(Math.sqrt(v) * 0.68);
}

To do this, we would need to add the getHorsePower() public method to the Engine class in order to make it available for usage by the getSpeedMph(double timeSec) method in the Vehicle class. For now, we leave the getSpeedMph(double timeSec, int weightPounds) method in the Engine class.

This is one of the design decisions you need to make. If you think that an object of the Engine class is going to be passed around and used by the objects of different classes (not only Vehicle), you would need to keep the getSpeedMph(double timeSec, int weightPounds) method in the Engine class. Otherwise, if you think that only the Vehicle class is going to be responsible for the speed calculation (which makes sense, since it is the speed of a vehicle, not of an engine), you should implement this method inside the Vehicle class.