Program 7.6: A Car Subclass

class Car extends MotorVehicle {

  int num_wheels = 4;
  int num_doors;

It may look like these classes aren't as complete as the earlier ones, but that's incorrect. Car and Motorcycle each inherit the member variables of their superclass, MotorVehicle. Since a MotorVehicle has a make, model, year, max_speed, weight, price, and num_passengers, Cars and Motorcycles also have makes, models, years, max_speeds, weights, prices, and num_passengers.

Car and Motorcycle are subclasses of MotorVehicle. If you instantiate a Car or a Motorcycle with new, you can use that object anywhere you can use a MotorVehicle, because Cars are MotorVehicles. Similarly you can use a Motorcycle anywhere you can use a MotorVehicle.

The converse is not true. Although all Cars are MotorVehicles, not all MotorVehicles are Cars. Some are Motorcycles. Therefore if a method expects a Car you shouldn't give it a MotorVehicle instead.

Copyright 1996 Elliotte Rusty Harold
This Chapter