Tải bản đầy đủ - 0 (trang)
Chapter 6. Static, Final, and Enumerated Types

Chapter 6. Static, Final, and Enumerated Types

Tải bản đầy đủ - 0trang

Whenyoudeclareavariablethatbelongstoanenumerated

type,itcanonlyholdonevalueatatime,anditcan'thold

valuesfromsomeothertype.At-shirtsizeenumvariablecan't

hold"large"and"small"simultaneously,justasanintcan'thold

twovaluessimultaneously.Youcan'tassign"Monday"toatshirtsizevariable.Thoughenumeratedtypesaren'tessential,

theymakesomekindsofcodemorereadable.



enumisanewkeyword

AlthoughJDK1.5introducedextensivelanguagechanges,"enum"istheonly

newkeywordbroughtintothelanguage.Ifanyofyourexistingprogramsuse

theword"enum"asanidentifier,youwillhavetochangethembeforeyoucan

useJDK.5features.

Theidentifierenummightwellbeinprogramsthatusetheolderclass

java.util.Enumeration.Thatclasshasnothingtodowiththeenumtype,butisa

wayofiteratingthroughalltheobjectsinadatastructureclass.Manypeople

(includingme)declaredvariablessuchas



java.util.Enumerationenum;



Thejava.util.EnumerationclasshasbeenobsoletedbyaclasscalledIterator,

alsointhejava.utilpackage,soifyou'reupdatingsomecodetochangea

variablecalled"enum",youmightwanttomodifyittouseaniteratortoo.We

coveriteratorsinChapter16.



BeforeJDK1.5,acommonwaytorepresentenumerationswas

withintegerconstants,likethis:



classBread{



staticfinalintwholewheat=0;

staticfinalintninegrain=1;

staticfinalintrye=2;

staticfinalintfrench=3;

}



thenlater



inttodaysLoaf=rye;



Inthenewenumscheme,enumerationsarereferencestoone

ofafixedsetofobjectsthatrepresentthevariouspossible

values.Eachobjectrepresentingoneofthechoicesknows

whereitfitsintheorder,itsname,andoptionallyother

informationaswell.Becauseenumtypesareimplementedas

classes,youcanaddyourownmethodstothem!

Themainpurposeofthischapteristodescribeenumerated

typesindetail.Todothat,wefirstneedtoexplainwhatthe



fieldmodifiers"static"and"final"mean.Here'sthestoryin

brief:

Thekeywordfinalmakesthedeclarationaconstant.

Thekeywordstaticmakesthedeclarationbelongtothe

classasawhole.Astaticfieldissharedbyallinstancesof

theclass,insteadofeachinstancehavingitsownversionof

thefield.Astaticmethoddoesnothavea"this"object.A

staticmethodcanoperateonsomeoneelse'sobjects,but

notviaanimplicitorexplicitthis.

Themethodwhereexecutionstarts,main(),isastatic

method.Thepurposeofmain()istobeanentrypointto

yourcode,nottotrackthestateofoneindividualobject.

Static"per-class"declarationsaredifferentfromallthe

"per-object"datayouhaveseentodate.

Thevaluesinenumeratedtypesarealwaysimplicitlystaticand

final.Thenexttwosections,WhatFieldModifierstaticMeans

andWhatFieldModifierfinalMeans,havealongerexplanation

ofthepracticaleffectofthesefieldmodifiers.Afterthat,we'll

getintoenumeratedtypesthemselves.



WhatFieldModifierstaticMeans

Wehaveseenhowaclassdefinesthefieldsandmethodsthat

areinanobject,andhoweachobjecthasitsownstoragefor

thesemembers.Thatisusuallywhatyouwant.

Sometimes,however,therearefieldsofwhichyouwantonly

onecopy,nomatterhowmanyinstancesoftheclassexist.A

goodexampleisafieldthatrepresentsatotal.Theobjects

containtheindividualamounts,andyouwantasinglefieldthat

representsthetotaloveralltheexistingobjectsofthatclass.

Thereisanobviousplacetoputthiskindof"one-per-class"

fieldtooinasingleobjectthatrepresentstheclass.Staticfields

aresometimescalled"classvariables"becauseofthis.

Youcouldputatotalfieldineveryobject,butwhenthetotal

changesyouwouldneedtoupdateeveryobject.Bymaking

totalastaticfield,anyobjectthatwantstoreferencetotal

knowsitisn'tinstancedata.Insteaditgoestotheclassand

accessesthesinglecopythere.Therearen'tmultiplecopiesofa

staticfield,soyoucan'tgetmultipleinconsistenttotals.



Staticisareallypoorname

OfallthemanypoorlychosennamesinJava,"static"istheworst.Thekeyword

iscarriedoverfromtheClanguage,whereitwasappliedtostoragewhichcan

beallocatedstatically(atcompiletime).Wheneveryousee"static"inJava,think

"once-only"or"one-per-class."



Whatyoucanmakestatic

YoucanapplythemodifierstatictofourthingsinJava:

Data.Thisisafieldthatbelongstotheclass,notafield

thatisstoredineachindividualobject.

Methods.Thesearemethodsthatbelongtotheclass,not

individualobjects.

Blocks.Theseareblockswithinaclassthatareexecuted

onlyonce,usuallyforsomeinitialization.Theyarelike

instanceinitializers,butexecuteonceperclass,notonce

perobject.

Classes.Theseareclassesthatarenestedinanotherclass.

StaticclasseswereintroducedwithJDK1.1.

We'lldescribestaticdataandstaticmethodsinthischapter.

Staticblocksandstaticclassesaredealtwithlateron.



Staticdata



Staticdatabelongstotheclass,notanindividualobjectofthe

class.Thereisexactlyoneinstanceofstaticdata,regardlessof

howmanyobjectsoftheclassthereare.Tomakeafield"perclass,"applythekeyword"static,"asshownhere.



classEmployee{

intid;//per-objectfield

intsalary;//per-objectfield



staticinttotal;//per-classfield(oneonly)



...

}



EveryEmployeeobjectwillhavetheemployee_idandsalary

fields.TherewillbeonefieldcalledtotalPayrollstored

elsewhereinanobjectrepresentingtheEmployeeclass.

Becausestaticdataisdeclaredintheclassrightnexttothe

instancedata,it'salltooeasytooverlookthatstaticdataisnot



keptineachobjectwithitsinstancedata.Makesureyou

understandthiscrucialpointbeforereadingon.Figure6-1

representsthepreviouscodeintheformofadiagram.



Figure6-1.ThereisonecopyofaStaticfield,

sharedbyeachobject



Inmethodsinsidetheclass,staticdataisaccessedbygivingits



namejustlikeinstancedata.



salary=90000;

total=this.total+this.salary;



It'slegalbuthighlymisleadingtoqualifythenameofastatic

fieldwith"this."The"this"variablepointstoaninstance,but

staticdatadoesn'tliveinaninstance.Thecompilerknows

wherethestaticdatareallyis,andgeneratescodetoaccessthe

fieldintheclassobject.

Outsidetheclass,staticdatacanbeaccessedbyprefixingit

withthenameoftheclassorthenameofanobjectreference.

Itisconsideredpoorformtousetheobjectreferencemethod.

Itconfusesthereaderintomistakingyourstaticmemberforan

instancemember.



Employeenewhire=newEmployee();



//staticreferencethroughtheclass(preferred)

Employee.total+=100000;



Staticmethods

Justastherecanbestaticdatathatbelongstotheclassasa

whole,therecanalsobestaticmethods,alsocalledclass

methods.Aclassmethoddoessomeclass-wideoperationsand

isnotappliedtoanindividualobject.Again,theseareindicated

byusingthestaticmodifierbeforethemethodname.

Themain()methodwhereexecutionstartsisstatic.



publicstaticvoidmain(String[]args){



Ifmainweren'tstatic,ifitwereaninstancemethod,some

magicwouldbeneededtocreateaninstancebeforecallingit,

asisdoneforappletsandservlets.

Anymethodthatdoesn'tuseinstancedataisacandidatetobe



astaticmethod.Theconversionroutinesinthewrappersforthe

primitivetypesarestaticmethods.Ifyoulookatthesource

codeforjava.lang.Integer,you'llseearoutinelikethis



publicstaticintparseInt(Strings)

throwsNumberFormatException{

//statementsgohere.

}



ThemethodisautilitythatreadstheStringpassedtoitasan

argument,andtriestoturnitintoanintreturnvalue.Itdoesn't

doanythingwithdatafromaspecificIntegerobject(thereisn't

evenanIntegerobjectinvolvedinthecall).SoparseInt()is

properlydeclaredasstatic.Itwouldn'tbeactivelyharmfulto

makeitaninstancemethod,butyouwouldthenneedtowhisk

upanotherwiseunnecessaryIntegerobjectonwhichtoinvoke

it.Here'sanexampleofcallingthestaticmethodparseInt:



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

Chapter 6. Static, Final, and Enumerated Types

Tải bản đầy đủ ngay(0 tr)

×