this
in constructors
This technique should also be used when one method needs to convert from one type to another. For instance one variant can convert a String
to an int
,
then invoke the variant that takes the int as an argument.
This straight-forward for regular methods, but doesn't quite work for constructors because you can't simply write a method like this:
public Car(String licensePlate, double maxSpeed) {
Car(licensePlate, 0.0, maxSpeed);
}
Instead, to invoke another constructor in the same class from a constructor
you use the keyword this
like so:
public Car(String licensePlate, double maxSpeed) {
this(licensePlate, 0.0, maxSpeed);
}
Must this be the first line of the constructor?For example,
public class Car {
private String licensePlate; // e.g. "New York A456 324"
private double speed; // kilometers per hour
private double maxSpeed; // kilometers per hour
// constructors
public Car(String licensePlate, double maxSpeed) {
this(licensePlate, 0.0, maxSpeed);
}
public Car(String licensePlate, double speed, double maxSpeed) {
this.licensePlate = licensePlate;
if (maxSpeed >= 0.0) {
this.maxSpeed = maxSpeed;
}
else {
maxSpeed = 0.0;
}
if (speed < 0.0) {
speed = 0.0;
}
if (speed <= maxSpeed) {
this.speed = speed;
}
else {
this.speed = maxSpeed;
}
}
// other methods...
}
This approach saves several lines of code. In also means that if you later need to change the constraints or other aspects of construction of cars,
you only need to modify one method rather than two.
This is not only easier; it gives bugs fewer opportunities to be introduced
either through inconsistent modification of multiple methods
or by changing one method but not others.