Java Reference
In-Depth Information
// constructors omitted ...
public long getID() { return idNum; }
public String getName() { return name; }
public void setName(String newName) {
name = newName;
}
public Body getOrbits() { return orbits; }
public void setOrbits(Body orbitsAround) {
orbits = orbitsAround;
}
}
Making a field final can be another way to prevent unwanted modific-
ations to a field, but immutability and accessibility should not be con-
fused. If a field is immutable then it should be declared final regardless
of accessibility. Conversely, if you don't want a field to form part of the
contract of a class you should hide it behind a method, regardless of
whether the field is read-only or modifiable.
Now that we have made all the fields of Body private, we can return to
an earlier remark that access control is per-class not per-object. Sup-
pose that a body could be captured by another body and forced to orbit
around it, we could define the following method in Body :
public void capture(Body victim) {
victim.orbits = this;
}
If access control were per-object, then the capture method when invoked
on one object would not be able to access the private orbits field of the
victim body object to modify it. But because access control is per-class,
the code of a method in a class has access to all the fields of all objects
of that classit simply needs a reference to the object, such as via a para-
 
Search WWH ::




Custom Search