String
field called version
can be used to store the version information and a static method called getVersion()
can return it. Since the version is a property of the class rather than of an object it is properly static.
Below is a Car
class with such a version
field and getVersion()
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
static String version = "1.0";
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 String getVersion() {
return version;
}
public String getLicensePlate() {
return this.licensePlate;
}
public double getMaxSpeed() {
return this.speed;
}
public double getSpeed() {
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;
}
}
}