To do this you need to be able to send information into the Car
class. This is done by passing arguments. For example,
to allow other objects to change the value of the speed
field in a Car
object, the Car
class could provide an accelerate()
method. This method does not allow
the car to exceed its maximum speed, or to go slower than 0 kph.
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;
}
}
The first line of the method is called its signature. The signature
void accelerate(double deltaV)
indicates that accelerate()
returns no value and takes a single argument, a double
which will be referred to as deltaV
inside the method.
deltaV
is a purely formal argument.
Java passes method arguments by value, not by reference.