Give an Examples of Access Protection ?
This is how the Car class would almost certainly be written in practice. Remember that all the fields are now declared private, and they are accessed just by public methods. This is the general pattern for all but the easiest 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 Several cases there will also be private, protected and default access techniques as well. Collectively these are known as non-public methods.
In several cases, the fields may be protected or default access. Therefore public fields are rare. This allows programmers to change the implementation of a class although still maintaining the similar contract with the outside world.
Dynamic vs static linking.