// Parent class that represents a basic // vehicle feature and function. class Vehicle { int wheels = 4; public void engineStart() { System.out.println("Engine started. . ."); } public void drive() { System.out.println("Driving on the pavement on " + wheels + " wheels."); } } // Subclass that uses the parent class' features // and adds a method unique to this kind of vehicle. class Car extends Vehicle { public Car() { System.out.println("I'm a car:"); } public void doorLock() { System.out.println("Locking all doors."); } } // Subclass that hides the field of the parent // class with its own more appropriate data, and // adds a method unique to this vehicle. class Motorcycle extends Vehicle { // Hides the data of the parent class. int wheels = 2; public Motorcycle() { System.out.println("I'm a motorcycle:"); } public void riding() { System.out.println("Riding on " + wheels + " wheels."); } public void doingaWheelie() { System.out.println("Riding only on one wheel!"); } } // Subclass with additional data, a method // that overrides the parent drive method, // then later calls the parent's drive method // within a method for this subclass. class Truck extends Vehicle { String storageBed1 = "long bed"; String storageBed2 = "short bed"; public Truck() { System.out.println("I'm a truck."); } // This method overrides the parent class // drive method, printing different text. public void drive() { System.out.println("Use either 4-wheel or 2-wheel drive."); } public void showFeatures() { // Use of the super keyword here calls the // drive method of the parent class. If you // omit super, then drive() from this // subclass is called. super.drive(); System.out.println("I have a " + storageBed1 + " for storage."); } } // Class to instantiate the object listed above and // call the parent classes as well as the subclass // methods. public class VehicleTest { public static void main(String[] args) { Car aCar = new Car(); aCar.engineStart(); aCar.drive(); aCar.doorLock(); Motorcycle aMotorcycle = new Motorcycle(); aMotorcycle.engineStart(); aMotorcycle.riding(); aMotorcycle.doingaWheelie(); Truck aTruck = new Truck(); aTruck.engineStart(); aTruck.drive(); aTruck.showFeatures(); } }