Exercise 2.13: Make the fields in your Vehicle class private, and add accessor methods for the fields.
Which fields should have methods to change them, and which should not?
Exercise 2.14: Make the fields in your LinkedList class private, and add accessor methods for the
fields. Which fields should have methods to change them, and which should not?
Exercise 2.15: Add a changeSpeed method that changes the current speed of the vehicle to a passed-in
value and add a stop method that sets the speed to zero.
Exercise 2.16: Add a method to LinkedList to return the number of elements in a list.
2.7. this
You have already seen (on page 52) how you can use an explicit constructor invocation to invoke another one
of your class's constructors at the beginning of a constructor. You can also use the special object reference
this inside a non-static method, where it refers to the current object on which the method was invoked.
There is no this reference in a static method because there is no specific object being operated on.
The this reference is most commonly used as a way to pass a reference to the current object as an argument
to other methods. Suppose a method requires adding the current object to a list of objects awaiting some
service. It might look something like this:
service.add(this);
The capture method in class Body also used this to set the value of the victim's orbits field to the
current object.
An explicit this can be added to the beginning of any field access or method invocation in the current
object. For example, the assignment to name in the Body class two-argument constructor
name = bodyName;
is equivalent to the following:
this.name = bodyName;
Conventionally, you use this only when it is needed: when the name of the field you need to access is
hidden by a local variable or parameter declaration. For example, we could have written the two-argument
Body constructor as
public Body(String name, Body orbits) {
this();
this.name = name;
this.orbits = orbits;
}