Java Reference
In-Depth Information
EXAMPLE:
(continued)
Note that the method
censor
has one regular parameter followed by a specification
for any number of additional string parameters. In this case, all parameters are of
type
String
. However, that first regular parameter (or parameters) in a method
heading can be of any type (or types); they need not match the type of the vararg
specification. We just happen to want the type
String
here.
Because the first parameter is of type
String
and the vararg specification in this
case says the remaining arguments are of type
String
, you might wonder why we
did not omit the first
String
parameter
sentence
, have only a vararg specification,
and then use
unwanted[0]
to serve the same role as
sentence
. If we did so, then the
method
censor
could be called with no arguments at all. A vararg specification allows
any number of arguments, including the possibility of zero arguments. However, we
want to insist that the method
censor
have at least one argument, and the parameter
sentence
ensures that
censor
will always have at least one argument.
Privacy Leaks with Array Instance Variables
In Chapter 5, we explained why it is a compromise of privacy for a class to have an
accessor (or other method) that returns a reference to a private mutable object. As we
noted there, an accessor method should instead return a reference to a
deep copy
of
the private object. (See the Pitfall subsection of Chapter 5 entitled “Privacy Leaks.”)
At the time, we had in mind returning the contents of a private instance variable of a
class type. However, the lesson applies equally well to private instance variables of an
array type.
For example, suppose that you decide that you want an accessor method for the
array instance variable in the class
PartiallyFilledArray
in Display 6.5 . You might
be tempted to define the accessor method as follows:
public double
[] getInsideArray( )
// Problematic version
{
return
a;
}
As indicated in the comment, this definition has a problem, which is this accessor
method allows a programmer to change the array object named by the private instance
variable
a
in ways that bypass the checks built into the mutator methods of the class
PartiallyFilledArray
. To see why this is true,
suppose we added this definition of the
method
getInsideArray
to the class
PartiallyFilledArray
, and then consider the
following code:
PartiallyFilledArray leakyArray =
new
PartiallyFilledArray(10);
double
[] arrayName = leakyArray.getInsideArray( );
The variable
arrayName
and the private instance variable
a
now contain the same
reference, so both
arrayName
and the private instance variable
a
name the same array.
Using
arrayName
as a name for the array named by the private instance variable
a
, we