Examples of Access Protection

This is how the Car class would probably be written in practice. Notice that all the fields are now declared private, and they are accessed only through public methods. This is the normal pattern for all but the simplest classes.

public class Car {

  private String licensePlate; // e.g. "New York A456 324"
  private double speed;        // kilometers per hour
  private double maxSpeed;     // 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 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 + deltaV;
     if (this.speed > this.maxSpeed) {
       this.speed = this.maxSpeed; 
     }
     if (this.speed <  0.0) {
       this.speed = 0.0; 
     }     
     
  }
  
}

In many cases there will also be private, protected and default access methods as well. Collectively these are called non-public methods.

In many cases, the fields may be protected or default access. However public fields are rare. This allows programmers to change the implementation of a class while still maintaining the same contract with the outside world.

Dynamic vs static linking.


Previous | Next | Top | Cafe au Lait

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