Java Reference
In-Depth Information
Hiding Information
Everyclass X exposesan interface (aprotocolconsistingofconstructors,methods,and
creating and communicating with X 's objects).
An interface serves as a one-way contract between a class and its clients , which are
structors and methods, and by accessing fields (typically public static final
face, which would break clients that depend upon the interface.
X alsoprovidesan implementation (thecodewithinexposedmethodsalongwithop-
difiestheinterface. Helper methods aremethodsthatassistexposedmethodsandshould
not be exposed.
of that interface's implementation. You hide the implementation to prevent developers
theimplementationisoftenreferredtoas information hiding .Furthermore,manydeve-
lopers consider implementation hiding to be part of encapsulation.
Java supports implementation hiding by providing four levels of access control,
access control levels tocontrol access tofields, methods, andconstructors, andtwoof
these levels to control access to classes:
Public : A field, method, or constructor that is declared public is accessible
from anywhere. Classes can be declared public as well.
Protected :Afield, method, orconstructor that isdeclared protected isac-
cessible from all classes in the same package as the member's class, as well
as subclasses of that class regardless of package. (I will discuss packages in
Chapter 3 . )
Private : A field, method, or constructor that is declared private cannot be
accessed from beyond the class in which it is declared.
Package-private : In the absence of an access-control reserved word, a field,
themember'sclass.Thesameistruefornon- public classes.Theabsenceof
public , protected , or private implies package-private.
Search WWH ::

Custom Search