Tải bản đầy đủ

Que using java 2 special edition standard edition dec 2000 ISBN 0789724685

BooleanOperators
MostcontrolflowexpressionsinJavadirectprogramexecution
basedonacomputedtrueorfalsevalue.Forinstance,as
you'llseelaterinthischapter,anif(expression)statement
causesthenextstatementtobeexecutedonlyifexpression
evaluatestotrue.Youcanactuallywritesomethinglikeif
(true),butthisisnotveryusefulingeneral(exceptfor
conceptssuchasconditionalcompilation,whichyou'lllearn
aboutlater).Instead,controlmechanismssuchastheif
statementareusuallydrivenbyaBooleanexpression.
Note
TheuseofthetermBooleaninthischapterrefersto
BooleanlogicingeneralandnottheBooleanclass
foundinJava.Theexpressionsusedinflowcontrol
typicallyevaluatetothetrueandfalseliterals
associatedwiththebooleanprimitivetypeandnot
toanobjectreference.Booleanandbooleanare
usedsomewhatinterchangeablythroughoutthis
chapterdependingonthecontext,butfromaJava
implementationstandpoint,theyarereferringtothe
sametypeofdataorexpression.


OperatorsinJavahaveparticularmeaningswhenusedin
Booleanexpressions.Manyoftheseoperatorsareusedwiththe
otherprimitivetypesasarithmeticandbitwiseoperators.In
mostcases,theBooleanmeaningsareanaturalextensionfrom
theoperationsperformedonintegertypes.Table6.1showsthe
operationsthatcanbeperformedonBooleans.
Table6.1.OperationsonBooleanExpressions

Operation

Name

Description


=

Assignment AsinlightOn=true;.

==

Equality

Thisproducesatrueifthetwo
booleanoperandshavethesame
value(trueorfalse).Itproduces
falseotherwise.Thisisequivalentto
NOTEXCLUSIVEOR(NXOR).

!=

Inequality

Thisproducesatrueifthetwo
booleanoperandshavedifferent
values(onetrue,theotherfalse).It
producesfalseotherwise.Thisis
equivalenttoEXCLUSIVEOR(XOR).

!

Logical
NOT

&

|

^

&&
||
?:

Aunaryoperator.Iftheoperandis
false,theresultistrue,andvice
versa.
AND
Producesatrueifandonlyifboth
operandsaretrue.Fornon-boolean
operands,itisinterpretedasabitwise
operator.
OR
Producesafalseifandonlyifboth
operandsarefalse.Fornon-boolean
operands,itisinterpretedasabitwise
operator.
XOR
Producestrueonlyifexactlyone
(EXCLUSIVEOR)operandistrue.For
non-booleanoperands,itisinterpreted
asabitwiseoperator.
Logical
Sameresultforbooleanoperandsas
AND
describedfor&.
LogicalOR Sameresultforbooleanasdescribed
for|.
if-then-else Usesabooleanexpressionbeforethe
questionmarktodeterminewhichof
twoexpressionstoevaluate.


TheRelationalOperators
Themostintuitivecomparativeoperatorsarethosethatfallinto
acategoryknownasrelationaloperators.Relationaloperators
includethestandardgreater-thanandless-thansymbolsyou
learnedaboutbackinthirdgrade.Convenientlyenough,they
workthesameinJavaastheydidbackinthirdgrade,too.For
instance,youknowthatifyouwrite(3>4),youhavewritten
somethingwrong(afalsestatement).Ontheotherhand,(3<4)
iscorrect(atruestatement).Theseexamplesuseliteralvalues,
whichmakesthemeasytoevaluate,butnotveryusefulina
programbecausetheirresultisknowninadvance,anditis
alwaysthesame.Fortunately,inJavaandotherlanguages,you
arenotlimitedtocomparingconstantswhenyouuserelational
operators;youarefreetousevariables,sothestatement
(accountBalance>minimumBalance)isalsoavalid
relationalexpressionthatprovidesmuchmorepotentialforuse
inaflowcontrolstatement.Theseexpressionsarebuiltusing
theoperatorsshownhere:
Operator
<
<=
>
>=

BooleanResult
Lessthan
Lessthanorequalto
Greaterthan
Greaterthanorequalto

Theprecedenceoftherelationaloperatorsisbelowthatofthe
arithmeticoperators,butabovethatoftheassignment
operator.Thus,thefollowingtwoassignmentstatements
produceidenticalresults:

result1=a+bresult2=((a+b)<(c*d));
Theassociativityofrelationaloperatorsisleft-to-right,butthis


aspectreallyisnotanissuebecausetheycanbeusedonlywith
non-booleanoperands.Itmightnotbeimmediatelyobvious
whatthisimplies,soconsiderthefollowing(illegal)expression:

aUsingleft-to-rightassociativity,theexpressionaevaluatedfirsttoproduceabooleanvalueofeithertrueor
false.Thisvaluewouldthenhavetobecomparedtoc.What
doesitmeantoaskiftrue(orfalse)islessthansomeother
operand?Unlikesomelanguages,abooleaninJavaisnotthe
sameasa0or1oranyothernumber,soarelational
comparisonwithabooleanhasnomeaning.Anexpressionlike
thisresultsinthecompilergeneratingasyntaxerror.
InCandC++,therelationaloperatorsproduceanintegervalue
of0or1,whichcanbeusedinanyexpressionexpectingan
integer.ExpressionssuchasthefollowingarelegalinCorC++
ifthevariablesaredeclaredaccordingly,buttheygenerate
compilererrorsinJava:

dailyRate=rateArray[dayOfWeek<4];
newValue=oldValue+(newRate>oldRate)*interest;
Tryabasicprogramtotestsomeofwhatyouhavejustlearned.
Listing6.1includessomesimpleprintstatementsthat
demonstratetheuseoftherelationaloperatorswith
literals.AnotherconvenientfactofJavaisusedhere:Youcan
concatenatebooleanvalueswithastringusingthe+or+=
operatorandthestringtrueorfalsewillbedisplayedinthe
output.
Listing6.1QuickTest.javaASimpleLessonfromtheThird
Grade


publicclassQuickTest
{
publicstaticvoidmain(Stringargs[]){
System.out.println("5isgreaterthan6:"+(5>
System.out.println("6isgreaterthanorequa
System.out.println("8islessthan10:"+(8<10
}
}
Torunthisprogram,firstcopyListing6.1toafilecalled
QuickTest.java.Asdiscussedinpreviouschapters,it's
importantthefilebecalledQuickTest.javawithall
capitalizationthesame.Next,compiletheprogramusing

javac:

javacQuickTest.java
Afterthefileiscompiled,you'rereadytorunit:

javaQuickTest
Asyoumighthavealreadyguessed,theoutputyougetshould
looklikethis:

0015isgreaterthan6:false
0026isgreaterthanorequalto3:true
0038islessthan10:true
004





TheEqualityOperators
TheequalityoperatorsarethenextsetofBooleanoperatorsin
Java.Equalityoperatorsenableyoutocompareonevalueto
anothertodetermineiftheyarethesame.Inthirdgrade,you
mighthavewrittenanequalitystatementsuchas(3=3).


Unfortunately,inJava,thisstatementwouldcausethecompiler
toattempttousetheassignmentoperatorratherthanevaluate
itasaBooleanexpression.
Theproblemisthatthisisnottheresultyouarelookingfor.It
isalsoacompilererrorwhenusingliteralvaluesbecauseyou
cannotassignanewvaluetothenumber3,evenifitisthe
value3.Tosolvethisproblem,aseparatetwo-character
operator(==)isusedtodistinguishequalitycomparisonsfrom
assignments.InJavathen,youwouldwritetheexpressionas
(3==3).Thiswouldbereadas"threeequalsthree"andwould
produceatrueresultwhenevaluated.Similarly,theexpression
(3==4)wouldevaluatetofalse.
Thetwoequalityoperatorsareverysimilartotherelational
operators,withslightlylowerprecedence:
Operator
==
!=

BooleanResult
Isequalto
Isnotequalto

Theequalityoperatorstakeoperandsofvirtuallyanytypeand
alwaysproduceabooleanresult.Iftheoperandsareprimitive
datatypes,thevaluesoftheoperandsarecomparedto
evaluatetheexpression.However,iftheoperandsareobject
references,thepurposeoftheseoperatorsistodetermineif
bothoperandsrefertoexactlythesameobject.Considerthe
followingexample:

string1==string2
Inthisexpression,string1andstring2mustrefertothe
samestringnottotwodifferentstringsthathappentocontain
thesamesequenceofcharactersfortheexpressiontoevaluate
totrue.ConsiderthelinesshowninListing6.2.


Listing6.2ObjectEquals.javaComparingObjectsinJava

publicclassObjectEquals
{
publicstaticvoidmain(Stringargs[]){
Stringstring1=newString("HiMom");
Stringstring2=newString("HiMom");

//Atthispointstring1isnotequaltostrin
System.out.println("string1==string2

:"+(string1==string2));
Stringstring3=string1;
//Nowstring1isequaltostring2
System.out.println("string1==string3:"+(st
}
}
Giventhissequence,string1==string2returnsfalseafter
thefirsttwolinesdespitethefactthatthetwoobjectsbeing
referencedareinitializedusingequivalentstringliterals.What
mattershereisthattheyarenotthesameobject.Ontheother
hand,string1==string3returnstruebecausethesetwo
variablesrefertoexactlythesameobject.Soasyoumight
havealreadyguessed,theoutputofthisprogramisasfollows:

string1==string2:false
string1==string3:true
Note
Ifyouwanttocomparestring1tostring2based


onthetexttheycontainratherthanwhatobjects
theyreferto,youcanusetheequalsmethodof
String.Thiswouldbewritten
string1.equals(string2),whichwould
evaluatetotrueinthiscase.Theequals()
methodcomparesthestringscharacterbycharacter.
Thismethodisanoverriddenversionoftheone
definedintheObjectclassthatisintroducedlater
inChapter7,"Classes."

Theassociativityoftheequalityoperatorsisagainleft-to-right.
Youhaveseenthattheassociativityoftherelationaloperators
isreallynotmeaningfultoyouasaprogrammer.The
associativityoftheequalityoperatorsisonlyslightlymore
useful.Takealookatthefollowingexample:

startTemp==endTemp==lastRace
Here,thevariablesstartTempandendTemparecompared
firsttoproduceabooleanresult.Thisresultbecomestheleft
operandforacomparisonwithlastRace.Abooleancanonly
becomparedwithanotherbooleanforequality,soacompiler
errorresultshereiflastRaceisanyotherdatatype.
Caution
Althoughthisexpressionisvalidifthefarright
operandisaboolean,youshouldavoidwriting
codethatrequiressuchacarefulexaminationbythe
readertodetermineitscorrectness.Evenifyou
understanditcompletelywhenyouwriteit,chances
areyou'llbeasmystifiedaseveryoneelsewhenyou
trytoreaditafewweeksormonthslater.Trytouse


constructsinyourcodethatareeasilyread.Ifthere
issomereasonthatyoumustuseanexpressionlike
theonejustgiven,besuretousecommentsto
explainhowtheexpressionoperatesand,ifpossible,
whyyouhavechosentoimplementyouralgorithm
thatway.


Chapter7.Classes
byBrianKeeton
Inthischapter
WhatAreClasses?
WhyUseClasses?
ClassesinJava
DeclaringaClass
VariablesDefiningState
MethodsDefiningBehavior
CreatinganInstanceofaClass
ReferringtoClassElements
TheObjectClass
CastingandConvertingReferenceTypes
InnerClasses
Packages
WrappingthePrimitiveTypesinClasses
UsingtheStandardMathematicalFunctions


BuildingaUMLClassDiagram
Troubleshooting


WhatAreClasses?
Classesarethebuildingblocksofanobject-orientedsystem,so
it'simportanttodefinethemandtalkabouthowtheyrelateto
objectsbeforeyoulearntodeclareandusethem.Ononehand,
objectsarerelativelyeasytodefinebecausetheysurroundyou.
Obviously,thisbookyou'rereadingandthekeyboardonwhich
youtypearebothobjects.Theconcretenessofobjectsmakes
theconceptsimpletograspobjectsarespecificthings(persons,
places,ideas,andsoonifyouwanttobecomplete).Turningto
classes,however,youmusttradethisconcreteviewforthe
abstract.
Innearlyeveryaspectoflife,fromsimpleconversationto
scientificresearch,peoplehavefounditeasiertounderstand
objectsandworkwiththemaftertheyhavebeenputinto
categoriesthatmakesimilaritiesanddifferencesclear.The
worldistoocomplexotherwise.ImagineHenryFordtryingto
explainhisplansfortheModelTwhentherewasnosuch
abstractionasa"car"fromwhichtostart.Whenanautomaker
introducesanewmodeltoday,youmightbeanxioustosee
whatitlookslikebutnoonehastotellyouwhatitdoes.When
abstractionsareusedtogroupobjects,thekeyistofocuson
whattheyhaveincommonandignorethewaysinwhichthey
differwhenthosedifferencesareunimportantinagiven
context.
Sohowdoesthisrelatetoclasses?Aclassdefinesan
abstractionusingasetofattributesandbehaviorthat
representswhatiscommonamongobjectsinagroup.Froma
programmingstandpoint,theseattributesarevariablesthat
representstateandyoudefinemethodstoactonthese
variablesasawaytomodelbehavior.Withproperadherenceto
encapsulation,thesemethodsdefineeverythingthatisallowed
intermsofaccessing,using,andchangingthestateofan
object.Anybehaviorthatisimportanttothesystemyou're


buildingshouldbefoundintheclassesyoudesign.
Beforegoinganyfurther,considerthissimpleexample:
Supposeyouhavetodesignasystemtocoordinatethe
stoplightsinabusysectionoftownasawaytoeasetraffic
congestion.Youlookattheproblemandrightawayknowthat
thestoplightsfoundattheaffectedintersectionsarethe
primaryobjectsthatneedtoberepresentedinyoursystem.
Theremightbetensorevenhundredsofindividualstoplights,
butbasedonyourproblem,they'reallthesamewhenitcomes
tostateandbehavior.Withthisinmind,youdecideyouneeda
classnamedStopLight.Thefirststepistodefinevariablesto
holdthestateofaStopLight.Asaninitialpass,youdecide
thatthecolorofthelightistheonlystateofaStopLightthat
therestofyoursystemneedstoknow.Torepresentthisstate,
youselectasingleintegervariablenamedgreenYellowRed
thatwillholdthevalueofthelightcolor.Javaoffersamuch
betterwaythanusinganintegerherebutyou'lllearnabout
thatalittlelater.Giventhesedesignchoices,here'sanexample
classdeclaration:

publicclassStopLight{
/*0->Green
1->Yellow
2->Red
*/
intgreenYellowRed;
}
Thisclassdeclarationisvalidbutitisn'tveryinterestingandit
doesn'tdoanythingtomodelthebehaviorofastoplight.Thisis
wheremethodsareneeded.InthecaseofaStopLightclass,
itislikelythatyouwouldhaveamethodcalled
changeLight(),whichwouldcausethelighttochangefrom
redtogreen(probablybychangingthegreenYellowRed
variable).ThefollowingmodifieddeclarationofStopLight


showshowthisbehaviorisincorporatedintotheclass:

publicclassStopLight{
intgreenYellowRed;
voidchangeLight(){
greenYellowRed=++greenYellowRed%3;
}
}
Note
Todistinguishclassvariableswithvariablesthatare
partsofmethods,classvariablesareoftenreferred
toasfields,orclassscopevariables.Intheprevious
example,thegreenYellowRedvariablewouldbea
fieldoftheStopLightclass.


WhyUseClasses?
Whendealingwithclasses,it'simportanttorememberthat
classesdonotenableprogrammerstodoanythingmorethan
theywouldbeabletodowithoutthem.Althoughitmightbe
significantlymorework,youcouldwriteallOOPprograms
structurally.
Classesareusedforthesamereasonlargecompaniesare
dividedintodepartmentsandthosedepartmentsaredivided
intosubdepartments.Whenacompanyisfacedwithorganizing
hundredsofpeoplearoundhundredsoftasks,adivideand
conquerstrategyistheonlywaytosurvive.Adepartmental
architecturedividestasksintomanageable,andhopefully
related,piecesthatcanbeaddressedbyanappropriategroup
ofstaff.Ifyou'reintheengineeringdepartment,youcareabout
gettingyourpaycheckontime,butyou'reprobablynot
concernedwithhowthepayrollsystemknowshowtohandle
paidholidays.Ifyou'reinthepayrolldepartment,however,you
mightcareagreatdeal.Asfarastherestofthecompanyis
concerned,theprocessingofpaycheckshasbeenfully
encapsulatedwithinthepayrolldepartment.Takingthissame
ideaandmovingitintothesoftwarearenaiswhatOOPdoes
whenresponsibilityisdividedamongclasses.Aswitha
companydepartment,eachclassshouldbeabletodoonething
anddoitwellsotherestofthesystemcanbeassuredthatthe
assignedtasksarecarriedout.
InOOP,encapsulationisachievedbyenclosingdataand
methodsinclasses.Whendoneproperly,thisisolates
informationsothatstatecanbecarefullymanaged,andit
insulatestherestofaprogramfromthedetailsofclass
implementation.Afteryouhavedevelopedacompleteclassthat
performsacertaintask,youcaneffectivelyforgetthe
intricaciesofthattaskandusetheclassandthemethodsit
provides.Becausetheclassmechanismsarehiddenwithinits


methods,evensignificantchangestotheinnerworkingsofthe
classthatmightbenecessarylaterdonotrequireyoutomodify
therestofyourprogramunlessthemethodsignatureschange.
Beyondencapsulation,classesallowyoutochangehowyou
thinkabouttheelementsofyourprograms.Bywritingclasses
thatencloseeverythingassociatedwithparticulartasksor
entities,youcanbuildtypesthathavemeaningintheproblem
domainsinwhichyouwork.Youarenotlimitedtodescribing
yourprogramelementsasintegers,Booleans,oranyother
nativedatatype.Insteadofusingtheserelativelyindistinct
mechanismsandrelyingonunattachedfunctionstointerpret
theirvaluesappropriately,youcanbuildsoftwarewithclass
typesthathelpdescribetheproblembeingsolved.Inthe
precedingpayrollexample,aproceduralapproachcouldbe
implementedthatmaintainsholidaysasintegerdayandmonth
valuesthatarecomparedagainstthedatesinapayperiod
wheneverapaycheckamountiscalculated.However,thinkof
howmuchmoreexpressiveaclass-basedapproachcouldbe.
UsingaCalendarclass,holidayscouldbemaintainedasa
collectionofDateobjects.Toproduceapaycheck,eachday
duringapayperiodcouldalsoberepresentedasaDatethatis
queriedforwhetherit'saweekenddayorholidayrelativetothe
currentCalendar.Theprocessingthatmustbeperformed
doesn'tchangesignificantlybetweenthetwoapproaches,buta
systembuiltonclassesallowsresponsibilitytobeclearly
dividedandproducesentitiesthatsupportthethoughtprocess
requiredtosolvetheproblem.
Althoughencapsulationfreesdeveloperswhouseaclassfrom
havingtoknowtheimplementationdetails,itisalsoapowerful
meansofpreventingaccidentalcorruptionofthedata.When
accesstothedatamembersofaclassismanagedthrough
methods,relationshipsbetweenmemberscanbemaintainedso
thatinvalidstatesdonotoccur.
Encapsulationandthecapabilitytocreateyourowndescriptive


typesarestrongargumentsforobject-orientedprogramming,
butthey'renottheonlyones.AgreatdealoftheappealofOOP
isinitssupportforinheritance.You'lllearnmoreaboutthe
mechanicsofinheritancealittlelater,butfornowthinkofitas
awaytopullcommonbehavioroutofmultipleclassesand
implementthatbehaviorinaseparateclasssothatitcanbe
shared.
Asanexampleofinheritance,consideraprogramthatmanages
theaccountsatabank.Assumethebankoffersbothchecking
andsavingsaccountstoitscustomers.Viewingeachtype
separately,youcouldwriteindependentcodetosupportthe
requiredfunctionality.However,thisisunnecessaryeffortanda
maintenanceheadachewaitingtohappengiventhecommon
featurescheckingandsavingsaccountsshare.Abetter
approachistofactoroutthecommonattributesandbehavior
sharedbytheaccounttypesanddefineaclasstorepresent
them.YoucandefineaclasscalledGeneralAccountforthis
purposewithanaccountbalanceattributeandmethodsto
checkthebalance,makeadeposit,andmakeawithdrawal.You
won'tusethisGeneralAccountclasstorepresentanactual
accountobjectbutyoucanuseittosimplifythedevelopmentof
CheckingAccountandSavingsAccountclasses.Ifchecking
accountsatthisbankdonotpayinterest,youcaninheritthe
functionalityofGeneralAccountwhendeclaring
CheckingAccountandbefinished.Youcanthendeclare
SavingsAccounttoinheritfromGeneralAccountandadda
methodtocomputeaninterestpaymentandaddittothe
currentaccountbalance.Withthisapproach,youcanfocusonly
onhowtheaccounttypesdifferandreflectthosedifferencesin
themethodsyouwrite.Inheritanceallowsyoutobuildclass
hierarchiesthatsimplifythetaskofrepresentingcomplex
structuresinasoftwaresystem.
Note
Whennewclassesinheritthepropertiesofanother


class,theyarereferredtoaschildclassesor
subclasses.Theclassfromwhichtheyarederivedis
thencalledaparentorsuperclass.

Also,withinheritancecomestheconceptofpolymorphism,
whichisthetruemarkofanobject-orientedprogramming
language.TounderstandthisaspectofOOP,firstthinkofan
object'stypenotasaspecificclassimplementation,butasthe
setofmessagesitunderstands(thatis,themethodstowhichit
canrespond).Usingthisdefinition,objectsofthesametype
canbeimplementedbydifferentclasses.Eachoftheseclasses
canrespondtothesamesetofmessages,buteveryonecan
respondwithdifferentbehaviorthroughitsowndistinctmethod
implementations.Polymorphismallowsyoutotreatinstancesof
theseclassesasinstancesofatypewithoutregardtotheir
particularimplementation.Forthistowork,theclassesmust
shareacommonsuperclassthatdefinesthemethodsthat
relatethem.Codethatmakesuseofapolymorphictypemakes
methodcallsonareferencetothesuperclassandthebehavior
thatresultsisdeterminedbytheparticularsubclass
implementation.
Theclassicexampleofpolymorphismusesasetofclasses
foundinasimpledrawingprogram.Inthisexample,the
programprovidesatoolpalettewithcircleandrectangle
drawingtools.Theuserselectsatoolfromthepalette,clicksa
screenlocation,anddragsthemousetosizeandshapeafigure
whenaddingtoadrawing.Inastructuredprogram,the
applicationdisplaysthedrawingusingaloopthatcheckseach
figurecreatedbytheuserandcallsaspecificfunctionthat
knowshowtodrawthattypeofshape.Thisapproachworks
reasonablywelluntiltheprogramusersaddarequirementthat
atrianglemustalsobesupportedasadrawingtool.A
programmermustthenlocatethedrawingloop,andevery
otherplaceshapesaretreateddifferentlybasedontheirtype,
andupdatethecodetounderstandtriangles.Thisupdateisnot


tooburdensomeinthissimpleexample,butitillustratesa
maintenanceandreliabilitydrawbackthatcangetoutofhand
quicklyinasystemwithanytruecomplexity.WithOOP,
encapsulationcomesintoplayfirstasabetterapproachtothis
program.Thefunctionsfordrawingdifferentshapetypesshould
belocatedinthecodethatdefineseachshape,namelywithin
CircleShape,RectangleShape,andTriangleShape
classes.Thedrawingfunctionalityshouldbeimplementedasa
drawmethodthatholdsalltheknowledgerequiredtodrawthe
associatedshapeonthescreen.Thisisalreadyanimprovement
becausethebehaviorofeachshapeisnowencapsulatedwithin
thedefinitionoftheshapesthemselves.Thisencapsulation
significantlyreducesthenumberofplacescodemustbe
modifiedifthedrawingrequirementsforaparticularshapeare
laterchanged.
There'sstillmore,however.Adrawbackinoursystemsofaris
thatalthoughthedrawmethodsareencapsulatedwithin
classes,theprogramstillhastocallaseparatemethodforeach
shapetypewhenthescreenneedstobedisplayed.Thisis
unnecessaryeffortbecausetheprogramdoesnotcareabout
theshapetypes;itonlywantsthemtobedrawncorrectly.The
capabilityforashapetobedrawncorrectlyisacommon
behaviorfoundineachoftheshapeclasses(CircleShape,
RectangleShape,andTriangleShape).
Thisiswherepolymorphismcomesintoplay.Insteadofdefining
threeunrelatedclasses,youcanfactoroutthecommon
behaviorthat,inthiscase,isthecapabilityforashapetodraw
itself.TheexamplebecomesatrueOOPimplementationwhena
GenericShapeclasswithadrawmethodisdefinedasa
superclassforeachofthethreeshapeclasses.A
GenericShapedoesnotcorrespondtoanyrealshape,soit
hasnoimplementationforitsdrawmethod.However,thisclass
doesserveasignificantpurposebydeclaringthatitssubclasses
mustsupportadrawmethod.Withthischange,theprogram
cankeeptrackofitsshapesasGenericShapeinstancesrather


thanacollectionofCircleShape,RectangleShape,and
TriangleShapeinstances.Thisworksbecausetheprogram
doesn'tneedtoknowthedifference,providedthatitcandirect
ashapeofanytypetodrawitself.Whenit'stimetodrawthe
screen,thedrawmethodofeachGenericShapecanbecalled
and,throughpolymorphism,thedrawmethodofthespecific
shapetypeiscalled.
Note
Thedynamicbehaviorpossiblewithpolymorphismis
theresultofaprocessknownaslatebinding.When
theJavacompilerencountersacalltoamethod,it
doesn'tbindthecalltoaparticularmethod
implementationuntilruntime(unlessthemethodis
declaredstaticorfinal,whichwouldmeanthat
theimplementationisknownatcompile-time).This
isincontrasttoearlybinding,whichbindsamethod
calltoaspecificimplementationduringcompilation.

Caution
Inthepreviousexample,althougheverycircleand
rectangleisalsoashape,agivenshapeisnot
necessarilyacircleorarectangle.Thus,although
theCircleShapeandRectangleShapeclasses
canbetreatedjustliketheGenericShapeclassin
Java,youcannotperformanoperationsuchas
getRadiusthatisreservedfortheCircleShape
classonaninstanceoftheGenericShapeclass.


ClassesinJava
Asstatedatthebeginningofthischapter,classesarethe
buildingblockinanobject-orientedlanguagesuchasJava.In
fact,Java,unlikeC++,goessofarastomakeitimpossibleto
defineanyvariablesormethodsoutsideaclass.Everythingyou
doinJavaisbasedondesigningandimplementingclasses.


TheJavaPlatform
JavaitselfisbuiltfromclassesthataremadeavailabletothepublicintheSDK.
Theseclasses,knownastheJavaplatform,provideapowerfulsetofcommon
functionalitytypicallyfoundonlyinthird-partyadd-onstootherlanguages.
Althoughtherearesomelimitations,alargenumberoftheclassesthatmakeup
theJavaplatformcanthemselvesbeextended.Bydoingthis,youcantailorthe
classesintheJavaAPIlibraryespeciallythosethatsupportuserinterface
developmenttomeetyourparticularneeds.

Beforeyoustartcreatingprograms,youmustfirstlearnhowto
createclasses.Intermsofsyntax,therearetwopartstoa
classinJava:thedeclarationandthebody.Listing7.1isa
simpleclassthatfulfillssomeoftherequirementsofthesimple
bankaccountexamplediscussedintheprevioussection.
Examinethislistingtogetanideaofwhatconstitutesaclass.
Youcanrefertothislistingagainlaterasyourunderstandingof
classesgrows.
Listing7.1GeneralAccount.javaAGeneralClassfor
MaintainingaBankAccount

/**
*Asimpleclassusedtoimplementcommonbehaviorfor
*typesofbankaccounts.Itshouldbeextendedtoimp
*behaviorforspecificaccounts.
*/
publicclassGeneralAccount{
//uniqueaccountidentifier
privateStringaccountNumber;
//thiswillholdthecurrentaccountbalance
protectedfloatbalance;


publicGeneralAccount(StringaccountNum){
accountNumber=accountNum;
}
publicStringgetAccountNumber(){
returnaccountNumber;
}
publicfloatgetBalance(){
returnbalance;
}
publicvoidmakeDeposit(floatamount){
balance+=amount;
}
publicvoidmakeWithdrawal(floatamount){
balance-=amount;
}
}





Takeaquicklookthroughthisclass.Thefirstpartofanyclass
istheclassdeclaration.Mostclassdeclarationsyouwritewill
looksimilartothatforGeneralAccount:

publicclassGeneralAccount
Declaringaclassstatesseveralthings,butprobablythemost
importantoneisthenameoftheclass(GeneralAccount).In
thecaseofanypublicclass,thenameoftheclassmustalso
matchthenameofthefilethatcontainsit.Inotherwords,this
classmustappearinthefileGeneralAccount.java.


Caution
RememberthatJavaisacase-sensitivelanguage.
Thiscasesensitivityappliestofilenamesalso.Inthe
precedingexample,namingthesourcefilethat
containstheGeneralAccountclass
generalAccount.javaoranythingelseotherthan
GeneralAccount.javaresultsinacompilererror.

Thenextpartoftheclassistheopeningbrace.Youshould
noticethatthereisabrace({)atthebeginningoftheclass,
andifyoulookallthewaydownatthebottomthere,isalsoa
closingbrace(}).Thebracesdefinetheareainthefilewhere
theclassdefinitionwillexist.Also,notethatthereisno
semicolonattheendofthefinalclosingbracelikeyoufindin
C++.
Abitfartherdown,youwillseeseveralcomments.Asyou
learnedin"Comments"(Chapter3,"DataTypesandOther
Tokens"),commentscanexistanywhereinthefileandare
ignoredbythecompiler,buttheyhelpyouleavemessagesfor
yourselforotherprogrammers.Next,youwillseeseveralfields
declared.Eachofthesevariablesisaccessiblefromanyofthe
methodsintheclass.Whenyouchangetheminonemethod,all
theothermethodswillseethenewvalue.


DeclaringaClass
Ingeneral,Javaclassdeclarationstaketheform

AccessSpecifierModifiersclassNewClassextendsSuperc
implementsInterfaceName





whereeverythinginitalicsisoptional.Asyoucansee,thereare
fivepropertiesoftheclassthatcanbedefinedinthe
declaration:
AccessSpecifier
Modifiers
Classname
Superclass
Interfacesimplemented
SeeChapter9,"Interfaces,"

AccessSpecifiers
Theaccessspecifierinaclassdeclarationdetermineshow
visibleaclassistootherclasses.Thespecifiersthatapplyto
classesaresimilartothemethodaccessspecifiersdiscussedin
Chapter4,"MethodsandExceptions."Althoughspecifiersare
notofprimaryimportancewhiledevelopinganindividualclass,
theybecomeveryimportantwhenyoudecidetocreateother
classes,interfaces,andexceptionsthatusethatclass.


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

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

×

×