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

How to do it...

  1. Look at the Vehicle class:
        public class Vehicle {
private int weightPounds, horsePower;
public Vehicle(int weightPounds, int horsePower) {
this.weightPounds = weightPounds;
this.horsePower = horsePower;
}
public double getSpeedMph(double timeSec){
double v = 2.0 * this.horsePower * 746 *
timeSec * 32.17 / this.weightPounds;
return Math.round(Math.sqrt(v) * 0.68);
}
}

The functionality implemented in the Vehicle class is not specific to a car or to a truck, so it makes sense to use this class as a base class for the Car and Truck classes, so each of them gets this functionality as its own.

  1. Create the Car class:
        public class Car extends Vehicle {
private int passengersCount;
public Car(int passengersCount, int weightPounds,
int horsepower){
super(weightPounds, horsePower);
this.passengersCount = passengersCount;
}
public int getPassengersCount() {
return this.passengersCount;
}
}
  1. Create the Truck class:
         public class Truck extends Vehicle {
private int payload;
public Truck(int payloadPounds, int weightPounds,
int horsePower){
super(weightPounds, horsePower);
this.payload = payloadPounds;
}
public int getPayload() {
return this.payload;
}
}

Since the Vehicle base class has neither an implicit nor explicit constructor without parameters (because we have chosen to use an explicit constructor with parameters only), we had to call the base class constructor super() as the first line of the constructor of every subclass of the Vehicle class.