Java Reference
In-Depth Information
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 = "<unnamed>";
public Body orbits = null;
private static long nextID = 0;
Body() {
idNum = nextID++;
}
public long getID() {
return idNum;
}
//...
}