Tải bản đầy đủ

Charles river media algorithms and data structures the science of computing jun 2004 ISBN 1584502509


A.6PACKAGES
ProgrammersarefreetowritetheirownlibrariesofJavaclasses,andtoshare
thoselibrarieswithotherprogrammers.Forexample,wehavewrittenalibrary
thatcontainsclassesList,OrderedTree,LineDrawing,etc.forthisbook.As
programmersallaroundtheworldwritetheirownJavalibraries,therewill
inevitablybenameconflicts—situationsinwhichtwopeopleusethesamename
toidentifydifferententities.
Java'spackagesareamechanismforreducingnameconflicts.Apackageisa
collectionofrelatedclasses.Programmersplaceaclassinapackagebyputtinga
specialpackagestatementatthebeginningofthefilethatdefinestheclass.All
membersofapackagehavenamesthat,technically,includethepackagename.
Forexample,theclassesthataccompanythisbookareallinapackagenamed
geneseo.cs.sc.ThefullnameoftheListclassthataccompaniesthisbookis
thereforegeneseo.cs.sc.List.[5]

A.6.1UsingClassesfromaPackage
Inordertouseclassesfromapackage,thoseclassesmustbeinstalledonyour
computer.Unfortunately,exactlywhat"installed"meansdependsonyourJava
programmingenvironment:insomeenvironments,"installed"meansthatfiles
containingthecompiledclasseshavetobepresentinspecificdirectories,in

otherenvironmentsitmeansthateitherthecompiledorsourcefilesmustbe
listedin"projectfiles"thatdescribeyourprogram,etc.Consultyourinstructor,
orthedocumentationforyourprogrammingenvironment,ifyouwanttoinstall
packagesforyourself.
Onceclassesdefinedinapackageareinstalledonyourcomputer,youmayuse
thembywritingouttheirfullnamesinyourownprograms.Forexample,you
coulddeclareaninstanceofthisbook'sListclassbywritingcodesuchas:
geneseo.cs.sc.ListaList=newgeneseo.cs.sc.List();

Suchcodequicklybecomespainfultowriteandhardtoread.Javatherefore
providesawaytoimportsomeorallofapackage'sdefinitionsintoasourcefile.
Afterimportingadefinition,codeinthatfilecanrefertotheimportedentityby
itsshortname.Forexample,afterimportinggeneseo.cs.sc.Listviathestatement:


importgeneseo.cs.sc.List;

youcouldwritetheabovedeclarationasjust:
ListaList=newList();

Toimportasingleclassintoafile,youwriteastatementoftheform:
import.;
atthebeginningofthefile.Inthistemplate,isapackagename,and
isthenameoftheclassyouwanttoimport.Forexample:
importgeneseo.cs.sc.List;

Toimporteveryclassinapackage,useanimportstatementoftheform:
import.*;

whereisthenameofthepackage.Forexample:
importgeneseo.cs.sc.*;

Afilecancontainmultipleimportstatements,ifyouneedtoimportmultiple
classes,orneedtoimportfrommultiplepackages.
[5]Packagesonlysolvetheproblemofnameconflictsifpackagenames

themselvesdon'tgiverisetoconflicts.Fortunatelytherearepublished
conventionsfornamingpackagesthatmakesuchconflictsunlikely.





A.5IMPRECISECLASSES
Sometimesaprogramneedsawayofspecifyinganobject'sclassimprecisely.
Forexample,supposeyouwanttodefineadatastructureinwhichyoucanstore
arbitrarykindsofdata—Stringobjects,Counterobjects,Pointobjects,anything
thatsomeonemightsomedayrepresentasanobject.Themessagethatstoresa
pieceofdataintothisstructurecannotdeclarethatdatatobeaninstanceofany
oneoftheseclasses,becausedoingsowouldprecludestoringinstancesofother
classesinthestructure.Norcanyoudeclaredifferentmessagestostoredifferent
kindsofdata,becauseyoucan'tknowwhatclassesfutureclientswilldefineand
wanttostoreinyourdatastructure.Similarproblemsariseindeclaring
messagesthatretrievedatafromthestructure,declaringthestructure'smember
variables,etc.Whatyouneedisawaytodeclareparameters,results,and
membervariablesthatcanbeobjectsofanyclass,notjustoneclass.Java
providesseveralfeaturesthathelpprogrammerswritesuchdeclarations.

A.5.1Class"Object"
Javaprogrammersusetheclasshierarchy(i.e.,superclass/subclassrelationships
betweenclasses)tospecifyclassesimprecisely.Inparticular,somethingdeclared
tobeaninstanceofasuperclasscanactuallybeaninstanceofanyofthat
superclass'ssubclasses(orsubclassesofthesubclasses,etc.).Therefore,ifyou
don'tknowexactlywhatclasssomeobjectwillhave,butyoudoknowthatit
willbeoneofthesubclassesofsomegeneralsuperclass,youcansimplydeclare
theobjecttobeaninstanceofthesuperclass.
ThemostgeneralsuperclassinJavaisObject,whichisthesuperclassofall
otherclasses.Anyclassthatdoesn'textendsomethingelseisautomaticallya
subclassofObject,soeveryclassdescends,eitherdirectlyorindirectly,from
Object.
Forexample,considerasimpledatastructureofthesortsuggestedinthe
introductiontothissection.Thisstructureholdsdatainanarray,providesastore
messagetoaddanitemtothearray,andprovidesaretrievemessagetofetchan
item,givenitspositioninthearray.YoucoulduseObjecttodeclarethese
features,asoutlinedinListingA.6(forthecompleteclassdefinitionandsample
clientcode,seefileSimpleStructure.javaatthisbook'sWebsite).


LISTINGA.6:AnOutlineofaSimpleGenericDataStructureinJava
privateObject[]data;//Thearrayofitems
publicvoidstore(ObjectnewData){//Thestoremethod
...
}
publicObjectretrieve(intindex){//Theretrievemethod
...
}

TheactualvaluesrepresentedbysomethingdeclaredasObjectwillalways
reallybeinstancesofsomesubclassofObject.Forexample,hereisastatement
thataddsaStringtoasimpledatastructurenamedcontainer:
container.store("Thisisastring");

NotethatthisstatementpassesanordinaryStringtostore.Thisisalegaluseof
store,becausestorecanreceiveanyinstanceofObjectasitsparameter,and
StringisasubclassofObject—soallStringobjectsare,indirectly,alsoinstances
ofObject.ClassObjectisneverusedtocreatethevaluestoredinthestructure.

A.5.2Casts
Impreciseclassessometimesleaveaprogrammerknowinganobject'sclassmore
preciselythanisevidentfromaprogram.Forexample,supposeyouareaclient
usingListingA.6'ssimpledatastructuretostorestrings.Yourapplicationwill
thusretrieveonlystringsfromthedatastructure.Unfortunately,however,aJava
compileronlyknowsthattheretrievemessageisdeclaredasreturningObject,it
doesn'tknowhowyourapplicationusesretrieve.Therefore,ifyoutrytosend
stringmessagestotheobjectsyouretrieve,orassignthoseobjectstostring
variables,thecompilerwillreportanerrorandrefusetocompileyourprogram.
Java'ssolutiontothisproblemisacast.Castsletprogrammersassertthatavalue
hasaparticulartype.Thesyntaxforwritingacastis:
()
whereisanexpressionwhoseresultisapparentlyofonetype,and
isanothertypethatreallyhas.Forexample,aclientofthe


simpledatastructurewhoknewthateveryobjectstoredinthestructurewasa
string,andsowantedtoassignobjectsretrievedfromthestructuretoastring
variable,couldwrite:
Stringitem=(String)container.retrieve(i);

Althoughyoucansometimesusecaststoconvertonesimpletypetoanother
(e.g.,youcancastachartoanint,aninttoadouble),youshouldgenerallytreat
acastasapromisebytheprogrammerthatanexpressionproducesaresultofa
differenttypethantheonetheexpression'soperatorsoroperandsimply.You
shouldnotusecaststoconvertvaluesofonetypeintovaluesofadifferenttype.
Tryingtodosocancauseaprogramtoabortwithanerrorcalleda"classcast
exception."

A.5.3Interfaces
AsyouuseeitherthestandardJavalibraries,ortheclassesprovidedwiththis
text,youwillencounterJavadatatypesknownas"interfaces."Likeaclass,an
interfacespecifiesmessagesthatcertainsetsofobjectshandle.Unlikeaclass,
however,aninterfacecannotdefinemethodswithwhichtohandlethese
messages.Instead,otherclasseshavetoimplementtheinterface,meaningthat
theyprovidemethodsforhandlingitsmessages.
Youcanusethenamesofinterfacesasyouwouldusethenamesofclassesto
declareobjectswhoseexactclassisunknown.Objectssodeclaredcanactually
beinstancesofanyclassthatimplementstheinterface.
Youprobablywon'tneedtodefineyourowninterfaceswhileusingthisbook,
butyoumayneedtodeclareclassesthatimplementotherprogrammers'
interfaces(recallthat"implement"inthiscontextisatechnicaltermthatmeans
"providesmethodsforhandlingtheinterface'smessages").Aclassthat
implementsaninterfacehasadeclarationthatlookslike:
classimplements{}
or
classextendsimplements
{}


Inthesetemplates,,,andaretheclass'sname,
thenameofitssuperclass,anddefinitionsofitsmembervariablesandmethods,
exactlyasinotherclassdeclarations.isacomma-separatedlistof
namesofinterfaces.Aclasscanimplementmanyinterfaces,whereasitcanonly
beasubclassofoneclass.Forexample:
classInterfaceExampleimplementsComparable,Serializable{
...
}

(ComparableandSerializableareinterfacesfromtheJavalibrary.Comparable
representsobjectswitha"lessthan"relation.Serializablerepresentsobjectsthat
canbewrittentoandreadfromfiles.)





A.7JAVA'SIMPLEMENTATIONOFOBJECTS
Java'sinternalrepresentationofobjectshassomeconsequencesthatcan
unpleasantlysurpriseprogrammers.Fortunately,knowingsomethingabout
Java'simplementationofobjectsreducesthesesurprises,andleadstomore
effectiveuseofthelanguageingeneral.

A.7.1ObjectVariablesarePointers
ObjectvariablesinJavaaremorecomplicated,withmoresubtlebehaviors,than
simplevariables.Asimplevariableisbasicallyaplaceinthecomputer's
memorytostorethevariable'svalue.Forexample,thestatement
inti=1;

setsasideenoughmemorytoholdoneinteger,notesthathenceforththenamei
meansthatlocationinmemory,andplacesthevalue1intothatlocation.Figure
A.1diagramstheseeffects.
Imagefrombook

FigureA.1:Asimplevariableisa
nameforamemorylocation.
Incontrast,FigureA.2illustratesanobjectvariable.Adeclarationsuchas
SomeClassobj=newSomeClass();

reservestworegionsofmemory.First,thenewoperationsetsasideenough
memorytoholdallthemembersofoneSomeClassobject.Thismemory
includeslocationsthatstorethevaluesoftheobject'smembervariables,and
locationsthatindicatewheretofindthecodefortheobject'smethods.Second,
thedeclarationsetsasideonememorylocation,namedobj,thatholds
informationaboutwhereinmemorytofindthemembers.Suchinformationis
calledapointer.Properlyspeaking,theobjectisthememorythatholdsthe
members;thevariableisonlyapointertotheobject.


Imagefrombook


FigureA.2:Anobjectvariableisapointertotheobject'smembers.

A.7.2AssignmentstoObjectVariables
Thedistinctionbetweenpointersandobjectsshapesthewayassignmentsto
objectvariableswork.Suchassignmentscopypointers,notobjects.Forinstance,
considerthestatements:
SomeClassa=newSomeClass();
SomeClassb=a;

Theassignmentinthesecondstatementcopiesthepointeraintovariableb,but
doesnotmakeacopyoftheobjectapointsto.Intheend,thereisonlyone
object,buttwodifferentvariablespointtoit,asillustratedinFigureA.3.
Imagefrombook


FigureA.3:Assignmentmakestwovariablespointtoasingleobject.
Similarly,whenyoupassanobjectasaparametertoamessage,orreturnan
objectasamessage'sresult,itisreallyapointertotheobject,notacopyofthe
object,thatispassedorreturned.
Assigningpointerswithoutcopyingobjectsmeansthatseveralvariablesor
parametersmayallpointtothesameobject.Oneimportantconsequenceisthat
youmightuseonevariable(orparameter)tochangeanobject,butalsoseethe
changeviaadifferentvariable.Forexample,thefollowingJavastatementsleave
text1andtext2bothbeginningwithlowercaseletters"a",eventhoughthe
programappearstochangeonlytext2(theprogramsendstext2asetCharAt


messageinordertochangeitsfirstcharacter;setCharAtreplacesacharacterina
StringBufferwithanewcharacter,giventhepositionofthecharactertochange):
StringBuffertext1=newStringBuffer("ABCD");
StringBuffertext2=text1;
text2.setCharAt(0,'a');

A.7.3ComparingObjects
Thedistinctionbetweenpointersandobjectsalsoaffectscomparisonsbetween
objects.
The==operatorappliedtotwoobjectstestswhethertwopointersarethesame,
notwhetherthecontentsoftwoobjectsarethesame.Thiscanbeusefulifyou
needtodeterminewhethertworeferencestoobjectsreallyrefertothesame
singleobject,butinothercasesitcanproduceunexpectedresults.Forexample,
considerthiscode:
Stringtext1=newString("XYZ");
Stringtext2=newString("XYZ");
if(text1==text2){
System.out.println("Theobjectsarethesame");
}
else
{
System.out.println("Theobjectsaredifferent");
}

Thiscodewillprint"Theobjectsaredifferent,"eventhoughtext1andtext2
patentlycontainthesamecharacters.Thishappensbecauseeventhoughthey
containthesamecharacters,text1andtext2aredistinctobjects,andsoany
pointerstothemarenotequal(eachnewoperationcreatesanobjectdistinct
fromallothers).
Toseeiftwoobjectshavethesamecontents,usetheequalsmessage.AllJava
objectshandlethismessage.Sendittoanobject,withanotherobjectasthe
message'sparameter.ThemessagereturnsaBooleanresult:generallytrueifthe
twoobjectshavethesamecontents,andfalseotherwise.[6]Forexample,ifyou
replacetheconditionalintheaboveexamplewith:
if(text1.equals(text2))...


theresultingcodewillprint"Theobjectsarethesame."

A.7.4NullPointers
Java'sbuilt-inconstantnullisapointerthatneverpointstoanything.Youcan
thususenullasavalueforvariablesorparametersthatshouldn'trefertoany
object.Youcanalsocomparepointerstonull.
Forexample,ListingA.7presentsaclassthatrepresentsemployeesina
company.Mostemployeeshaveaboss,representedbythebossmember
variable.However,someemployees(e.g.,thecompany'sCEO)don'thavea
boss.TheseemployeeswillberepresentedbyEmployeeobjectswithnullinthe
bossmember.
LISTINGA.7:AJavaClassthatRepresentsEmployees
classEmployee{
privateStringname;//Thisemployee'sname
privateEmployeeboss;//Thisemployee'sboss
//Aconstructor.
publicEmployee(StringemployeesName,EmployeeemployeesBoss){
name=employeesName;
boss=employeesBoss;
}
//FindCEO'sname(i.e.,nameoftheemployeewithnoboss)
publicStringfindCEOName(){
EmployeecurrentEmployee=this;
while(currentEmployee.boss!=null){
currentEmployee=currentEmployee.boss;
}
returncurrentEmployee.name;
}
}

TheconstructorforclassEmployeereceivesanEmployeeobjectasitssecond
parameter.ProgrammerscancreateEmployeeobjectswithnobossbyusingnull
asthevalueforthisparameter.Forexample:
Employeeceo=newEmployee("J.MegaBucks",null);

ThefindCEONamemethodsearchesthroughbosses,bosses'bosses,etc.,untilit


findssomeonewithnoboss.Themethodusesthecomparison:
currentEmployee.boss!=null

tocontinuethesearch.Noticethatcomparisonstonullarenecessarily
comparisonsbetweenpointers,notbetweenobjects'contents,sincenulldoesn't
pointtoanobject.Therefore,youmustalwaysuse!=or==,notanequals
message,insuchcomparisons.
Becausenulldenotestheabsenceofanobject,youcannotsendmessagestonull.
Tryingtodosocausesprogramstoabortwithanerrorknownasa"nullpointer
exception."
[6]Thingsdonot,however,alwaysworkthisway.Classesinheritequalsfrom

Object,andshouldoverridetheinheritedmethodtotestforequalityofcontents
inawayappropriatetotheclass.However,ifaclassdoesn'toverridethe
inheritedequalsmethod,whatitinheritscomparespointersexactlyas"=="does.
Furthermore,evenifaclass'simplementordoesoverrideequals,thereisno
guaranteethattheirmethodbehavesasitissupposedto.





A.4DEFININGCLASSES
Writingobject-orientedprogramsofanyrealcomplexityrequiresdefiningyour
ownclasses.Chapter2discussesclasses,theirmembers,andwhyaprogrammer
wouldwanttodefinetheirownclasses.Toillustratewhatsuchdefinitionslook
likeinJava,ListingA.3showsaclassthatrepresentssimplecounters—objects
thatstoreanintegervaluethattheyincrementinresponsetoincrement
messages.
LISTINGA.3:ACounterDefinedasaJavaClass
classCounter{
privateintvalue;
//Aconstructor
publicCounter(){
value=0;
}
//Incrementacounterbyn
publicvoidincrement(intn){
if(n>0){
value=value+n;
}
}
//Incrementacounterby1
publicvoidincrement(){
this.increment(1);
}
//Reportacounter'scount
publicintgetValue(){
returnvalue;
}
//Changeacounter'scounttoanewvalue
protectedvoidsetValue(intnewValue){
value=newValue;
}
}

A.4.1OverallForm
AclassdeclarationinJavahastheoverallform:


class{}
Inthistemplate,isthenameoftheclass,forexampleCounterforthe
counterclass.isaseriesofdeclarationsofmembervariablesor
methods.Forexample,thestatement:
privateintvalue;

inListingA.3isamembervariabledeclaration,whilethecodesegments
beginning:
publicCounter()...
publicvoidincrement(intn)...
publicvoidincrement()...
publicintgetValue()...

and
protectedvoidsetValue(intnewValue)...

areconstructorormethoddeclarations.

A.4.2MemberVariables
Youmustdeclaremembervariablesbeforeusingthem,justasyoumustdeclare
othervariables.Thesyntaxfordeclaringandusingmembervariablesissimilar
todeclarationanduseofregularvariables,albeitwithafewfeaturesnecessitated
bythefactthatmembervariablesarecontainedinobjects.
Becauseobjectsusuallyencapsulate(i.e.,hide)information,programmershave
todecidewhatcodeisallowedtoaccesseachmembervariable.Canitonlybe
accessedbymethodsintheobject'sclass(a"private"membervariable,fully
encapsulated)?Canitbeaccesseddirectlybyclientsoftheobjectaswellasby
codeintheobject'sclass(a"public"membervariable,noencapsulation)?
Section2.5andSection3.4discusswhymembervariablesshouldgenerallybe
private,butJavadoesn'tforcethemtobe.Javaevenprovidesathirdlevelof
encapsulation,intermediatebetweenpublicandprivate:"protected,"meaning
thatthevariablecanbeaccessedbymethodsintheclass,insubclassesofthe
class,orinthesame"package"astheclass(seeSectionA.6forinformationon
packages).Ineffect,aprotectedmembervariablecanbeaccessedbycodethatis
closelyrelatedtotheclassthatdeclaresthevariable,butnotbyarbitraryclients.


Declarations
Membervariabledeclarationsbeginwithanaccessspecifierthatindicateswhich
otherpartsofaprogramcandirectlyaccessthevariable.Thesyntaxfora
membervariabledeclarationis:
;
whereistheaccessspecifier,andandarethetypeand
nameofthevariable.Someaccessspecifiersinclude:
private,meaningthatthevariableisprivate
public,meaningthatthevariableispublic
protected,meaningthatthevariableisprotected
Forexample,thestatement:
privateintvalue;

inListingA.3declaresanintegermembervariablenamedvaluethatcanonlybe
usedbycodeinsidetheCounterclass.
Access
Refertomembervariablesjustasyouwouldanyvariable.[4]Forexample,the
statement:
value=value+n;

fromListingA.3'sfirstincrementmethodaccessesthevaluemembervariable
oncetofetchitsvalue,andasecondtimetostoretheincrementedvalueback
intothemembervariable.

A.4.3MethodDeclarations
Methoddeclarationslookmuchlikefunctiondeclarationsinotherlanguages.
Syntax


Thetemplateforamethoddeclarationis:
(){}
where
isanaccessspecifier.Javaallowsprogrammerstocontrolwhat
codecansendmessagestoobjects(i.e.,invokemethods),usingexactlythe
sameaccessspecifiers,withthesamemeanings,asformembervariables.
indicateswhattypeofvaluethismethodreturns,ifany.Ifamethod
doesn'treturnanything,usethedummytypevoid.
isthemethod'sname.Themethodwillbeinvokedbyamessageof
thesamename.
isacomma-separatedlistofparameterdeclarations.
Individualparameterdeclarationshaveaformparalleltothatofvariable
declarations,namely:

isthesequenceofstatementstoexecutewhenthismethodis
invoked.
Forexample,thepartofListingA.3thatreads:
publicvoidincrement(intn){
if(n>0){
value=value+n;
}
}

declaresamethodnamedincrement.Thismethodhasoneintegerparameter,and
noreturnvalue.ItcanbeinvokedbyclientsofCounter,orbyothermethods
withinCounter.Wheninvoked,themethodchecksthatitsparameterispositive,
andifso,addstheparametertothevaluemembervariable.
Themethod:
protectedvoidsetValue(intnewValue){
value=newValue;


}

givescodecloselyrelatedtoCounterawaytoarbitrarilychangeacounter's
value,whilegeneralclientscanonlyincrementcounters.Providingspecial
powerstocloselyrelatedcodeisatypicalreasonforusingprotectedmethods.
ReturningValues
ListingA.3'sdeclaration:
publicintgetValue(){
returnvalue;
}

declaresthegetvaluemethod,whichhasnoparametersbutdoesreturnan
integer.Withinthismethod,thestatement:
returnvalue;

iswhatactuallyreturnstheinteger(inthiscase,thecontentsofthevalue
membervariable).Statementsoftheform:
return;
whereisanexpression,causeamethodtoexitandreturnthevalue
computedby.
MultipleMethodswiththeSameName
Aclassmaydefineseveralmethodswiththesamenameaslongastheydifferin
thenumberortypesoftheirparameters.Whenanobjectreceivesamessagewith
thisname,theobjectexecuteswhichevermethodhasthesamenumberandtypes
ofparametersasthemessage.Forexample,ListingA.3containsmethods:
publicvoidincrement(intn){
if(n>0){
value=value+n;
}
}

and


publicvoidincrement(){
this.increment(1);
}

Thesemethodsarebothnamedincrement,butonehasoneparameter,andthe
otherhasnone.Therefore,ifaCounterobjectreceivesanincrementmessage
withoneintegerparameter,thatobjectwillexecutethefirstmethod,whereasif
theobjectreceivesanincrementmessagewithnoparameters,itwillexecutethe
secondmethod.
TheSpecialObject"this"
Withinamethod,thenamethisreferstotheobjectexecutingthemethod(recall
fromSection2.4thatanobjectexecutesamethodwhenthatobjectreceivesa
message—therecipientofthemessage,notthesender,istheobjectthatexecutes
themethod).Forexample,thestatement:
this.increment(1);

inListingA.3'ssecondincrementmethodcausesobjectsexecutingthatmethod
tosendthemselvesanincrementmessagewithparameter1(i.e.,theversionof
incrementthatalwaysincrementsby1simplyinvokesthemoregeneral
incrementwithaparameterthatmakesitincrementby1.Itisimportantthatthe
parameter-lessincrementsendsthemessagethis.increment(1),notjust
this.increment()—thelatterwouldinvoketheparameterlessincrementmethod
again,inanendlessrecursion.)

A.4.4Constructors
Constructors(seeSection3.4)aren'tquitemethods,buttheirdeclarationslook
likemethoddeclarations,exceptfortwothings:
Constructorsmusthavethesamenameastheclasstheyinitialize.
Constructorsdonothavearesulttype.
Forexample,theconstructorfortheCounterclassisdeclared:
publicCounter(){
value=0;
}


Justasclassescanhavemultiplemethodswiththesamename,classescanhave
multipleconstructors.Aswithmethods,theconstructorsmustdifferinthe
numberortypesoftheirparameters.

A.4.5Subclasses
Section2.3explainshowsubclassesarespecializedsubsetsofaclass.Imaginea
subclassofCounterinwhichthecountincreasesfrom0to9,butthenwraps
backto0insteadofpassing10.ListingA.4demonstrateshowonecouldwrite
thissubclassinJava:
LISTINGA.4:ASpecialKindofCounterthatCountsfrom0to9
classOneDigitCounterextendsCounter{
//Aconstructorforone-digitcounters
publicOneDigitCounter(){
super();
}
//Incrementaone-digitcounterbyn
publicvoidincrement(intn){
super.increment(n);
this.setValue(this.getValue()%10);
}
//Reportthemaximumvalueaone-digitcountercanreach
publicintgetMaxValue(){
return9;
}
}

DeclaringaSubclass
Thekeywordextendsinaclassdeclarationmakesthedeclaredclassasubclass
ofsomeotherclass.Thesyntaxis
classextends{}
whereandarethesameasinanyclass,andis
thesuperclass'sname.ClassesinJavacanonlyhaveonesuperclass.


OneDigitCounter'sdeclarationdemonstratesthissyntax,withOneDigitCounter
beingthesubclass,andCounterthesuperclass.ClassOneDigitCounterdefines
itsownconstructorandincrementandgetMaxValuemethods,andinheritsother
featuresfromCounter.
MethodsandMemberVariables
SubclassesinJavaordinarilyinheritallofthefeaturesoftheirsuperclass.In
otherwords,instancesofthesubclasswillhaveallofthemembervariablesand
methodsofthesuperclass(althoughcodeinthesubclassdoesnothavedirect
accesstothesuperclass'sprivatemembervariablesorprivatemethods—itcan
onlyaccessthemindirectly,byinvokingapublicorprotectedmethodthatuses
them).Forexample,OneDigitCounterobjectshandlegetValue,setValue,and
parameterlessincrementmessageswiththesamemethodsthatotherCounter
objectsdo.
Youcanoverrideaninheritedmethodbywritinganewdefinitionofitinthe
subclass.Forexample,ListingA.4overridesCounter'sone-parameterincrement
methodwithonethatwrapsthecountaroundto0whenitreaches10.(This
methodwillbeinvokedbythethis.increment(1)statementintheinherited
parameterlessincrementmethod,whichmeansthatbothincrementmethods
wrapthecountaround,eventhoughListingA.4onlyoverridesoneofthem.)
Asubclasscanalsodefineadditionalmembervariablesormethodsbeyondthose
inheritedfromitssuperclass.Forexample,ListingA.4definesagetMaxValue
methodthatisnotpresentinothercounters.
AccessingSuperclassFeatures
Noticethestatement:
super.increment(n);

inListingA.4'sone-parameterincrementmethod.Thisstatementcausesthe
objectexecutingthatmethod(aOneDigitCounter)tosenditselfanincrement
message,butwiththeadditionalprovisothatthemessageistobehandledby
Counter'sone-parameterincrementmethod(i.e.,bythesuperclass'smethod).
Thewordsuperisanalogoustothewordthis,inthatbothallowtheobject
executingamethodtosenditselfmessages,butsuperalwayshandlesthe


messagewiththemethoddefinedintheobject'ssuperclass,evenifthatmethod
hasbeenoverridden.Thewordsuperisthereforeonlymeaningfulinasubclass.
UsingsuperallowstheincrementmethodinOneDigitCountertousethecode
alreadywrittenforincrementingCounterobjects.Afterwards,thestatement:
this.setValue(this.getValue()%10);

limitstheresultofthisstandardincrementtotherange0through9(becauseof
the%,orremainder,operator).
Aconstructorinasubclasscanusesupertoinvokeoneofthesuperclass's
constructors.Thesyntaxis:
super();
whereisacomma-separatedlistofparameterstothesuperclass's
constructor.Thusthestatement:
super();

inListingA.4'sconstructormeansthataOneDigitCounterinitializesitselfby
simplydoingwhateverisnecessarytoinitializeaCounter.Whenoneconstructor
invokesanotherviasuper,theinvocationofsupermustbethefirststatementin
theinvokingconstructor.

A.4.6StaticMembers
Javaallowsprogrammerstocreateavariableormethodassociatedwithanentire
classratherthanasingleobjectofthatclass.Suchmembervariablesormethods
aredistinguishedbythewordstaticintheirdeclarations.Forexample,Listing
A.5definesbothastaticmethod(printIndented)andastaticmembervariable
(SAMPLE_MESSAGE).
LISTINGA.5:AJavaClassthatProvidesIndentedPrinting
classPrintTools{
publicstaticfinalStringSAMPLE_MESSAGE="Hello";
//Print"msg"indentedby"indent"spaces:
publicstaticvoidprintIndented(Stringmsg,intindent){
for(inti=0;i

System.out.print("");
}
System.out.println(msg);
}
}

Whileeveryobjectinaclasshasitsowncopyofeachoftheclass'sordinary
membervariables,allobjectsshareasinglecopyofeachstaticmembervariable.
Thisisparticularlyusefulwhenthemembervariableisaconstantandso
differentobjectswon'thavedifferentvaluesforit—e.g.,SAMPLE_MESSAGE
inListingA.5.Similarly,staticmethodsaren'texecutedbyobjects.Thus,a
methodthatdoesn'toperateonanobject'sstateanyhow—e.g.,printIndentedin
ListingA.5—iseasierforclientstoinvokeifitisstatic,becauseclientsneedn't
createanobjectinwhichtoinvokethemethod.
Youinvokeastaticmethodwiththesyntax
.()
whereisthenameoftheclassthatdefinesthestaticmethod,
isthenameofthemethod,andisacomma-separatedlistof
argumentstothemethod.Forexample,tocallListingA.5'sprintIndented
method,youwouldwriteastatementsuchas
PrintTools.printIndented("Indentedprinting",4);

Useasimilarsyntaxforaccessingstaticmembervariables,namely:
.
Forexample,torefertoListingA.5'sSAMPLE_MESSAGEmembervariable,
youwouldsay:
PrintTools.SAMPLE_MESSAGE

ThephraseSystem.outthatyouusewhenprintingtextisanotherexample—itis
reallyareferencetoastaticmembervariablenamedoutinaclassnamed
System.
Ingeneral,staticmembershavelimitationsanddangersthatregularmembers


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay

×

×