Java Reference
In-Depth Information
you would not be able to compile this program because of the access violation. Although
access to alpha by code outside of MyClass is not allowed, methods defined within
MyClass can freely access it, as the setAlpha( ) and getAlpha( ) methods show.
The key point is this: A private member can be used freely by other members of its class,
but it cannot be accessed by code outside its class.
To see how access control can be applied to a more practical example, consider the fol-
lowing program that implements a “fail-soft” int array, in which boundary errors are pre-
vented, thus avoiding a run-time exception from being generated. This is accomplished by
encapsulating the array as a private member of a class, allowing access to the array only
through member methods. With this approach, any attempt to access the array beyond its
boundaries can be prevented, with such an attempt failing gracefully (resulting in a “soft”
landing rather than a “crash”). The fail-soft array is implemented by the FailSoftArray
class, shown here:
Search WWH ::




Custom Search