Program 7.2: The Car Class

Code reusability is claimed to be a key advantage of OOP languages over non-object-oriented languages. Inheritance is the mechanism by which this is achieved. An object can inherit the variables and methods of another object. It can keep those it wants, and replace those it doesn't want.

For instance suppose there is a class which represents a car. A car has a make, a model, a year, a maximum speed, a weight, a price, a number of passengers it can carry, four wheels, either two or four doors and many other properties you can represent with member variables. Here's how you might write a class definition for a car:

class Car {

  String make;
  String model;
  int year;
  int max_speed;
  int weight
  float price;
  int num_passengers;
  int num_wheels = 4;
  int num_doors;

}
Obviously this doesn't exhaust everything there is to say about a car. Which properties you choose to include in your class depends on your application.


Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home