Constraints

One of the reasons to use constructors and setter methods rather than directly accessing fields is to enforce constraints. For instance, in the Car class it's important to make sure that the speed is always less than or equal to the maximum speed and that both speed and maximum speed are greater than or equal to zero.

You've already seen one example of this in the accelerate() method which will not accelerate a car past its maximum speed.

  void accelerate(double deltaV) {

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

You can also insert constraints like that in the constructor. For example, this Car constructor makes sure that the maximum speed is greater than or equal to zero:

 Car(String licensePlate, double maxSpeed) {

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

Previous | Next | Top | Cafe au Lait

Copyright 1998, 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified June 8, 1999