Tải bản đầy đủ - 0 (trang)
Chapter 11. Polymorphism, Interfaces & Operator Overloading

Chapter 11. Polymorphism, Interfaces & Operator Overloading

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

Chapter11.Polymorphism,Interfaces&

OperatorOverloading

OneRingtorulethemall,OneRingtofindthem,

OneRingtobringthemallandinthedarknessbind

them.

JohnRonaldReuelTolkien

Generalpropositionsdonotdecideconcretecases.

OliverWendellHolmes

Aphilosopherofimposingstaturedoesn'tthinkina

vacuum.Evenhismostabstractideasare,tosome

extent,conditionedbywhatisorisnotknownin

thetimewhenhelives.

AlfredNorthWhitehead

Whyartthoucastdown,Omysoul?

Psalms42:5

OBJECTIVES

Inthischapteryouwilllearn:

Theconceptofpolymorphismandhowitenablesyouto

"programinthegeneral."

Touseoverriddenmethodstoeffectpolymorphism.

Todistinguishbetweenabstractandconcreteclasses.



Todeclareabstractmethodstocreateabstractclasses.

Howpolymorphismmakessystemsextensibleand

maintainable.

Todetermineanobject'stypeatexecutiontime.

Tocreatesealedmethodsandclasses.

Todeclareandimplementinterfaces.

Tooverloadoperatorstoenablethemtomanipulateobjects.



[Page509]



Outline

11.1 Introduction

11.2 PolymorphismExamples

11.3 DemonstratingPolymorphicBehavior

11.4 AbstractClassesandMethods

11.5 CaseStudy:PayrollSystemUsingPolymorphism















11.5.1 CreatingAbstractBaseClassEmployee

11.5.2 CreatingConcreteDerivedClassSalariedEmployee

11.5.3 CreatingConcreteDerivedClassHourlyEmployee

11.5.4 CreatingConcreteDerivedClassCommissionEmployee

11.5.5 CreatingIndirectConcreteDerivedClass

BasePlusCommissionEmployee









11.5.6 PolymorphicProcessing,OperatorisandDowncasting

11.5.7 SummaryoftheAllowedAssignmentsBetweenBaseClassand

DerivedClassVariables

11.6 sealedMethodsandClasses

11.7 CaseStudy:CreatingandUsingInterfaces









11.7.1 DevelopinganIPayableHierarchy

11.7.2 DeclaringInterfaceIPayable

















11.7.3 CreatingClassInvoice

11.7.4 ModifyingClassEmployeetoImplementInterfaceIPayable

11.7.5 ModifyingClassSalariedEmployeeforUseintheIPayableHierarchy

11.7.6 UsingInterfaceIPayabletoProcessInvoicesandEmployees

Polymorphically

11.7.7 CommonInterfacesofthe.NETFrameworkClassLibrary

11.8 OperatorOverloading

11.9 (Optional)SoftwareEngineeringCaseStudy:IncorporatingInheritance

andPolymorphismintotheATMSystem



11.10 Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises

Exercises







[Page509(continued)]



11.1.Introduction

Wenowcontinueourstudyofobject-orientedprogrammingby

explaininganddemonstratingpolymorphismwithinheritance

hierarchies.Polymorphismenablesusto"programinthe

general"ratherthan"programinthespecific."Inparticular,

polymorphismenablesustowriteapplicationsthatprocess

objectsthatsharethesamebaseclassinaclasshierarchyasif

theyareallobjectsofthebaseclass.

Considerthefollowingexampleofpolymorphism.Supposewe

createanapplicationthatsimulatesthemovementofseveral

typesofanimalsforabiologicalstudy.ClassesFish,FrogandBird

representthethreetypesofanimalsunderinvestigation.

ImaginethateachoftheseclassesextendsbaseclassAnimal,

whichcontainsamethodMoveandmaintainsananimal'scurrent

locationasx-ycoordinates.Eachderivedclassimplements

methodMove.Ourapplicationmaintainsanarrayofreferencesto

objectsofthevariousAnimalderivedclasses.Tosimulatethe

animals'movements,theapplicationsendseachobjectthe

samemessageoncepersecondnamely,Move.However,each

specifictypeofAnimalrespondstoaMovemessageinaunique

wayaFishmightswimthreefeet,aFrogmightjumpfivefeetand

aBirdmightfly10feet.Theapplicationissuesthesame

message(i.e.,Move)toeachanimalobjectgenerically,buteach

objectknowshowtomodifyitsx-ycoordinatesappropriately

foritsspecifictypeofmovement.Relyingoneachobjectto

knowhowto"dotherightthing"(i.e.,dowhatisappropriate

forthattypeofobject)inresponsetothesamemethodcallis

thekeyconceptofpolymorphism.Thesamemessage(inthis

case,Move)senttoavarietyofobjectshas"manyforms"of

resultshencethetermpolymorphism.



[Page510]



Withpolymorphism,wecandesignandimplementsystemsthat

areeasilyextensiblenewclassescanbeaddedwithlittleorno

modificationtothegeneralportionsoftheapplication,aslong

asthenewclassesarepartoftheinheritancehierarchythatthe

applicationprocessesgenerically.Theonlypartsofan

applicationthatmustbealteredtoaccommodatenewclasses

arethosethatrequiredirectknowledgeofthenewclassesthat

theprogrammeraddstothehierarchy.Forexample,ifwe

extendclassAnimaltocreateclassTortoise(whichmightrespond

toaMovemessagebycrawlingoneinch),weneedtowriteonly

theTortoiseclassandthepartofthesimulationthatinstantiates

aTortoiseobject.Theportionsofthesimulationthatprocess

eachAnimalgenericallycanremainthesame.

Thischapterhasseveralparts.First,wediscusscommon

examplesofpolymorphism.Wethenprovidealive-code

exampledemonstratingpolymorphicbehavior.Asyouwillsoon

see,youwillusebaseclassreferencestomanipulatebothbase

classobjectsandderivedclassobjectspolymorphically.

Wethenpresentacasestudythatrevisitstheemployee

hierarchyofSection10.4.5.Wedevelopasimplepayroll

applicationthatpolymorphicallycalculatestheweeklypayof

severaldifferenttypesofemployeesusingeachemployee's

Earningsmethod.Thoughtheearningsofeachtypeofemployee

arecalculatedinaspecificway,polymorphismallowsusto

processtheemployees"inthegeneral."Inthecasestudy,we

enlargethehierarchytoincludetwonewclassesSalariedEmployee

(forpeoplepaidafixedweeklysalary)andHourlyEmployee(for

peoplepaidanhourlysalaryand"time-and-a-half"for

overtime).Wedeclareacommonsetoffunctionalityforallthe

classesintheupdatedhierarchyinan"abstract"class,Employee,

fromwhichclassesSalariedEmployee,HourlyEmployeeand

CommissionEmployeeinheritdirectlyandclass

BasePlusCommissionEmployee4inheritsindirectly.Asyouwillsoonsee,

whenweinvokeeachemployee'sEarningsmethodoffabase

classEmployeereference,thecorrectearningscalculationis



performedduetoC#'spolymorphiccapabilities.

Occasionally,whenperformingpolymorphicprocessing,we

needtoprogram"inthespecific."OurEmployeecasestudy

demonstratesthatanapplicationcandeterminethetypeofan

objectatexecutiontimeandactonthatobjectaccordingly.In

thecasestudy,weusethesecapabilitiestodeterminewhether

aparticularemployeeobjectisaBasePlusCommissionEmployee.Ifso,

weincreasethatemployee'sbasesalaryby10%.

ThechaptercontinueswithanintroductiontoC#interfaces.An

interfacedescribesasetofmethodsandpropertiesthatcanbe

calledonanobject,butdoesnotprovideconcrete

implementationsforthem.Programmerscandeclareclasses

thatimplement(i.e.,provideconcreteimplementationsforthe

methodsandpropertiesof)oneormoreinterfaces.Each

interfacemembermustbedeclaredinalltheclassesthat

implementtheinterface.Onceaclassimplementsaninterface,

allobjectsofthatclasshaveanis-arelationshipwiththe

interfacetype,andallobjectsoftheclassareguaranteedto

providethefunctionalitydescribedbytheinterface.Thisistrue

ofallderivedclassesofthatclassaswell.



[Page511]

Interfacesareparticularlyusefulforassigningcommon

functionalitytopossiblyunrelatedclasses.Thisallowsobjectsof

unrelatedclassestobeprocessedpolymorphicallyobjectsof

classesthatimplementthesameinterfacecanrespondtothe

samemethodcalls.Todemonstratecreatingandusing

interfaces,wemodifyourpayrollapplicationtocreateageneral

accounts-payableapplicationthatcancalculatepaymentsdue

fortheearningsofcompanyemployeesandforinvoiceamounts

tobebilledforpurchasedgoods.Asyouwillsee,interfaces

enablepolymorphiccapabilitiessimilartothoseenabledby

inheritance.



Thischapterendswithanintroductiontooperatoroverloading.

Inpreviouschapters,wedeclaredourownclassesandused

methodstoperformtasksonobjectsofthoseclasses.Operator

overloadingallowsustodefinethebehaviorofthebuilt-in

operators,suchas+,-and<,whenusedonobjectsofourown

classes.Thisprovidesamuchmoreconvenientnotationthan

callingmethodsforperformingtasksonobjects.







[Page511(continued)]



11.2.PolymorphismExamples

Wenowconsiderseveraladditionalexamplesofpolymorphism.

IfclassRectangleisderivedfromclassQuadrilateral(afour-sided

shape),thenaRectangleisamorespecificversionofa

Quadrilateral.Anyoperation(e.g.,calculatingtheperimeteror

thearea)thatcanbeperformedonaQuadrilateralobjectcan

alsobeperformedonaRectangleobject.Theseoperationsalso

canbeperformedonotherQuadrilaterals,suchasSquares,

ParallelogramsandTRapezoids.Thepolymorphismoccurswhenan

applicationinvokesamethodthroughabaseclassvariableat

executiontime,thecorrectderivedclassversionofthemethod

iscalled,basedonthetypeofthereferencedobject.Youwill

seeasimplecodeexamplethatillustratesthisprocessin

Section11.3.

Asanotherexample,supposewedesignavideogamethat

manipulatesobjectsofmanydifferenttypes,includingobjects

ofclassesMartian,Venusian,Plutonian,SpaceShipandLaserBeam.

Imaginethateachclassinheritsfromthecommonbaseclass

SpaceObject,whichcontainsmethodDraw.Eachderivedclass

implementsthismethod.Ascreen-managerapplication

maintainsacollection(e.g.,aSpaceObjectarray)ofreferencesto

objectsofthevariousclasses.Torefreshthescreen,thescreen

managerperiodicallysendseachobjectthesame

messagenamely,Draw.However,eachobjectrespondsina

uniqueway.Forexample,aMartianobjectmightdrawitselfin

redwiththeappropriatenumberofantennae.ASpaceShipobject

mightdrawitselfasabrightsilverflyingsaucer.ALaserBeam

objectmightdrawitselfasabrightredbeamacrossthescreen.

Again,thesamemessage(inthiscase,Draw)senttoavarietyof

objectshas"manyforms"ofresults.

Apolymorphicscreenmanagermightusepolymorphismto



facilitateaddingnewclassestoasystemwithminimal

modificationstothesystem'scode.Supposewewanttoadd

Mercurianobjectstoourvideogame.Todoso,wemustbuilda

MercurianclassthatextendsSpaceObjectandprovidesitsownDraw

methodimplementation.WhenobjectsofclassMercurianappear

intheSpaceObjectcollection,thescreenmanagercodeinvokes

methodDraw,exactlyasitdoesforeveryotherobjectinthe

collection,regardlessofitstype.SothenewMercurianobjects

simply"plugrightin"withoutanymodificationofthescreen

managercodebytheprogrammer.Thus,withoutmodifyingthe

system(otherthantobuildnewclassesandmodifythecode

thatcreatesnewobjects),programmerscanusepolymorphism

toincludeadditionaltypesthatmightnothavebeenenvisioned

whenthesystemwascreated.



[Page512]



SoftwareEngineeringObservation11.1

Polymorphismpromotesextensibility:Softwarethatinvokes

polymorphicbehaviorisindependentoftheobjecttypestowhich

messagesaresent.Newobjecttypesthatcanrespondtoexisting

methodcallscanbeincorporatedintoasystemwithoutrequiring

modificationofthebasesystem.Onlyclientcodethatinstantiatesnew

objectsmustbemodifiedtoaccommodatenewtypes.







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

Chapter 11. Polymorphism, Interfaces & Operator Overloading

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

×