halveIt so that the above code would modify the value of one, or so that commonName could change the
variable sirius to null. This is not possible. The Java programming language does not pass objects by
reference; it passes object references by value. Because two copies of the same reference refer to the same
actual object, changes made through one reference variable are visible through the other. There is exactly one
parameter passing modepass by valueand that helps keep things simple.
You can declare method parameters to be final, meaning that the value of the parameter will not change
while the method is executing. Had bodyRef been declared final, the compiler would not have allowed
you to change its value to null. When you do not intend to change a parameter's value, you can declare it
final so the compiler can enforce this expectation. A final declaration can also protect against assigning
a value to a parameter when you intended to assign to a field of the same name. The declaration can also help
the compiler or virtual machine optimize some expressions using the parameter, because it is known to remain
the same. A final modifier on a parameter is an implementation detail that affects only the method's code,
not the invoking code, so you can change whether a parameter is final without affecting any invoking code.
2.6.6. Using Methods to Control Access
The Body class with its various constructors is considerably easier to use than its simple data-only form, and
we have ensured that the idNum is set both automatically and correctly. But a programmer could still mess up
the object by setting its idNum field after construction because the idNum field is public and therefore
exposed to change. The idNum should be read-only data. Read-only data in objects is common, but there is
no keyword to apply to a field that allows read-only access outside the class while letting the class itself
modify the field.
To enforce read-only access, you must either make the field final, which makes it read-only for the lifetime
of the object, or you must hide it. You hide the field by making the idNum field private and providing a
new method so that code outside the class can read its value using that method:
class Body {
private long idNum; // now "private"
public String name = "
public Body orbits = null;
private static long nextID = 0;
Body() {
idNum = nextID++;
}
public long getID() {
return idNum;
}
//...
}
Now programmers who want to use the body's identifier will invoke the getID method, which returns the
value. There is no longer any way for programmers to modify the identifierit has effectively become a
read-only value outside the class. It can be modified only by the internal methods of the Body class.
Methods that regulate access to internal data are sometimes called accessor methods. Their use promotes
encapsulation of the class's data.