Presentation is loading. Please wait.

Presentation is loading. Please wait.

Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 0 COSC3311 – Software Design Inheritance and.

Similar presentations


Presentation on theme: "Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 0 COSC3311 – Software Design Inheritance and."— Presentation transcript:

1 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 0 COSC3311 – Software Design Inheritance and Polymorphism OOSC2 chapters 14 and parts of 15-17

2 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 1 The Open-Closed Principle ACE D B FA’ G H I

3 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 2 What is inheritance?  Principle: Describe a new class not from scratch but as extension or specialization of one existing class — or several in the case of MULTIPLE inheritance. oFrom the module viewpoint: if B inherits from A, all the services of A are potentially available in B (possibly with a different implementation). oFrom the type viewpoint: inheritance is the ‘‘is-a’’ relation. If B inherits from A, whenever an instance of A is required, an instance of B will be acceptable.

4 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 3 Terminology  Parent, Heir  Ancestor, Descendant  The ancestors of B are B itself and the ancestors of its parents.  Proper ancestor, Proper descendant  Direct instance, Instance  The instances of A are the direct instances of its descendants.  (Other terminology: subclass, superclass, base class) A B feature

5 Department of Computer Science, York University Polymorphism & Dynamic Binding Object Oriented Software Construction 14/10/2015 10:15 AM 4

6 Department of Computer Science, York University Design Problem Suppose we had an array of figures and want to rotate all the figures in it. Each figure has its own rotation method

7 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 6 The traditional architecture figures: ARRAY[ANY] rotate_all_figures_in_array_by ( d : DEGREE) require d > 0 local f: ANY; i: INTEGER do from i := fig_array.lower until i = fig_array.upper loop f := fig_array[i] rotate(f, d) -- what happens with an unknown f? i := i + 1 end

8 Department of Computer Science, York University Traditional rotate (f: ANY; d: DEGREE) is do if ‘‘f is a CIRCLE’’ then …... elseif ‘‘f is a POLYGON’’ then... end  and similarly for all other routines such as display etc.!  What happens when we add a new figure type? oWe must update all routines rotate, display etc. Object Oriented Software Construction 14/10/2015 10:15 AM 7

9 Department of Computer Science, York University Single Choice Principle  What happens when we add a new figure type? oWe must update all routines rotate, display etc.  Single Choice Principle oWhenever a software system must support a set of alternatives (e.g. variants of a figure in graphic systems), one and only one module in the system should know their exhaustive list oLater, if variants are added (e.g. by introducing a class in the figure hierarchy for a new figure), we only have to update a single module – the point of single choice! oFollows from the Open-Close Principle Object Oriented Software Construction 14/10/2015 10:15 AM 8

10 Department of Computer Science, York University New solutions required!  Want to be able to add new kinds of figures without obreaking previous programs owithout modifying the method that rotates all figures  Solution opolymorphism & dynamic binding Object Oriented Software Construction 14/10/2015 10:15 AM 9

11 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 10 Example hierarchy FIGURE * OPEN_ FIGURE * CLOSED_ FIGURE * SEGMENTPOLYLINEPOLYGONELLIPSE CIRCLE RECTANGLETRIANGLE SQUARE extent* barycenter* … display* rotate … perimeter* perimeter+ perimeter++ diagonal... perimeter++ ++ side1 side2 * deferred + effective ++ redefined

12 Department of Computer Science, York University FIGURE polymorphism Object Oriented Software Construction 14/10/2015 10:15 AM 11 FIGURE * CLOSED_ FIGURE * barycenter* … display* rotate* … perimeter* POLYGONELLIPSE perimeter+ ++

13 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 12 Redefinition class POLYGON inherit CLOSED_FIGURE create make feature vertices: ARRAY [POINT] vertices_count: INTEGER perimeter: REAL is -- Perimeter length do from... until... loop Result := Result + (vertices[i]). distance (vertices [i + 1])...end invariant vertices.count >= 3 vertices_count = vertices.count end vertices[i] vertices[i+1]

14 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 13 Redefinition (cont’d) class RECTANGLE inherit POLYGON redefine perimeter end create make feature diagonal, side1, side2: REAL perimeter: REAL is -- Perimeter length do Result := 2 * (side1 + side2) end invariant vertices_count = 4 end side1 side2

15 Department of Computer Science, York University Solution figures: ARRAY[FIGURE] rotate_all_figures_in_array_by ( d : DEGREE) require d > 0 local f: FIGURE; i: INTEGER do from i := fig_array.lower until i = fig_array.upper loop -- static typing f := fig_array[i] -- dynamic binding f.rotate(d) -- polymorphism i := i + 1 end Object Oriented Software Construction 14/10/2015 10:15 AM 14

16 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 15 Applying the Single Choice Principle f: FIGURE c: CIRCLE p: POLYGON... create c.make (...) create p.make (...)... if... then f := c else f := p end... f.move (...) f.rotate (...) f.display (...)...

17 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 16 Genericity + Inheritance: Polymorphic data structures class STACK [G] feature... item: G is... put (x: G) is... end fs: STACK [FIGURE] r: RECTANGLE s: SQUARE t: TRIANGLE p: POLYGON... fs.put (p); fs.put (t); fs.put (s); fs.put (r) fs.item.display (SQUARE) (RECTANGLE) (TRIANGLE) (POLYGON) fs

18 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 17 Genericity vs. Inheritance LIST_OF_ BOOKS SET_OF_ BOOKS LIKED_LIST_ OF_BOOKS LIST_OF_ PEOPLE LIST_OF_ JOURNALS Abstraction Specialization Type parameterization

19 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 18 Polymorphism  Typing  Binding

20 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 19  Assume: p: POLYGON; r: RECTANGLE; t: TRIANGLE; x: REAL   Permitted: x := p.perimeter x := r.perimeter x := r.diagonal p := r  NOT permitted: x := p.diagonal (even just after p := r !) r := p Inheritance and polymorphism (POLYGON) (RECTANGLE) p r

21 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 20 Dynamic binding  What is the effect of the following (assuming some_test true)? if some_test then p := r else p := t end x := p.perimeter  Redefinition: A class may change an inherited feature, as with POLYGON redefining perimeter.  Polymorphism: p may have different forms at run-time.  Dynamic binding: Effect of p.perimeter depends on run-time form of p.

22 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 21 Polymorphism  Polymorphism means the ability to take several forms  In OO, it is entities (attributes, arguments, local variables) which can become attached to objects of different types  P: POLYGON; r:RECTANGLE; t: TRIANGLE The following are both valid: op := r op := t oAssignments in which the type of the source (RHS) is different than the target (LHS) are called polymorphic assignments  Since both RECTANGLE and TRIANGLE inherit from POLYGON we say that the type of the source conforms to the type of the target. oIn the reverse direction the assignment r := p is not valid because p does not conform to r.

23 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 22 Typing vs. Binding – OOSC2 chapter 17 AIRCRAFT * PLANE * COPTER * BOEINGAIRBUS A_320 B_747B_737 B_747_400 * deferred + effected ++ redefined lower_landing_gear* lower_landing_gear++ lower_landing_gear+

24 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 23 Typing vs. Binding  Binding should be checked at runtime (dynamically) oSo that the correct version of lower_landing_gear is invoked  Typing should be checked at compile time (statically) oRuntime is much too late to determine that you do not have lower_landing_gear

25 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 24 Typing vs. binding  What do we know about the feature to be called?  Static typing: At least one  Dynamic binding: The right one  Example: my_aircraft.lower_landing_gear

26 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 25 The Typing problem  Basic OO Construct: x.f (arg)  meaning: execute on the object attached to x the operation f, using the argument arg  The model is simple – at run time, this is what our systems do – calling features on objects, and passing arguments as necessary  From the simplicity of the model follows the simplicity of the typing problem, whose statement mirrors the structure of the Basic Construct:  When, and how, do we know that: oThere is a feature corresponding to f and applicable to the object? oarg is an acceptable argument for that feature?

27 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 26 Definition – statically typed system  Type violation: a runtime type violation occurs in the execution of a call x.f(arg) where x is attached to an object OBJ if either othere is no feature corresponding to f and and applicable to OBJ oThere is a feature but arg is not acceptable  An OO language is statically typed if it is equipped with a set of consistency rules so that a compiler can detect that there will be no runtime type violations merely by inspecting the program text (at compile time)

28 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 27 Consistency Rules (partial)  p: AIRBUS; a:ACCOUNT x: D x.f(arg) oDeclaration Rule: Every entity (e.g. x) must be explicitly declared to be of a certain type oCall rule: If a class C contains the call x.f(arg) there must be feature f in class D exported to C oAttachment Rule: In an assignment x := y (or argument passing) the base class of y must be a descendant of the base class of x.

29 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 28 (After Barry W. Boehm) RequirementsDesignCodeDevelopmentAcceptanceOperation test SMALL PROJECTS LARGE PROJECTS

30 Department of Computer Science, York University Inheritance & Contracts Object Oriented Software Construction 14/10/2015 10:15 AM 29

31 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 30 Invariant accumulation  Every class inherits all the invariant clauses of its parents.  These clauses are conceptually “and”-ed.

32 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 31 Accumulating invariants  Every routine will fail with an invariant contract violation

33 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 32 Inheritance and assertions  What is the relationship between postcondition C in POLYGON and D in RECTANGLE?  In the descendant RECTANGLE oRequire less oEnsure more  i.e. Why? o So that RECTANGLE should not be able to change the meaning of perimeter to area o Substitutivity

34 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 33 Substitutivity  Require less / Ensure more constrains an instance of RECTANGLE to act like an instance of POLYGON.  Hence the instance of RECTANGLE can always be substituted for an instance of POLYGON without changing the meaning of function routine perimeter  Without contracts you could not truly ensure substitutivity

35 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 34 Subcontracting Correct call: if a1. then a1.r (...) else... end r is require  ensure  r is require  ensure  CA B a1: A a1.r (…) …

36 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 35  Redefined version may not have require or ensure.  May have nothing (assertions kept by default), or require else new_pre ensure then new_post  Resulting assertions are: ooriginal_precondition or new_pre ooriginal_postcondition and new_post Assertion redeclaration rule

37 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 36 Why Contracts?  Specifications (vs. implementations)  Documents the contract between client and supplier o contract view (information hiding)  Validating the implementation oCheck that the implementation satisfies the specification oCatches many errors oVerification via formal methods  Defines an exception (contract violation)  Subcontracting (ensures substitutivity)

38 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 37 The meaning of inheritance  The type perspective: oAutomatic adaptation of operations to the dynamic form of their targets (extendibility): Representation independence. oFactoring out reusable operations: Commonality.  The module perspective (reusability): oOpen-closed modules oModularity oThe Single Choice Principle

39 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 38 The dangers of static binding  For every creation procedure cp: {pre cp } do cp {post cp and INV}  For every exported routine r: {INV and pre r } do r {INV and post r }  The worst possible erroneous run-time situation in object-oriented software development: oProducing an object that does not satisfy the invariant of its class. a.f (…) a.g (…) a.f (…) create a.make (…) S1 S2 S3 S4

40 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 39 The dangers of static binding (cont’d)  {INV A } do r A {INV A }  {INV B } do r B {INV B }  Consider a call of the form a1.r where a1 is polymorphic: oNo guarantee on the effect of do r A on an instance of B! A B rArA r B ++

41 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 40 A concrete example w: WINDOW b: BUTTON create b w := b w.display WINDOW BUTTON display display++

42 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 41 Using original version of redefined feature class BUTTON inherit WINDOW redefine display end feature display is do Precursor display_border display_label end display_label is do... end display_border is do... end

43 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 42 Use of Precursor  Not necessarily the first feature statement.  May have arguments. class B inherit A redefine my_feature end feature my_feature (args: SOME_TYPE) is do -- Something here Precursor (args) -- Something else here end A B my_feature my_feature++

44 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 43 Assignment Attempt (OOSC2 16.5)  Suppose we want to find out the longest diagonal (rectangles only) in a list of figures.  Suppose we were retrieving the list from a network or from a stored file where we could not guarantee the type of the object.

45 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 44 Forcing a type: the problem list: LIST [FIGURE] x: RECTANGLE list.store ("FILE_NAME")  Two years later: list := retrieved ("FILE_NAME") x := list.item-- [1] print (x.diagonal)-- [2]  But oIf x is declared of type RECTANGLE, [1] will not compile. oIf x is declared of type FIGURE, [2] will not compile.

46 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 45 What not to do! if “list.item is of type RECTANGLE” then … elseif “list.item is of type CIRCLE” then etc.  We could so the above as in ANY we have: conforms_to (other: ANY): BOOLEAN is -- Is type of current object identical to type of `other'?

47 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 46 Assignment attempt (cont’d) x ?= y with x: A  If y is attached to an object whose type conforms to A, perform normal reference assignment.  Otherwise, make x void.

48 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 47 Calculating largest diagonal in list – Solution list: LIST[FIGURE] maximum_diagonal (file_name: STRING): REAL -- Max value of diagonals of rectangles in list retrieved from storage or network -- -1 if none local r: RECTANGLE do Result := -1 list ?= retrieved(“file_name”) if list /= Void then -- file contains an object structure that conforms to LIST[FIGURE] from list.start; until list.after loop r ?= list.item if r /= Void then -- list.item conforms to RECTANGLE Result := Result.max(r.diagonal) end list.forth end

49 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 48 Feature Call Rule is Preserved r ?= list.item if r /= Void then Result := Result.max(r.diagonal) end  r.diagonal is guarded ostatically, by a compiler check that diagonal is a feature of class RECTANGLE odynamically by a guarantee that r /= Void

50 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 49 Multiple inheritance  A class may have two or more parents.  What not to use as an elementary example: TEACHING_ASSISTANT inherits from TEACHER and STUDENT. TEACHERSTUDENT TEACHING_ ASSISTANT

51 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 50 The teaching assistant example  This is in fact a case of repeated inheritance: TEACHERSTUDENT TEACHING_ ASSISTANT UNIVERSITY_ PERSON id ?? ????

52 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 51 Common examples of multiple inheritance  Combining separate abstractions: oRestaurant, train car oCalculator, watch oPlane, asset

53 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 52 Multiple inheritance: Combining abstractions COMPARABLENUMERIC STRINGCOMPLEX INTEGER REAL DOUBLE **

54 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 53 Multiple inheritance: Nested windows  ‘‘Graphical’’ features: height, width, change_height, change_width, xpos, ypos, move...  ‘‘Hierarchical’’ features: superwindow, subwindows, change_subwindow, add_subwindow... class WINDOW inherit RECTANGLE TREE [WINDOW] feature... end

55 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 54 Multiple inheritance: Composite figures A composite figure Simple figures

56 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 55 Defining the notion of composite figure FIGURE LIST [FIGURE] COMPOSITE_ FIGURE * display hide rotate move … count put remove …

57 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 56 Defining the notion of composite figure through multiple inheritance FIGURE LIST [FIGURE] COMPOSITE_ FIGURE * OPEN_ FIGURE CLOSED_ FIGURE SEGMENT POLYLINE POLYGON ELLIPSE RECTANGLE SQUARE CIRCLE TRIANGLE … perimeter+ perimeter* perimeter++ perimeter+ diagonal …

58 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 57 A composite figure as a list start item forthafter

59 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 58 Composite figures class COMPOSITE_FIGURE inherit FIGURE redefine display, move, rotate,... end LIST [FIGURE] feature display is -- Display each constituent figure in turn. do from start until after loop item.display forth end end... Similarly for move, rotate etc.... end

60 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 59 Complex figures  Note: a simpler form of procedures display, move etc. can be obtained through the use of iterators.  Exercise: Use agents for that purpose.

61 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 60 Name clashes under multiple inheritance A C foo B

62 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 61 Resolving name clashes A C foo B rename foo as fogrename foo as zoo

63 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 62 Resolving name clashes (cont’d) class C inherit A rename foo as fog end B rename foo as zoo end feature...

64 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 63 Results of renaming a1: A b1: B c1: C... c1.fog c1.zoo a1.foo b1.foo Invalid: a1.fog, a1.zoo, b1.zoo, b1.fog, c1.foo

65 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 64 Another application of renaming  Provide locally better adapted terminology.  class TREE feature child: TREE[WINDOW] end  class WINDOW inherit TREE feature rename child as subwindow end

66 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 65 The marriage of convenience class ARRAYED_STACK [G] inherit STACK [G] ARRAY [G] feature... end class LINKED_STACK [G] inherit STACK [G] LINKED_LIST [G] feature... end

67 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 66 The need for deferred classes  In the scheme seen earlier: f: FIGURE; c: CIRCLE; p: POLYGON... create c.make (...); create p.make (...)... if... then f := c else f := p end... f.move (...); f.rotate (...); f.display (...);...  How do we ensure that a call such as f.move (...) is valid even though there is no way to implement a general-ee- purpose feature move for class FIGURE?

68 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 67 Deferred classes deferred class FIGURE feature move (v: VECTOR) is deferred end rotate (a: ANGLE; p: POINT) is deferred end... display, hide,... end Not permitted: create f...

69 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 68 Example hierarchy FIGURE * OPEN_ FIGURE * CLOSED_ FIGURE * SEGMENTPOLYLINEPOLYGONELLIPSE CIRCLE RECTANGLETRIANGLE SQUARE extent* barycenter* … display* rotate … perimeter* perimeter+ perimeter++ diagonal... perimeter++

70 Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 69 Deferred classes and features  A feature is either deferred or effective.  To effect a inherited feature (deferred in the parent) is to make it effective. No need for redefine clause.  Like a feature, a class is either deferred or effective.  A class is deferred if it has at least one deferred feature (possibly coming from an ancestor) that it does not effect. It is effective otherwise.  A deferred class may not be instantiated.  BUT: A deferred class may have assertions (in particular, a deferred routine may have a precondition and a postcondition, and the class may have a class invariant).


Download ppt "Department of Computer Science, York University Object Oriented Software Construction 14/10/2015 10:15 AM 0 COSC3311 – Software Design Inheritance and."

Similar presentations


Ads by Google