国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

TIJ英文原版書籍閱讀之旅——Chapter Seven:Reusing Classes

2019-11-15 00:33:47
字體:
來源:轉載
供稿:網友
TIJ英文原版書籍閱讀之旅——Chapter Seven:Reusing Classes 2015-06-11 19:36 by 海峰 :), ... 閱讀, ... 評論, 收藏, 編輯

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)


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 建平县| 高安市| 定边县| 津市市| 汉阴县| 永丰县| 仪陇县| 德清县| 屏山县| 越西县| 房山区| 台中市| 二手房| 西乌珠穆沁旗| 珠海市| 读书| 镇平县| 深州市| 贡嘎县| 神农架林区| 内黄县| 河曲县| 射洪县| 长顺县| 阜城县| 连江县| 惠东县| 德化县| 兰溪市| 中西区| 诸暨市| 濉溪县| 肇东市| 东辽县| 万荣县| 二连浩特市| 巴彦淖尔市| 内乡县| 漳平市| 翁牛特旗| 永顺县|