麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

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

TIJ英文原版書籍閱讀之旅——Chapter Eight:Polymorphism

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

Thetwist

|_Method-callbinding

Connectingamethodcalltoamethodbodyiscalledbinding.Whenbindingisperformedbeforethe

Whenalanguageimplementslatebinding,theremustbesomemechanismtodeterminethetypeoftheobjectatruntimeandtocalltheappropriatemethod.Thatis,thecompilerstilldoesn'tknowtheobjecttype,butthemethod-callmechanismfindsoutandcallsthecorrectmethodbody.Thelate-bindingmechanismvariesfromlanguagetolanguage,butyoucanimaginethesomesortoftypeinformationmustbeinstalledintheobjects.

Allmethodbindinginjavauseslatebindingunlessthemethodisstaticorfinal(privatemethodareimplicitlyfinal).Thismeansthatordinarilyyoudon'tneedtomakeanydecisionaboutwhetherlatebindingwilloccur-ithappensautomatically.

|_Pitfall:"overriding"privatemethods

Here'ssomethingyoumightinnocentlytrytodo:

public class PrivateOverride{private void f() {System.out.println("private f()");}public static void main(String[] args){PrivateOverride po = new Derived();po.f(); }}class Derived extends PrivateOverride{public void f() {System.out.println("public f()");}}/*Output:private f()*/

Youmightreasonablyexpecttheoutputtobe"publicf()",butaprivatemethodisautomaticallyfinal,andisalsohiddenfromthederivedclass.SoDerived'sf()inthecaseisabrandnewmethod;it'snotevenoverloaded,sincethebase-classversionoff()isn'tvisibleinDerived.Ifyouwanttogetthe"publicf()",youcanmodifythatcodepo.f()to((Derived)po).f().

Theresultofthisisthatonlynon-privatemethodsmaybeoverridden,butyoushouldwatchoutfortheappearanceofoverridingprivatemethods,whichgeneratesnocompilerwarnings,butdoesn'tdowhatyoumightexpect.Tobeclear,youshoulduseadifferentnamefromaprivatebase-classmethodinyourderivedclass.

|_Pitfall:fieldsandstaticmethods

Onceyoulearnaboutpolymorphism,youcanbegintothinkthateverythinghappenspolymorphically.However,onlyordinarymethodcallscanpolymorphic.Ifyouaccessafielddirectly,thataccesswillberesolvedatcompiletime.

Althoughthisseemslikeitcouldbeaconfusingissue,inpracticeitvirtuallynevercomesup.Foronething,you'llgenerallymakeallfieldsprivateandsoyouwon'taccessthemdirectly,butonlyassideeffectsofcallingmethods,Inaddition,youprobablywon'tgivethesamenametobase-classfieldandaderived-classfield,becauseitsconfusing.

Ifamethodisstatic,itdoesn'tbehavepolymorphically,staticmethodsareassociatedwiththeclass,andnottheindividualobjects.

Constructorsandpolymorphism

|_Orderofconstructorcalls

Eventhoughconstructorsarenotpolymorphic(they'reactuallystaticmethods,butthestaticdeclarationisimplicit),it'simportanttounderstandthewayconstructorsworkincomplexhierarchiesandwithpolymorphism.

Aconstructorforthebaseclassisalwayscalledduringtheconstructionprocessforaderivedclass,chaininguptheinheritancehierarchysothataconstructorforeverybaseclassiscalled.

Theorderofconstructorcallsforacomplexobjectisasfollows:

1.Thebase-classconstructoriscalled.Thisstepisrepeatedrecursivelysuchthattherootofthehierarchyisconstructedfirst,followedbythenext-derivedclass,etc.,untilthemost-derivedclassisreached.

2.Memberinitializersarecalledintheorderofdeclaration.

3.Thebodyofthederived-classconstructoriscalled.

Theorderoftheconstructorcallsisimportant.Whenyouinherit,youknowallaboutthebaseclassandcanaccessanypublicandprotectedmembersofthebaseclass.Thismeansthatyoumustbeabletoassumethatallthemembersofthebaseclassarevalidwhenyou'remembersofallpartsoftheobjecthavebeenbuilt.Insidetheconstructor,however,youmustbeabletoassumethatallmembersthatyouusehavabeenbuilt.Theonlywaytoguaranteethisisforthebase-classconstructortobecalledfirst.Thenwhenyou'reinthederived-classconstructor,allthemembersyoucanaccessinthebaseclasshavebeeninitialized.Knowingthatallmembersarevalidinsidetheconstructorisalsothereasonthat,wheneverpossible,youshouldinitializeallmemberobject(thatis,objectsplacedintheclassusingcomposition)attheirpointofdefinitionintheclass.Ifyoufollowthispractice,youwillheapensurethatallbaseclassmembersandmembersobjectsofthecurrentobjecthavebeeninitialized.

|_Inheritanceandcleanup

Whenyouoverridedispose()(thenameIhavechosentousehere;youmaycomeupwithsomethingbetter)inaninheritedclass,it'simportanttoremembertocallthebase-classversionofdispose(),sinceotherwisethebase-classcleanupwillnothappen.

|_Behaviorofpolymorphicmethodsinsideconstructors

Conceptually,theconstructor'sjobistobringtheobjectintoexistence(whichishardlyanordinaryfeat).Insideanyconstructor,theentireobjectmightbeonlypartiallyformed-youcanonlyknowthatthebase-classobjectshavebeeninitialized.Iftheconstructorisonlyonestepinbuildinganobjectofaclassthat'sbeenderivedfromthatconstructor'sclass,thederivedpartshavenotyetbeeninitializedatthetimethatthecurrentconstructorisbeingcalled.Adynamicboundmethodcall,however,reaches"outward"intotheinheritancehierarchy.Itcallsamethodinaderivedclass.Ifyoudothisinsideaconstructor,youcallamethodthatmightman

Youcanseetheprobleminthefollowingexample:

class Glyph{void draw() {System.out.println("Glyph.draw()");}Glyph(){System.out.println("Glyph() before draw()");draw();System.out.println("Glyph() after draw()");}}class RoundGlyph extends Glyph{private int radius = 1;RoundGlyph(int r){radius = r;System.out.println("RoundGlyph.RoundGlyph(), radius = " + radius);}void draw(){System.out.println("RoundGlyph.draw(), radius = " + radius);}}public class PolyConstructors{public static void main(String[] args){new RoundGlyph(5);}}/* Output:Glyph() before draw()RoundGlyph.draw(), radius = 0Glyph() after draw()RoundGlyph.RoundGlyph(), radius = 5*/

Theorderofinitializationdescribedintheearliersectionisn'tquitecomplete,andthat'sthekeytosolvingthemystery.Theactualprocessofinitializationis:

1.Thestorageallocatedfortheobjectisinitializedtobinaryzerobeforeanythingelsehappens.

2.Thebase-classconstructorsarecalledasdescribedpreviously.Atthispoint,theoverriddendraw()methodiscalled(yes,beforetheRoundGlyphconstructoriscalled),whichdiscoversaradiusvalueofzero,duetoStep1.

3.Memberinitializesarecalledintheorderofdeclaration.

4.Thebodyofthederived-classconstructoriscalled.

Foravoidthisproblem,agoodguidelineforguidelineforconstructorsis,"Doaslittleaspossibletosettheobjectintoagoodstate,andifyoucanpossiblyavoidit,don'tcallanyothermethodsinthisclass."Theonlysafemethodstocallinsideaconstructorarethosethatarefinalinthebaseclass.(Thisalsoappliestoprivatemethods,whichareautomaticallyfinal.)Thesecannotbeoverriddenandthuscannotproducethiskindofsurprise.Youmaynotalwaysbeabletofollowthisguideline,butit'ssomethingtostrivetowards.

Covariantreturntypes

JavaSE5addscovariantreturntypes,whichmeansthatanoverriddenmethodinaderivedclasscanreturnatypederivedfromthetypereturnedbythebase-classmethod.

Designingwithinheritance

Ageneralguidelineis"Useinheritancetoexpressdifferencesinbehavior,andfieldstoexpressvariationsinstate".

(END_XPJIANG)


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 一级免费黄色免费片 | av在线免费看片 | 日本在线不卡一区二区三区 | 亚洲国产在 | 毛片在哪里看 | 国产精品久久久久久久久久尿 | 精国产品一区二区三区四季综 | 夜间福利网站 | 成人国产精品一区二区毛片在线 | 欧美精品v国产精品v日韩精品 | 2019天天干夜夜操 | 国产精品成人免费一区久久羞羞 | 成年人视频在线免费播放 | 在线成人免费av | 久久影院免费观看 | 成人免费在线视频 | 久久久久一本一区二区青青蜜月 | 国产精品久久久久久久久久iiiii | 久久久久久久久久91 | 香蕉视频1024| 久久亚洲精品久久国产一区二区 | 一日本道久久久精品国产 | videos真实高潮xxxx | 精品国产91久久久久久浪潮蜜月 | 精品亚洲在线 | 久草在线最新 | 天天看成人免费毛片视频 | 免费看日韩片 | 日本一区视频在线观看 | 中国免费一级毛片 | 久久17| 一本免费视频 | 久久精品99久久久久久2456 | 精品一区二区三区在线视频 | 久久最新免费视频 | 成人午夜在线播放 | 成人免费网站在线观看视频 | 国产91久久精品 | 欧美日韩在线播放 | 免费国产在线视频 | 国产精品久久久久久久久久了 |