Tải bản đầy đủ - 0 (trang)
Chapter 5.  Inheritance and Polymorphism

Chapter 5.  Inheritance and Polymorphism

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

5.1.SpecializationandGeneralization

Classesandtheirinstances(objects)don'texistinavacuum,

butrather,inanetworkofinterdependenciesandrelationships,

justaswe,associalanimals,liveinaworldofrelationshipsand

categories.

Theis-arelationshipisoneofspecialization.Whenwesaythat

adogis-amammal,wemeanthatthedogisaspecializedkind

ofmammal.Ithasallthecharacteristicsofanymammal(it

bearsliveyoung,nurseswithmilk,hashair),butitspecializes

thesecharacteristicstothefamiliarcharacteristicsofcanine

domesticus.Acatisalsoamammal.Assuch,weexpectitto

sharecertaincharacteristicswiththedogthataregeneralizedin

mammals,buttodifferinthosecharacteristicsthatare

specializedincats.

Thespecializationandgeneralizationrelationshipsareboth

reciprocalandhierarchical.Theyarereciprocalbecause

specializationistheobversesideofthecoinfrom

generalization.Thus,dogandcatspecializemammal,and

mammalgeneralizesfromdogandcat.

Theserelationshipsarehierarchicalbecausetheycreatea

relationshiptree,withspecializedtypesbranchingofffrom

moregeneralizedtypes.Asyoumoveupthehierarchy,you

achievegreatergeneralization.Youmoveuptowardmammalto

generalizethatdogsandcatsandhorsesallbearliveyoung.As

youmovedownthehierarchy,youspecialize.Thus,thecat

specializesmammalinhavingclaws(acharacteristic)and

purring(abehavior).

Similarly,whenyousaythatListBoxandButtonareControls

youindicatethattherearecharacteristicsandbehaviorsof

Controlsthatyouexpecttofindinbothofthesetypes.In

otherwords,Controlgeneralizesthesharedcharacteristicsof



bothListBoxandButton,whileeachspecializesitsown

particularcharacteristicsandbehaviors.



AbouttheUnifiedModelingLanguage

TheUnifiedModelingLanguage(UML)isastandardized"language"fordescribing

asystemorbusiness.ThepartoftheUMLthatisusefulforthepurposesofthis

chapteristhesetofdiagramsusedtodocumenttherelationshipsbetween

classes.

IntheUML,classesarerepresentedasboxes.Thenameoftheclassappearsat

thetopofthebox,and(optionally)methodsandmemberscanbelistedinthe

sectionswithinthebox.IntheUML,youmodel(forexample)specialization

relationshipsasshowninFigure5-1.Notethatthearrowpointsfromthemore

specializedclassuptothemoregeneralclass.



Figure5-1.Anis-arelationship



Itiscommontonotethattwoclassessharefunctionality,and

thentofactoroutthesecommonalitiesintoasharedbaseclass.

Thisprovidesyouwitheasier-to-maintaincodeandgreater

reuseofcommoncode.Forexample,supposeyoustartedout

creatingaseriesofobjectsasillustratedinFigure5-2.



Figure5-2.DerivingfromControl



AfterworkingwithRadioButtons,CheckBoxes,andCommand

buttonsforawhile,yourealizethattheysharecertain

characteristicsandbehaviorsthataremorespecializedthan

Controlbutmoregeneralthananyofthethree.Youmight

factorthesecommontraitsandbehaviorsintoacommonbase

class,Button,andrearrangeyourinheritancehierarchyas

showninFigure5-3.Thisisanexampleofhowgeneralizationis

usedinobject-orienteddevelopment.



Figure5-3.Amorefactoredhierarchy



ThisUMLdiagramdepictstherelationshipbetweenthefactored

classesandshowsthatbothListBoxandButtonderivefrom

Control,andthatButtonisinturnspecializedintoCheckBox

andCommand.Finally,RadioButtonderivesfromCheckBox.You



canthussaythatRadioButtonisaCheckBox,whichinturnisa

Button,andthatButtonsareControls.

Thisisnottheonly,orevennecessarilythebest,organization

fortheseobjects,butitisareasonablestartingpointfor

understandinghowthesetypes(classes)relatetooneanother.



Actually,althoughthismightreflecthowsomewidgethierarchiesare

organized,I'mveryskepticalofanysysteminwhichthemodeldoesn't

reflecthowIperceivereality.WhenIfindmyselfsayingthata

RadioButtonisaCheckBox,Ihavetothinklongandhardabout

whetherthatmakessense.IsupposeaRadioButtonisakindof

checkbox.Itisacheckboxthatsupportstheidiomofmutually

exclusivechoices.Thatsaid,itisabitofastretchandmightbeasign

ofashakydesign.



5.2.Inheritance

InC#,thespecializationrelationshipistypicallyimplemented

usinginheritance.Thisisnottheonlywaytoimplement

specialization,butitisthemostcommonandmostnaturalway

toimplementthisrelationship.

SayingthatListBoxinheritsfrom(orderivesfrom)Control

indicatesthatitspecializesControl.Controlisreferredtoas

thebaseclass,andListBoxisreferredtoasthederivedclass.

Thatis,ListBoxderivesitscharacteristicsandbehaviorsfrom

Controlandthenspecializestoitsownparticularneeds.



5.2.1.ImplementingInheritance

InC#,youcreateaderivedclassbyaddingacolonafterthe

nameofthederivedclass,followedbythenameofthebase

class:

publicclassListBox:Control



Thiscodedeclaresanewclass,ListBox,thatderivesfrom

Control.Youcanreadthecolonas"derivesfrom."



C++programmerstakenote:C#hasnoprivateorprotected

inheritance.



Thederivedclassinheritsallthemembersofthebaseclass,



bothmembervariablesandmethods.



5.3.Polymorphism

Therearetwopowerfulaspectstoinheritance.Oneiscode

reuse.WhenyoucreateaListBoxclass,you'reabletoreuse

someofthelogicinthebase(Control)class.

Whatisarguablymorepowerful,however,isthesecondaspect

ofinheritance:polymorphism.Polymeansmanyandmorph

meansform.Thus,polymorphismreferstobeingabletouse

manyformsofatypewithoutregardtothedetails.

Whenthephonecompanysendsyourphonearingsignal,it

doesn'tknowwhattypeofphoneisontheotherendoftheline.

Youmighthaveanold-fashionedWesternElectricphonethat

energizesamotortoringabell,oryoumighthavean

electronicphonethatplaysdigitalmusic.

Asfarasthephonecompanyisconcerned,itknowsonlyabout

the"basetype"Phoneandexpectsthatany"instance"ofthis

typeknowshowtoring.Whenthephonecompanytellsyour

phonetoring,itsimplyexpectsthephoneto"dotheright

thing."Thus,thephonecompanytreatsyourphone

polymorphically.



5.3.1.CreatingPolymorphicTypes

BecauseaListBoxis-aControlandaButtonis-aControl,we

expecttobeabletouseeitherofthesetypesinsituationsthat

callforaControl.Forexample,aformmightwanttokeepa

collectionofalltheinstancesofControlitmanagessothat

whentheformisopened,itcantelleachofitsControlsto

drawitself.Forthisoperation,theformdoesn'twanttoknow

whichelementsarelistboxesandwhicharebuttons;itjust

wantstotickthroughitscollectionandtelleachto"draw."In



short,theformwantstotreatallitsControlobjects

polymorphically.



5.3.2.CreatingPolymorphicMethods

Tocreateamethodthatsupportspolymorphism,youneedonly

markitasvirtualinitsbaseclass.Forexample,toindicate

thatthemethodDrawWindow()ofclassControlinExample51ispolymorphic,simplyaddthekeywordvirtualtoits

declarationasfollows:

publicvirtualvoidDrawWindow()



Noweachderivedclassisfreetoimplementitsownversionof

DrawWindow().Todoso,simplyoverridethebaseclassvirtual

methodbyusingthekeywordoverrideinthederivedclass

methoddefinition,andthenaddthenewcodeforthat

overriddenmethod.

InthefollowingexcerptfromExample5-1(whichappearslater

inthissection),ListBoxderivesfromControlandimplements

itsownversionofDrawWindow():

publicoverridevoidDrawWindow()

{

base.DrawWindow();//invokethebasemethod

Console.WriteLine("Writingstringtothelistbox:{0}",

listBoxContents);

}



Thekeywordoverridetellsthecompilerthatthisclasshas



intentionallyoverriddenhowDrawWindow()works.Similarly,

you'lloverridethismethodinanotherclass,Button,also

derivedfromControl.

InthebodyofExample5-1,you'llfirstcreatethreeobjects:a

Control,aListBox,andaButton.You'llthencallDrawWindow(

)oneach:

Controlwin=newControl(1,2);

ListBoxlb=newListBox(3,4,"Standalonelistbox");

Buttonb=newButton(5,6);

win.DrawWindow();

lb.DrawWindow();

b.DrawWindow();



Thisworksmuchasyoumightexpect.ThecorrectDrawWindow(

)objectiscalledforeach.Sofar,nothingpolymorphichasbeen

done.Therealmagicstartswhenyoucreateanarrayof

Controlobjects.BecauseaListBoxis-aControl,youarefree

toplaceaListBoxintoaControlarray.Youcanalsoplacea

ButtonintoanarrayofControlobjectsbecauseaButtonis

alsoaControl:

Control[]winArray=newControl[3];

winArray[0]=newControl(1,2);

winArray[1]=newListBox(3,4,"Listboxinarray");

winArray[2]=newButton(5,6);



WhathappenswhenyoucallDrawWindow()oneachobject?

for(inti=0;i<3;i++)

{

winArray[i].DrawWindow();



}



AllthecompilerknowsisthatithasthreeControlobjectsand

thatyou'vecalledDrawWindow()oneach.Ifyouhadnot

markedDrawWindowasvirtual,Control'sDrawWindow()

methodwouldbecalledthreetimes.However,becauseyoudid

markDrawWindow()asvirtual,andbecausethederived

classesoverridethatmethod,whenyoucallDrawWindow()on

thearray,thecompilerdeterminestheruntimetypeofthe

actualobjects(aControl,aListBox,andaButton)andcalls

therightmethodoneach.Thisistheessenceofpolymorphism.

ThecompletecodeforthisexampleisshowninExample5-1.



Thislistingusesanarray,whichisacollectionofobjectsofthesame

type.Accessthemembersofthearraywiththeindexoperator:



//setthevalueoftheelement

//atoffset5

MyArray[5]=7;



Thefirstelementinanyarrayisatindex0.Theuseofthearrayinthis

exampleshouldbefairlyintuitive.Arraysareexplainedindetailin

Chapter9.



Example5-1.Usingvirtualmethods

#regionUsingdirectives



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

Chapter 5.  Inheritance and Polymorphism

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

×