ReusingClasses
有兩種常用方式實現類的重用,組件(在新類中創建存在類的對象)和繼承。
Compositionsyntax
Everynon-PRimitiveobjecthasatoString()method,andit’scalledinspecialsituationswhenthecompilerwantsaStringbutithasanobject.
Inheritancesyntax
You’realwaysdoinginheritancewhenyoucreateaclass,becauseunlessyouexplicitlyinheritfromsomeotherclass,youimplicitlyinheritfromjava’sstandardrootclassObject.
Toallowforinheritance,asageneralrulemakeallfieldsprivateandallmethodspublic.Ofcourse,inparticularcasesyoumustadjustments,butthisisausefulguideline.
|_Initializingthebaseclass
Evenifyoudon’tcreateaconstructorforderived-class,thecompilerwillsynthesizeadefaultconstructorforyouthatcallsthebaseconstructor.
Ifyourclassdoesn’thavedefaultarguments,orifyouwanttocallabase-classconstructorthathasanargument,youmustexplicitlywritethecallstothebase-classconstructorusingthesuperkeyWordandtheappropriateargumentlist.Inaddition,thecalltothebase-classconstructormustbethefirstthingyoudointhederived-classconstructor.
Delegation
委托是重用類的第三種方式,介于繼承和組件之間。在新建類中放置成員對象(像組件),同時暴露該對象的所有方法(像繼承)。Youhavemorecontrolwithdelegationbecauseyoucanchoosetoprovideonlyasubsetofthemethodsinthememberobject.
Combiningcompositionandinherit
|_Guaranteeingpropercleanup
Notethatinyourcleanupmethod,youmustalsopayattentiontothecallingorderforthebase-classandmember-objectcleanupmethodsincaSEOnesubobjectdependsonanother.Ingeneral,youshouldfollowthesameformthatisimposedbyaC++compileronitsdestructors:Firstperformallofthecleanupworkspecifictoyourclass,inthereverseorderofcreation.
Therecanbemanycasesinwhichthecleanupissueisnotaproblem;youjustletthegarbagecollectordothework.Butwhenyoumustdoitexplicitly,diligenceandattentionarerequired,becausethere’snotmuchyoucanrelyonwhenitcomestogarbagecollection.Thegarbagecollectormightneverbecalled.Ifitis,itcanreclaimobjectsinanyorderitwants.Youcan’trelyongarbagecollectionforanythingbutmemoryreclamation.Ifyouwantcleanuptotakeplace,makeyourowncleanupmethodsanddon’tuseonfinalize().
Choosingcompositionvs.inheritance
Bothcompositionandinheritanceallowyoutoplacesubobjectinsideyournewclass(compositionexplicitlydoesthis-withinheritanceit’simplicit).
Theis-arelationshipisexpressedwithinheritance,andthehas-arelationshipisexpressedwithcomposition.
Upcasting
Inobject-orientedprogramming,themostlikelywaythatyou’llcreateandusecodeisbysimplypackagingdataandmethodstogetherintoaclass,andusingobjectsofthatclass.You’llalsouseexistingclassestobuildnewclasseswithcomposition.Lessfrequently,you’lluseinheritance.SoalthoughinheritancegetsalotofemphasiswhilelearningOOP,itdoesn’tmeanthatyoushoulduseiteverywhereyoupossiblycan.Onthecontrary,youshoulduseitsparingly,onlywhenit’sclearthatinheritanceisuseful.Oneoftheclearestwaystodeterminewhetheryoushouldusecompositionorinheritanceistoaskwhetheryou’lleverneedtoupcastfromyournewclasstothebaseclass.Ifyoumustupcast,theninheritanceisnecessary.ThePolymorphismprovidesoneofthemostcompellingreasonsforupcasting,butifyouremembertoask“DoIneedtoupcast?”you’llhavaagoodtoolfordecidingbetweencompositionandinheritance.
Thefinalkeyword
Therearethereplaceswherefinalcanbeused:fordata,methodsandclasses.
|_finaldata
Thatapieceofdataisconstantisusefulfortworeasons:
1.Itcanbeacompile-timeconstantthatwon’teverchange.
2.Itcanbeavalueinitializedatruntimethatyoudon’twantchanged.
Inthecaseofacompile-timeconstant,thecompilerisallowedto“fold”theconstantvalueintoanycalculationsinwhichit’sused;thatis,thecalculationcanbeperformedatcompiletime,eliminatingsomerun-timeoverhead.InJava,thesesortsofconstantsmustbeprimitivesandareexpressedwiththefinalkeyword.Avaluemustbegivenatthetimeofdefinitionofsuchaconstant.
當final被用于對象引用上時,對象的引用不能被更改,即該引用不能指向其他對象,但是對象本身可以被修改。這個規則對隸屬于對象的數組引用同樣適用。
在定義時不賦初值的final變量必須在使用之前被初始化(比如在構造體中初始化,staticfinal不能在構造體中初始化,因為static不依賴于對象而存在),否則編譯報錯。You’reforcedtoperformassignmentstofinalseitherwithanexpressionatthepointofdefinitionofthefieldorineveryconstructor.Thatwayit’sguaranteedthatthefinalfieldisalwaysinitializedbeforeuse.
|_finalarguments
參數被final修飾時可讀不可寫。Thisfeatureisprimarilyusedtopassdatatoanonymousinnerclasses.
|_finalmethods
用final修飾的方法不能被重寫。
|_finalandprivate
Anyprivatemethodsinaclassareimplicitlyfinal.Becauseyoucan’taccessaprivatemethod,youcan’toverrideit.Youcanaddthefinalspecifiertoaprivatemethod,butitdoesn’tgivethatmethodanyextrameaning.
“Overriding”canonlyoccurifsomethingispartofthebase-classinterface.Thatis,youmustbeabletoupcastanobjecttoitsbasetypeandcallthesamemethod.Ifamethodisprivate,itisn’tpartofthebase-classinterface.Itisjustsomecodethat’shiddenawayinsidetheclass,anditjusthappenstohavathename,butifyoucreateapublic,protected,orpackage-accessmethodwiththesamenameinthederivedclass,there’snoconnectiontothemethodthatmighthappentohavethatnameinthebaseclass.Youhaven’toverriddenthemethod;you’vejustcreatedanewmethod.Sinceaprivatemethodisunreachableandeffectivelyinvisible,itdoesn’tfactorintoanythingexceptforthecodeorganizationoftheclassforwhichitwasdefined.
|_finalclasses
Whenyousaythatanentireclassisfinal(byprecedingitsdefinitionwiththefinalkeyword),youstatethatyoudon’twanttoinheritfromthisclassorallowanyoneelsetodoso.Inotherwords,forsomereasonthedesignofyourclassissuchthatthereisneveraneedtomakeanychanges,orforsafetyorsecurityreasonsyoudon’twantsubclassing.
Notethatthefieldofafinalclasscanbefinalornot,asyouchoose.Thesamerulesapplytofinalforfieldsregardlessofwhethertheclassisdefinedasfinal.However,becauseitpreventsinheritance,allmethodsinafinalclassareimplicitlyfinal,sincethere’snowaytooverridethem.Youcanaddthefinalspecifiertoamethodinafinalclass,butitdoesn’taddanymeaning.
Initializationandclassloading
InJava,thecompiledcodeforeachclassexistsinitsownseparatefile.Thatfileisn’tloadeduntilthecodeisneeded.Ingeneral,youcansaythat“classcodeisloadedatthepointoffirstuse.”Thisisusuallywhenthefirstobjectofthatclassisconstructed,butloadingalsooccurswhenastaticfieldorstaticmethodisaccessed(Theconstructorisalsoastaticmethodseventhoughthestatickeywordisnotexplicit.Sotobeprecise,aclassisfirstloadedwhenanyoneofitsstaticmembersisaccessed.).
|_Initializationwithinheritance
第一次運行主類的main方法時,裝載器找到該類對應的class文件,在裝載的過程中如果發現它有父類,則繼續裝載其父類,父類還有父類,繼續裝載。接下來,在根類開始執行靜態初始化,接下來是其派生類,等等。這是重要的,因為派生類靜態初始化可能依賴父類成員被合理的初始化。
Atthispoint,thenecessaryclasseshavaallbeenloadedsotheobjectcanbecreated.First,alltheprimitivesinthisobjectaresettotheirdefaultvaluesandtheobjectreferencesaresettonull-thishappensinonefellswoopbysettingthememoryintheobjecttobinaryzero.Thenthebase-classconstructorwillbecalled.Inthiscasethecallisautomatic,butyoucanalsospecifythebase-classconstructorcallbyusingsuper.Thebaseclassconstructiongoesthroughthesameprocessinthesameorderasthederived-classconstructor.Afterthebase-classconstructorcompletes,theinstancevariablesareinitializedintextualorder.Finally,therestofthebodyoftheconstructorisexecuted.
Summary
Bothinheritanceandcompositionallowyoutocreateanewtypefromexistingtypes.Compositionreusesexistingtypesaspartoftheunderlyingimplementationofthenewtype,andinheritancereusestheinterface.
(END_XPJIANG)
新聞熱點
疑難解答