
上QQ阅读APP看书,第一时间看更新
How to do it...
- Create an Engine class with the horsePower field. Add the setHorsePower(int horsePower) method, which sets this field's value, and the getSpeedMph(double timeSec, int weightPounds) method, which calculates the speed of a vehicle based on the period of time passed since the vehicle began moving, the vehicle weight, and the engine power:
public class Engine {
private int horsePower;
public void setHorsePower(int horsePower) {
this.horsePower = horsePower;
}
public double getSpeedMph(double timeSec, int weightPounds){
double v = 2.0 * this.horsePower * 746 * timeSec *
32.17 / weightPounds;
return Math.round(Math.sqrt(v) * 0.68);
}
}
- Create the Vehicle class:
public class Vehicle {
private int weightPounds;
private Engine engine;
public Vehicle(int weightPounds, Engine engine) {
this.weightPounds = weightPounds;
this.engine = engine;
}
public double getSpeedMph(double timeSec){
return this.engine.getSpeedMph(timeSec, weightPounds);
}
}
- Create the application that will use the preceding classes:
public static void main(String... arg) {
double timeSec = 10.0;
int horsePower = 246;
int vehicleWeight = 4000;
Engine engine = new Engine();
engine.setHorsePower(horsePower);
Vehicle vehicle = new Vehicle(vehicleWeight, engine);
System.out.println("Vehicle speed (" + timeSec + " sec)="
+ vehicle.getSpeedMph(timeSec) + " mph");
}
As you can see, the engine object was created by invoking the default constructor of the Engine class without parameters and with the new Java keyword that allocates memory for the newly created object on the heap.
The second object, vehicle, was created with the explicitly defined constructor of the Vehicle class with two parameters. The second parameter of the constructor is the engine object, which carries the horsePower value set to 246 using the setHorsePower(int horsePower) method.
The engine object contains the getSpeedMph(double timeSec, int weightPounds) method, which can be called by any object (because it is public), as is done in the getSpeedMph(double timeSec) method of the Vehicle class.