what is constraints explain with exampleone of


What is Constraints explain with example?

One of the purposes to use constructors and setter techniques rather than directly accessing fields is to enforce constraints. For example, in the Car class it's significant to make sure in which the speed is always less than or equal to the maximum speed and in which both speed and maximum speed are greater than or equal to zero.

You've already seen one instance of this in the accelerate() method which will not accelerate a car past its maximum speed.
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;
}
}
You can also insert constraints such as that in the constructor. For instance, this Car constructor makes sure in which the maximum speed is greater than or equal to zero:
Car(String licensePlate, double maxSpeed) {

this.licensePlate = licensePlate;
this.speed = 0.0;
if (maxSpeed >= 0.0) {
this.maxSpeed = maxSpeed;
}
else {
maxSpeed = 0.0;
}
}

Request for Solution File

Ask an Expert for Answer!!
JAVA Programming: what is constraints explain with exampleone of
Reference No:- TGS0284566

Expected delivery within 24 Hours