Java Reference
In-Depth Information
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 ac-
cessor methods. Their use promotes encapsulation of the class's data.
Even if an application doesn't require fields to be read-only, making
fields private and adding methods to set and fetch them enables you to
add actions that may be needed in the future. If programmers can ac-
cess a class's fields directly, you have no control over the values they
will use or what happens when values are changed. Additionally, making
a field part of the contract of a class locks in the implementation of that
classyou can't change the implementation without forcing all clients to
be recompiled. For example, a future version of Body may want to look-
up the ID number in a database indexed by the body's name and not
actually store the ID number in the object at all. Such a change cannot
be made if idNum is accessible to clients. For these reasons, you will see
very few public or protected fields in subsequent examples in this topic.
Methods to get or set a value in an object's state are sometimes said to
define a property of that object. For example, the Body class's getID can
be said to define an ID property for Body objects that is retrieved by the
getID method, and implemented by the idNum field. Some automatic sys-
tems, including those for the JavaBeans component architecture, use
these conventions to provide automatic property manipulation systems;
see Section 25.3 on page 721 . We can and should define the name and
orbits fields to be properties by making them private and providing set
and get methods for them:
class Body {
private long idNum;
private String name = "<unnamed>";
private Body orbits = null;
private static long nextID = 0;
 
Search WWH ::




Custom Search