Changing the Implementation

Suppose the Car class needs to be used in a simulation of New York City traffic in which each actual car on the street is represented by one Car object. That's a lot of cars. As currently written each car object occupies approximately 60 bytes of memory (depending mostly on the size of the license plate string. We can knock off eight bytes per car by using floats instead of doubles, but the interface can stay the same:

public class Car {

  private String licensePlate; // e.g. "New York A456 324"
  private float speed;        // kilometers per hour
  private float maxSpeed;     // kilometers per hour
  
  public Car(String licensePlate, double maxSpeed) {

    this.licensePlate = licensePlate; 
    this.speed = 0.0F;
    if (maxSpeed >= 0.0) {
      this.maxSpeed = (float) maxSpeed;
    }
    else {
      maxSpeed = 0.0F;
    }
    
  }

  // getter (accessor) methods
  public String getLicensePlate() {
    return this.licensePlate;
  }

  public double getSpeed() {
    return this.speed;
  }

  public double getMaxSpeed() {
    return this.maxSpeed;
  }

  // setter method for the license plate property
  public void setLicensePlate(String licensePlate) {
    this.licensePlate = licensePlate;
  }

  // accelerate to maximum speed
  // put the pedal to the metal
  public void floorIt() {
    this.speed = this.maxSpeed;  
  }
  
  public void accelerate(double deltaV) {

     this.speed = this.speed + (float) deltaV;
     if (this.speed > this.maxSpeed) {
       this.speed = this.maxSpeed; 
     }
     if (this.speed <  0.0) {
       this.speed = 0.0F; 
     }     
     
  }
  
}

Since the interface is the same, no other classes that depend on this class need to change or even be recompiled. We might save even more by using a custom LicensePlate class that only allowed one-byte ASCII characters instead of two byte Unicode characters.


Previous | Next | Top | Cafe au Lait

Copyright 1997-1999, 2001 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified September 4, 2001