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
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 = 123.45; // in kilometers per hour
// getter (accessor) methods
String getLicensePlate() {
return this.licensePlate;
}
double getMaxSpeed() {
return this.maxSpeed;
}
double getSpeed() {
return this.speed;
}
// setter method for the license plate property
void setLicensePlate(String licensePlate) {
this.licensePlate = licensePlate;
}
// setter method for the maxSpeed property
void setMaximumSpeed(double maxSpeed) {
if (maxSpeed > 0) this.maxSpeed = maxSpeed;
else this.maxSpeed = 0.0;
}
// 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;
}
}
}