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. 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;            v = v * timeSec * 32.174 / this.weightPounds;            return Math.round(Math.sqrt(v) * 0.68);          }        }

There is an obvious commonality between a car and a truck that can be encapsulated in the Vehicle class as the base class.

  1. Create a subclass, called Car:
        public class Car extends Vehicle {          private int passengersCount;          public Car(int passengersCount, int weightPounds,                      int horsepower){            super(weightPounds, horsePower); this.passengersCount = passengersCount; ...

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