Returning Multiple Values From Methods

It is not possible to return more than one value from a method. You cannot, for example, return the licensePlate, speed and maxSpeed fields from a single single method. You could combine them into an object of some kind and return the object. However this would be poor object oriented design.

The right way to solve this problem is to define three separate methods, getSpeed(), getMaxSpeed(), and getLicensePlate(), each of which returns its respective value. For example,

class Car {

  String licensePlate = "";    // e.g. "New York 543 A23"
  double speed        = 0.0;   // in kilometers per hour
  double maxSpeed;    = 120.0; // in kilometers per hour
  
  // getter (accessor) methods
  String getLicensePlate() {
    return this.licensePlate;
  }

  double getMaxSpeed() {
    return this.maxSpeed;
  }

  double getSpeed() {
    return this.speed;
  }

  // accelerate to maximum speed
  // put the pedal to the metal
  void floorIt() {
    this.speed = this.maxSpeed;  
  }
  
  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
Last Modified February 7, 1999
Copyright 1998, 1999 Elliotte Rusty Harold
elharo@metalab.unc.edu