learning to program with c# - 41 unit 5 adding behaviour using inheritanceadding behaviour using...

15
Learning to Program with Learning to Program with C# - 4 C# - 4 1 Unit 5 Unit 5 Adding Adding behaviour using behaviour using inheritance inheritance Introducing Introducing polymorphism polymorphism the ability of a single piece of the ability of a single piece of code to operate with objects of code to operate with objects of different shapes different shapes

Upload: andrew-summers

Post on 29-Jan-2016

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

11

Unit 5Unit 5

• AddingAdding behaviour using behaviour using inheritanceinheritance

• Introducing Introducing polymorphismpolymorphism– the ability of a single piece of code to the ability of a single piece of code to

operate with objects of different operate with objects of different shapesshapes

Page 2: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

22

A simple addition firstA simple addition first

• In each rocket controller, we re-In each rocket controller, we re-write the same code for taking offwrite the same code for taking off– how about adding a how about adding a TakeOffTakeOff method, method,

which contains the necessary which contains the necessary instructions?instructions?

– in each version of in each version of FlyFly that we write, that we write, we can simply call the we can simply call the TakeOffTakeOff method rather than having to include method rather than having to include all those instructionsall those instructions

Page 3: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

33

Examine this solution…Examine this solution…• We are now working with the Visual Studio We are now working with the Visual Studio

solution directory solution directory AdvancedRocketryAdvancedRocketry– Open up the Rocketry solution in itOpen up the Rocketry solution in it– Look for and open the AutoRocketController classLook for and open the AutoRocketController class– Use the members pull-down to get to the new Use the members pull-down to get to the new

TakeOff methodTakeOff method– and then go to the AutoFly method to see it in useand then go to the AutoFly method to see it in use

Page 4: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

44

General technique…General technique…• We observed that we wanted additional We observed that we wanted additional

behaviour – in this case a set of operations behaviour – in this case a set of operations performed regularlyperformed regularly

• We added a new method in a derived class of We added a new method in a derived class of the originalthe original– Users of our engineering can now use either versionUsers of our engineering can now use either version

• Try it out for yourselfTry it out for yourself– add to this class a method LoopTheLoop, including add to this class a method LoopTheLoop, including

the necessary code to perform a loop, and then use the necessary code to perform a loop, and then use it in the AutoFly methodit in the AutoFly method• easiest: take a copy of TakeOff and change the name and easiest: take a copy of TakeOff and change the name and

code appropriatelycode appropriately

Page 5: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

55

• Look around the rest of the classLook around the rest of the class– notice it is inherited from notice it is inherited from

RocketControllerRocketController• how can you tell this…?how can you tell this…?

– it has quite a different kind of Fly it has quite a different kind of Fly method, and there's a complicated method, and there's a complicated looking Land method toolooking Land method too• We'll explore these nextWe'll explore these next

Page 6: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

66

Motivation, using RocketryMotivation, using Rocketry• Consider the Fly methods we've builtConsider the Fly methods we've built

– We have written a simple sequence of instructions that We have written a simple sequence of instructions that depend on knowing the exact layout of the arenadepend on knowing the exact layout of the arena

– This is fine for some applications – ballistic missile for This is fine for some applications – ballistic missile for example!example!

• Now consider sending a rocket to the moon or Now consider sending a rocket to the moon or another planetanother planet– Can we risk being so certain of our surroundings?Can we risk being so certain of our surroundings?– History says no, since Neil Armstrong had to take over History says no, since Neil Armstrong had to take over

from the 'fixed' landing sequence to avoid Apollo 11 from the 'fixed' landing sequence to avoid Apollo 11 crashing into a cratercrashing into a crater

• So we need increased So we need increased adaptabilityadaptability

Page 7: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

77

AdaptabilityAdaptability

• We need for the RocketController to adjust We need for the RocketController to adjust the instructions it sends to the rocket…the instructions it sends to the rocket…– on the basis of the surrounding environment…on the basis of the surrounding environment…– for example, how fast and in what direction is the for example, how fast and in what direction is the

rocket travelling? what obstacles are nearby?rocket travelling? what obstacles are nearby?

• Neil Armstrong was a very adaptable Neil Armstrong was a very adaptable controllercontroller

• he had gauges in the spacecraft to check his velocityhe had gauges in the spacecraft to check his velocity• he looked out of the window and saw the nasty cratershe looked out of the window and saw the nasty craters

– we need these abilitieswe need these abilities

Page 8: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

88

Extending the Rocketry Extending the Rocketry modelmodel

• The rocket controller must be able to The rocket controller must be able to interrogateinterrogate– the Rocketthe Rocket

• how fast are you moving in each direction?how fast are you moving in each direction?• what is your attitude?what is your attitude?• … … to ensure safe landingsto ensure safe landings

– the Arenathe Arena• How close is the nearest obstacle in each How close is the nearest obstacle in each

direction?direction?• … … to avoid crashes along the way, and land safelyto avoid crashes along the way, and land safely

Page 9: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

99

Explore with the Object Explore with the Object browserbrowser

• IAdvancedRocket & IAdvancedArenaIAdvancedRocket & IAdvancedArena– These both inherit from simpler versions of Rocket These both inherit from simpler versions of Rocket

and Arena respectivelyand Arena respectively– Examine the added methodsExamine the added methods

• exactly the interrogation functionality we needexactly the interrogation functionality we need

• and run ExecuteMission to see the new and run ExecuteMission to see the new AutoRocketController in actionAutoRocketController in action– you will see the rocket automatically landing itselfyou will see the rocket automatically landing itself– experiment by changing the in-flight code, see if it experiment by changing the in-flight code, see if it

still manages to perform a safe landingstill manages to perform a safe landing– we will look at the detail of the Land method in Unit we will look at the detail of the Land method in Unit

7 – it is interesting stuff…7 – it is interesting stuff…

Page 10: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

1010

What's the point of all What's the point of all this?this?

• We have two kinds each of Rocket & ArenaWe have two kinds each of Rocket & Arena– the simple and the advanced version, defined by the simple and the advanced version, defined by interfacesinterfaces

• and an implementation for each interfacesand an implementation for each interfaces– Rocket, AdvancedRocket, SimpleArena, AdvancedArenaRocket, AdvancedRocket, SimpleArena, AdvancedArena

• Think of an interface as a contractual Think of an interface as a contractual agreement on services suppliedagreement on services supplied

• IRocket specifies a limited service, IAdvancedRocket IRocket specifies a limited service, IAdvancedRocket a slightly more advanced servicea slightly more advanced service

Page 11: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

1111

Interfaces as contractual Interfaces as contractual agreementagreement• A class can guarantee to produce objects meeting these A class can guarantee to produce objects meeting these

agreementsagreements– e.g. Rocket guarantees to meet the interface IRockete.g. Rocket guarantees to meet the interface IRocket

• Now, many different factories can produce objects Now, many different factories can produce objects meeting the specificationmeeting the specification– We have a competitive market for the best implementation of a We have a competitive market for the best implementation of a

given interfacegiven interface– Note that the free market hasn't yet come to Rocketry – there is Note that the free market hasn't yet come to Rocketry – there is

only one factory for each kind of objectonly one factory for each kind of object

• Why have we built Rocketry this way?Why have we built Rocketry this way?– it is good engineering practiceit is good engineering practice– we've shared/reused as much design/code as possiblewe've shared/reused as much design/code as possible– all the components we've created may be flexibly used with all the components we've created may be flexibly used with

one another…one another…

Page 12: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

1212

InteroperationInteroperation• The original RocketController will work withThe original RocketController will work with

– any class that implements IRocketany class that implements IRocket– any class that implements IArenaany class that implements IArena– this includes the advanced versions of Rocket and Arena, this includes the advanced versions of Rocket and Arena,

because they are because they are derivedderived from the simpler versions from the simpler versions

• This feature is known as This feature is known as polymorphismpolymorphism– literally: poly – many, morphism – shapesliterally: poly – many, morphism – shapes– the Rocket Controller will handle rockets and arenas of many the Rocket Controller will handle rockets and arenas of many shapesshapes

• Key benefit here:Key benefit here:– Old code (e.g. RocketController) is Old code (e.g. RocketController) is guaranteedguaranteed to still work with to still work with

new code (e.g. AdvancedRocket)new code (e.g. AdvancedRocket)– Huge cost savingsHuge cost savings

Page 13: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

1313

Page 14: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

1414

AnalogyAnalogy

• Video recorderVideo recorder– Any video recorder, no matter how new and Any video recorder, no matter how new and

with however many new features, will still with however many new features, will still play through virtually any televisionplay through virtually any television

– Why? because the interface specification – the Why? because the interface specification – the aerial socket – is still supportedaerial socket – is still supported• even though the new SCART connectors have also even though the new SCART connectors have also

been added, the original coaxial connection is still been added, the original coaxial connection is still therethere

– Although note this interface is country-specificAlthough note this interface is country-specific• The interface specification in the UK is PAL…The interface specification in the UK is PAL…• … … and in the US it is NTSCand in the US it is NTSC

Page 15: Learning to Program with C# - 41 Unit 5 Adding behaviour using inheritanceAdding behaviour using inheritance Introducing polymorphismIntroducing polymorphism

Learning to Program with C# Learning to Program with C# - 4- 4

1515

SummarySummary

• Extended the concepts around Extended the concepts around inheritanceinheritance– this time, we this time, we addedadded behaviour behaviour

• Introduced the Introduced the interfaceinterface– a contractual agreement on minimum services a contractual agreement on minimum services

provided by a classprovided by a class

• Introduced the concept of Introduced the concept of polymorphismpolymorphism– objects of many different classes objects of many different classes appearappear to be to be

of the one class or interface, ifof the one class or interface, if• they are derived from that one class, orthey are derived from that one class, or• they implement the interfacethey implement the interface

– improves code reuse and interoperabilityimproves code reuse and interoperability