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

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

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

2019-11-15 00:36:06
字體:
供稿:網(wǎng)友
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)


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 若羌县| 桂平市| 双流县| 瑞安市| 永和县| 浮梁县| 海伦市| 图木舒克市| 益阳市| 南平市| 灌南县| 雅江县| 盐边县| 仲巴县| 象山县| 苗栗市| 公主岭市| 新竹市| 苏尼特右旗| 马山县| 贵南县| 青龙| 淅川县| 乐昌市| 郎溪县| 清涧县| 珲春市| 辉南县| 和顺县| 武功县| 郓城县| 故城县| 墨脱县| 囊谦县| 温宿县| 玛沁县| 宾阳县| 张家川| 潼关县| 普兰店市| 浮山县|