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

How to do it...

  1. Add the getWeightKg(int pounds) method implementation:
     public interface Truck extends Vehicle {
int getPayloadPounds();
default int getPayloadKg(){
return (int) Math.round(0.454 * getPayloadPounds());
}
static int convertKgToPounds(int kilograms){
return (int) Math.round(2.205 * kilograms);
}
default int getWeightKg(int pounds){
return (int) Math.round(0.454 * pounds);
}
}
  1. Remove the redundant code by using the private interface method:
    public interface Truck extends Vehicle {
int getPayloadPounds();
default int getPayloadKg(int pounds){
return convertPoundsToKg(pounds);
}
static int convertKgToPounds(int kilograms){
return (int) Math.round(2.205 * kilograms);
}
default int getWeightKg(int pounds){
return convertPoundsToKg(pounds);
}
private int convertPoundsToKg(int pounds){
return (int) Math.round(0.454 * pounds);
}
}