Explain final fields ?
You may also declare fields to be final. This is not the similar thing as declaring a method or class to be final. While a field is declared final, it is a constant that will not and cannot change. It can be set once (for instance when the object is constructed, other than it cannot be changed after that.) Attempts to change it will produce either a compile-time error or an exception (depending on how sneaky the attempt is).
Fields in which are both final, static, and public are effectively named constants. For example a physics program might describe Physics.c, the speed of light as
public class Physics {
public static final double c = 2.998E8;
}
In the SlowCar class, the speedLimit field is likely to be both final and static by it's private.
public class SlowCar extends Car {
private final static double speedLimit = 112.65408; // kph == 70 mph
public SlowCar(String licensePlate, double speed, double maxSpeed,
String make, String model, int year, int numberOfPassengers, int numDoors) {
super(licensePlate,
(speed < speedLimit) ? speed : speedLimit,
maxSpeed, make, model, year, numberOfPassengers, numDoors);
}
public void accelerate(double deltaV) {
double speed = this.speed + deltaV;
if (speed > this.maxSpeed) {
speed = this.maxSpeed;
}
if (speed > speedLimit) {
speed = speedLimit;
}
if (speed < 0.0) {
speed = 0.0;
}
this.speed = speed;
}
}