O'Reilly logo

Java 9 Cookbook by Nick Samoylov, Mohamed Sanaulla

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

  1. Enhance the Truck interface by adding the getPayloadKg() method, which returns the truck payload in kilograms. You can do this without forcing a change in the TruckImpl class that implements the Truck interface inside FactoryVehicle--by adding a new default method to the Truck interface:
        public interface Truck extends Vehicle {          int getPayloadPounds();          default int getPayloadKg(){            return (int) Math.round(0.454 * getPayloadPounds());          }        }

Notice how the new method getPayloadKg() uses the existing getPayloadPounds() method as if the latter is implemented inside the interface too when, in fact, it is implemented by a class inside FactoryVehicle. The magic happens during runtime when this method becomes dynamically bound to the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required