Kate Gregory Week 6 Lab 3 due now –Rating your group Inheritance Multiple Inheritance Polymorphism...

Preview:

Citation preview

Kate Gregory

Week 6

• Lab 3 due now– Rating your group

• Inheritance

• Multiple Inheritance

• Polymorphism

• Midterm Review

Date Week Topic Hand Out Due Back Test

6-Sep-13 1 Administrivia / Overview / Motivation, benefits of OO

13-Sep-13 2 Use Cases Lab 1: Use cases

20-Sep-13 3 CRC Cards, collab graphs Lab 2: CRC cards lab 1 5%

27-Sep-134 start class diag lab 2 5%

4-Oct-13 5 Finish class diag, Associations Lab 3: Class Diag

11-Oct-13 6 Inh & Polymorphism / midterm review   lab 3 5%  

18-Oct-13 7 midterm Midterm 25%

25-Oct-13 Reading Break

1-Nov-13 8 Interaction diag / Design Patterns Lab 4: Interaction Diag    

8-Nov-13 9 Good Design / Modules & Packages / Deployment and component diagrams /Metrics / SOLID

Lab 5: Critiques lab 4 5%

15-Nov-13 10 State diagrams / Activity diagrams / Summary and Conclusion / The Future

22-Nov-13 11 Critiques critique lab (before class) 15%

29-Nov-13 12 Critiques

TBD Final Exam Final 40%

Kate Gregory

Inheritance

• Programming by extension• One class is based on (is derived from)

another class.• Inheritance allows classes to share and

reuse behaviors and attributes.– Code and design

• Build on existing work– Designing, coding, testing

Kate Gregory

From the General to the Specific

• The base class or super class is general: animal, vehicle, bank account

• The derived classes or subclasses are specific: mammal, car, savings account

• You add functionality as you move from the general to the specific: mammals can do things that not all animals can

• You cannot remove functionality

Kate Gregory

Inheritance Example

Kate Gregory

IS A

• Inheritance examples should make sense with “is a”.– A mammal is an animal– An ungulate is a mammal– A savings account is a bank account– A rush order is an order– A car is a vehicle

• Is a car an engine with metal wrapped around it?

IS A Problems

• Square and Rectangle have obvious similarities– Location in space

– Can calculate area (similar formula)

– Rectangle has height and width, Square has only height

• Square IS A Rectangle?– Can’t suppress functionality

• Rectangle IS A Square?– Doesn’t make any sense

Kate Gregory

Square and Rectangle

Square

Location: PointWidth: int

GetArea(): intMove(Point)GetWidth(): intSetWidth(int)

Rectangle

Location: PointWidth: intHeight: intGetArea(): intMove(Point)GetWidth(): intSetWidth(int)GetHeight(): intSetHeight(int)

Square and Rectangle

Square

Rectangle

Square inherits all Rectangle functions including GetHeight() and SetHeight()

Square and Rectangle

Rectangle

Square

Rectangle adds functions including GetHeight() and SetHeight(), adds attribute height

Abstract Base Class

• Quadrilateral– Has location in space, idea of a function for area

• Rectangle IS A Quadrilateral– With height and width

– Implements area function

• Square IS A Quadrilateral– With height

– Implements area function

Kate Gregory

Abstract Base Class

Square

Width: int

GetArea(): intGetWidth(): intSetWidth(int)

Rectangle

Width: intHeight: int

GetArea(): intGetWidth(): intSetWidth(int)GetHeight(): intSetHeight(int)

Quadrilateral

Location: Point

GetArea(): intMove(Point)

Abstract Classes

• An abstract class can’t be used to generate an object– Can you open just a bank account?

• Subclasses must implement the un-implemented methods or they are also abstract

• You instantiate objects of the subclasses

Kate Gregory

Not all Base Classes are Abstract

• Use it when no complete (working) class has all the common functionality

• Don’t go out of your way to invent ABC when a concrete class can be a good base class– Eg Rush Order inherits from Order, don’t need

to create abstract Order with Rush Order and Regular Order as subclasses

Kate Gregory

Kate Gregory

Multiple Inheritance• Some OO systems (C++, not Java or C#)

permit a class to inherit from more than one superclass.

• This kind of inheritance is referred to as multiple inheritance.

Kate Gregory

Multiple Inheritance Example

• Utility vehicle inherits from Car and Truck classes.

MotorVehicle

Truck Car Bus

UtilityVehicle

Kate Gregory

Diamond Problem: Bad M.I.

Disambiguatingoverride

Appliance

+turnOn() : boolean+turnOff() : boolean

-poweredup : boolean

Clock

+setAlarm() : boolean+turnOn() : boolean

-time : int

Radio

+turnOn() : boolean

-station : int

ClockRadio

Diamond Problem

• What happens here?

ClockRadio cr;

cr.turnOn();• Need a disambiguating override

Kate Gregory

Kate Gregory

Good Multiple Inheritance

• Problem : Track RCMP transportation– Includes: Car, PowerBoat, Bike, Canoe,

SeaDoo and Horse.– Track schedules for changing oil, rotating tires,

feeding, checkingForHoles etc.– Use inheritance as much as possible since we

only want to write the code once !

Kate Gregory

Vehicle

Land Sea Air

Car Horse Bike PowerBoat Canoe SeaDoo

Kate Gregory

Vehicle

AnimalPowered HumanPowered

BikeCanoeHorse

M otorized

PowerBoatSeaDooCar

Kate Gregory

Vehicle is still base class for these three.

Land Sea Air

Car Horse Bike PowerBoat Canoe SeaDoo

Motorized

+changeOil()

+rotateTires()

What if there’s no MI allowed?• No need to inherit code, just design:

– Interface

– Keep substitutability, IS-A, polymorphism

• Need to inherit (reuse, maintain) code:– Use aggregation instead

– Wrapper functions delegate to helper class

– Drawbacks• if helper class adds a method you must add the wrapper by

hand to all who use it

• No polymorphism

Kate Gregory

Kate Gregory

Kate Gregory

Polymorphism

Motor Vehicle

+colour: ?+price: ?+model: ?

+go()+stop()+turn left()+turn right()

Bus Truck Car

Ford Mustang

+stop()+go()

Toyota Corolla Pontiac Sunfire

Kate Gregory

Polymorphism

• Imagine an array of MotorVehicles holding objects of Car, Truck and Bus, as well as, Mustang, Corolla and Sunfire. All are subclasses of Motor Vehicle.

• Code asks each vehicle in the array to stop.

• When the vehicle is a Mustang, the Mustang override of Stop without the calling code having to figure out which specific subclass the vehicle belongs.

• The correct version of a method will be called even though the object is being referred to in more generic terms.

Kate Gregory

Uses of Polymorphism

• Here are a whole pile of shapes - draw them on the screen

• Here are a whole pile of bank accounts - print their statements

• Here are a whole pile of employees - print their paycheques

Kate Gregory

Polymorphism benefit

The old way:struct shape {

int type;

struct point reference;

int dimension1;

int dimension2;

int dimension3; /* ...*/ };

Kate Gregory

Using the structstruct shape circle, square;/* fill them with values somehow*//* put pointers to them into an array */for (i=0; i<numshapes; i++){ switch (array[i].type) { case CIRCLE: drawcircle(array[i]); break; case SQUARE: drawsquare(array[i]); break;/* etc */ }}

Kate Gregory

Without Polymorphism

• What is involved in adding a new shape?– #define for type– another case statement in the switch– new drawing method – the code that created the shape and added it to

the array

• Four different files

Kate Gregory

With Polymorphism

class Shape {

protected:

Point reference;

public:

virtual void draw();

};

Kate Gregory

class Circle: public Shape {private: int radius;public: void draw();};

class Square: public Shape {private: int width;public: void draw();};

Kate Gregory

Circle circle;Square square;/* fill them with values somehow*//* put pointers to them into an array */for (i=0; i<numshapes; i++){ array[i]->draw();}

Using the classes

Kate Gregory

With Polymorphism

• What is involved in adding a new shape?– New class definition– code for draw() method – the code that created the shape and added it to

the array

• Two or three different files– can get compiler to remind you to write the

function

Inheritance and Relationships

• On your class diagram, if a Person can own any kind of Vehicle, draw the line to Vehicle, not to each subclass

• If for some reason a Company can own any kind of Vehicle but a Person can only own a Car, draw the lines to show that.

Kate Gregory

Kate Gregory

Next Weeks

• Oct 18th - midterm – Covers till the end of this lecture

• Oct 25th, no lecture– Reading Week

• Nov 1st – Interaction diagrams, design patterns– Lab 4 on interaction diagrams (due Nov 8th)

Midterm Location

• Science Complex Lecture Hall (SC 137)

• Not This Room!

• We will start shortly after 9am and run for one hour

• There will not be a lecture afterwards

Kate Gregory

Kate Gregory

Midterm

• Worth 25% of final grade• One hour• Closed book• Covers up to today’s class• True/False – Multiple Choice 20%• Short Answer -- <= One sentence 20%• Long Answer – diagrams, paragraphs etc. 60%