Java Reference
In-Depth Information
Hiding Information
Everyclass X exposesan interface (aprotocolconsistingofconstructors,methods,and
[possibly]fieldsthataremadeavailabletoobjectscreatedfromotherclassesforusein
creating and communicating with X 's objects).
An interface serves as a one-way contract between a class and its clients , which are
theexternalconstructors,methods,andother(initialization-oriented)classentities(dis-
cussedlaterinthischapter)thatcommunicatewiththeclass'sinstancesbycallingcon-
structors and methods, and by accessing fields (typically public static final
fields,orconstants).Thecontractissuchthattheclasspromisestonotchangeitsinter-
face, which would break clients that depend upon the interface.
X alsoprovidesan implementation (thecodewithinexposedmethodsalongwithop-
tionalhelpermethodsandoptionalsupportingfieldsthatshouldnotbeexposed)thatco-
difiestheinterface. Helper methods aremethodsthatassistexposedmethodsandshould
not be exposed.
Whendesigningaclass,yourgoalistoexposeausefulinterfacewhilehidingdetails
of that interface's implementation. You hide the implementation to prevent developers
fromaccidentallyaccessingpartsofyourclassthatdonotbelongtotheclass'sinterface,
sothatyouarefreetochangetheimplementationwithoutbreakingclientcode.Hiding
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,
wherethreeoftheselevelsareindicatedviaareservedword.Youcanusethefollowing
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,
method,orconstructorisonlyaccessibletoclasseswithinthesamepackageas
themember'sclass.Thesameistruefornon- public classes.Theabsenceof
public , protected , or private implies package-private.
Search WWH ::




Custom Search