Class or static Members

Below is a Car class with such a speedLimit field and getSpeedLimit() method.

public class Car {

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

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

  // getter (accessor) methods
  public static double getSpeedLimit() {
    return speedLimit;
  }

  public boolean isSpeeding() {
    return this.speed > speedLimit;
  }

  public String getLicensePlate() {
    return this.licensePlate;
  }

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

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

  // 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 + deltaV;
     if (this.speed > this.maxSpeed) {
       this.speed = this.maxSpeed; 
     }
     if (this.speed <  0.0) {
       this.speed = 0.0; 
     }     
     
  }
  
}

Previous | Next | Top | Cafe au Lait

Copyright 1998, 1999, 2002 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified February 16, 2002