Java Reference
In-Depth Information
Let's look closely at this example. Inside
FailSoftArray
are defined three
private
mem-
bers. The first is
a
, which stores a reference to the array that will actually hold information.
The second is
errval
, which is the value that will be returned when a call to
get( )
fails.
The third is the
private
method
indexOK( )
, which determines whether an index is within
bounds. Thus, these three members can be used only by other members of the
FailSoftAr-
ray
class. Specifically,
a
and
errval
can be used only by other methods in the class, and
indexOK( )
can be called only by other members of
FailSoftArray
. The rest of the class
members are
public
and can be called by any other code in a program that uses
FailSoftAr-
ray
.
When a
FailSoftArray
object is constructed, you must specify the size of the array and
the value that you want to return if a call to
get( )
fails. The error value must be a value that
would otherwise not be stored in the array. Once constructed, the actual array referred to
by
a
and the error value stored in
errval
cannot be accessed by users of the
FailSoftArray
object. Thus, they are not open to misuse. For example, the user cannot try to index
a
dir-
ectly, possibly exceeding its bounds. Access is available only through the
get( )
and
put( )
methods.
The
indexOK( )
method is
private
mostly for the sake of illustration. It would be harm-
less to make it
public
because it does not modify the object. However, since it is used in-
ternally by the
FailSoftArray
class, it can be
private
.
Notice that the
length
instance variable is
public
. This is in keeping with the way Java
implements arrays. To obtain the length of a
FailSoftArray
, simply use its
length
member.
To use a
FailSoftArray
array, call
put( )
to store a value at the specified index. Call
get(
)
to retrieve a value from a specified index. If the index is out-of-bounds,
put( )
returns
false
and
get( )
returns
errval
.
For the sake of convenience, the majority of the examples in this topic will continue to
use default access for most members. Remember, however, that in the real world, restrict-
ing access to members—especially instance variables—is an important part of successful
vital when inheritance is involved.
Try This 6-1
Improving the Queue Class
You can use the
private
modifier to make a rather important improvement to the
Queue
class developed in
Chapter 5
,
Try This 5-2
.
In that version, all members of the
Queue
class