you canít touch that!
means no one can access that member except that particular class, inside
methods of that class. Other classes in the same package cannot access private members, so itís as if youíre
even insulating the class against yourself. On the other hand, itís not
unlikely that a package might be created by several people collaborating
together, so private allows you to
freely change that member without concern that it will affect another class in
the same package. The default ďfriendlyĒ package access is often an adequate
amount of hiding; remember, a ďfriendlyĒ member is inaccessible to the user of
the package. This is nice, since the default access is the one that you normally
use. Thus, youíll typically think about access for the members that you
explicitly want to make public for
the client programmer, and as a result, you might not initially think youíll use the private keyword often since itís tolerable to get away without it.
(This is a distinct contrast with C++.) However, it turns out that the
consistent use of private is very important,
especially where multithreading is concerned. (As youíll see in Chapter 14.)
Hereís an example of the use of private:
// Demonstrates 'private'
static Sundae makeASundae()
public class IceCream
This shows an example in which private comes in handy: you might want
to control how an object is created and prevent someone from directly accessing
a particular constructor (or all of them). In the example above, you cannot create
a Sundae object via its constructor;
instead you must call the makeASundae( )
method to do it for you.
Any method that youíre certain is only a
ďhelperĒ method for that class can be made private
to ensure that you donít accidentally use it elsewhere in the package and thus
prohibit you from changing or removing the method. Making a method private guarantees that you retain this
option. (However, just because the handle is private doesn't mean that some other object can't have a public handle to the same object. See
Chapter 12 for issues about aliasing.)