Download presentation
Presentation is loading. Please wait.
Published byArnhild Stene Modified over 6 years ago
1
Inheritance and Polymorphism OOSC2 chapters 14 and parts of 15-17
1/16/2019 1:45 PM COSC3311 – Software Design Inheritance and Polymorphism OOSC2 chapters 14 and parts of 15-17 Object Oriented Software Construction /01/2019 1:45 PM 0
2
The Open-Closed Principle
1/16/2019 1:45 PM The Open-Closed Principle B A C E D F A’ G H I Object Oriented Software Construction /01/2019 1:45 PM 1
3
Open-Closed Principle
Modules should be both Open and Closed It is open if it is available for extension (Volatile?) It is closed if it’s API is fixed i.e. clients can rely on well-defined interface that does not change (Stable?) (The implementation may change) It’s a contradiction! Resolved via inheritance! Inheritance is not just for classification (taxonomy) but also for re-use Object Oriented Software Construction /01/2019 1:45 PM 2
4
1/16/2019 1:45 PM 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. From the module viewpoint: if B inherits from A, all the services of A are potentially available in B (possibly with a different implementation). From 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. Object Oriented Software Construction /01/2019 1:45 PM 3
5
Terminology Parent, Heir Ancestor, Descendant
1/16/2019 1:45 PM 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) feature A feature B Definition: heir, parent If class C has a Parent clause for B, then C is said to inherit from B; B is said to be a parent of C, and C is said to be an heir of B. Definition: ancestor, descendant Class A is an ancestor of class B if and only if A is B itself or, recursively, an ancestor of one of B's parents. Class B is a descendant of class A if and only if A is an ancestor of B, in other words if B is A or (recursively) a descendant of one of its heirs. Definition: proper ancestor, descendant The proper ancestors of a class C are its ancestors other than C itself. The proper descendants of a class B are its descendants other than B itself. Object Oriented Software Construction /01/2019 1:45 PM 4
6
Polymorphism & Dynamic Binding
Object Oriented Software Construction /01/2019 1:45 PM 5
7
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
8
The traditional architecture
1/16/2019 1:45 PM 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 := figures.lower until i = figures.upper loop f := figures[i] rotate(f, d) -- what happens with an unknown f? i := i + 1 end Each routine display, move, scale would have to be changed with a new figure class Object Oriented Software Construction /01/2019 1:45 PM 7
9
Traditional rotate (f: ANY; d: DEGREE) 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? We must update all routines rotate, display etc. Object Oriented Software Construction /01/2019 1:45 PM 8
10
Single Choice Principle
What happens when we add a new figure type? We must update all routines rotate, display etc. Single Choice Principle Whenever 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 Later, 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! Follows from the Open-Close Principle Object Oriented Software Construction /01/2019 1:45 PM 9
11
New solutions required!
Want to be able to add new kinds of figures without breaking previous programs without modifying the method that rotates all figures Solution polymorphism & dynamic binding Object Oriented Software Construction /01/2019 1:45 PM
12
FIGURE polymorphism FIGURE * CLOSED_ FIGURE POLYGON ELLIPSE + display*
barycenter* … display* rotate* perimeter* POLYGON ELLIPSE perimeter+ + Object Oriented Software Construction /01/2019 1:45 PM
13
Example hierarchy * FIGURE * * OPEN_ FIGURE CLOSED_ FIGURE + + SEGMENT
1/16/2019 1:45 PM Example hierarchy extent* display* * deferred + effective ++ redefined barycenter* * rotate* … FIGURE … * * OPEN_ FIGURE CLOSED_ FIGURE perimeter* perimeter+ perimeter+ + + SEGMENT POLYLINE POLYGON ELLIPSE perimeter++ ... TRIANGLE RECTANGLE diagonal side1 CIRCLE side2 perimeter++ perimeter++ SQUARE Object Oriented Software Construction /01/2019 1:45 PM
14
Redefinition class POLYGON inherit CLOSED_FIGURE create make feature
1/16/2019 1:45 PM Redefinition class POLYGON inherit CLOSED_FIGURE create make feature vertices: ARRAY [POINT] vertices_count: INTEGER perimeter: REAL -- Perimeter length do from ... until ... loop Result := Result + (vertices[i]) . distance (vertices [i + 1]) ... end end invariant vertices.count >= 3 vertices_count = vertices.count end vertices[i] vertices[i+1] Object Oriented Software Construction /01/2019 1:45 PM
15
Redefinition (cont’d)
1/16/2019 1:45 PM 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 side2 side1 Object Oriented Software Construction /01/2019 1:45 PM
16
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 /01/2019 1:45 PM
17
Applying the Single Choice Principle
1/16/2019 1:45 PM 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 (...) Dynamic binding ensures that the right routine e.g. `move’ is selected. Do not need a long time If statement Easy to add a new kind of figure Object Oriented Software Construction /01/2019 1:45 PM
18
Polymorphism Typing Binding 1/16/2019 1:45 PM
Object Oriented Software Construction /01/2019 1:45 PM
19
Inheritance and polymorphism
1/16/2019 1:45 PM Inheritance and polymorphism 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 p (POLYGON) r (RECTANGLE) Object Oriented Software Construction /01/2019 1:45 PM
20
1/16/2019 1:45 PM 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 RECTANGLE redefining perimeter. Polymorphism: p may have different forms at run-time. Dynamic binding: Effect of p.perimeter depends on run-time form of p. Object Oriented Software Construction /01/2019 1:45 PM
21
Polymorphism Polymorphism means the ability to take several forms
1/16/2019 1:45 PM 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: p := r p := t Assignments 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. In the reverse direction the assignment r := p is not valid because p does not conform to r. Object Oriented Software Construction /01/2019 1:45 PM
22
Type checking When should we check typing and binding?
1/16/2019 1:45 PM Type checking When should we check typing and binding? statically (compile time) dynamically (runtime) Runtime or Compile time Object Oriented Software Construction /01/2019 1:45 PM
23
Typing – OOSC2 chapter 17 * AIRCRAFT * * PLANE COPTER BOEING AIRBUS
1/16/2019 1:45 PM Typing – OOSC2 chapter 17 * deferred * + effected AIRCRAFT ++ redefined * * PLANE COPTER lower_landing_gear* BOEING AIRBUS A_320 B_737 B_747 a: ARRAY[AIRCRAFT] a[i].lower_landing_gear target.f(arg) lower_landing_gear+ B_747_400 lower_landing_gear++ Object Oriented Software Construction /01/2019 1:45 PM
24
Check at compile time or runtime?
1/16/2019 1:45 PM Check at compile time or runtime? when should we check that there is a feature lower_landing_gear (compile time or runtime)? If there is more than one (polymorphism), when should we determine which one to use? a: PLANE b: B_747 a := b a.take_off ... a.lower_landing_gear Question (1) is the typing problem Question (2) is the binding problem Object Oriented Software Construction /01/2019 1:45 PM
25
Check at compile time or runtime?
a: PLANE b: B_747 a := b a.take_off ... a.lower_landing_gear runtime is much too late to find out that you do not have landing gear Object Oriented Software Construction /01/2019 1:45 PM
26
Typing vs. Binding Binding should be checked at runtime (dynamically)
1/16/2019 1:45 PM Typing vs. Binding Binding should be checked at runtime (dynamically) So that the correct version of lower_landing_gear is invoked Typing should be checked at compile time (statically) Runtime is much too late to determine that you do not have lower_landing_gear Object Oriented Software Construction /01/2019 1:45 PM
27
Typing vs. binding What do we know about the feature to be called?
1/16/2019 1:45 PM 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 Object Oriented Software Construction /01/2019 1:45 PM
28
The Typing problem Basic OO Construct: x.f (arg)
1/16/2019 1:45 PM 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: There is a feature corresponding to f and applicable to the object? arg is an acceptable argument for that feature? Object Oriented Software Construction /01/2019 1:45 PM
29
Definition – statically typed system
1/16/2019 1:45 PM 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 there is no feature corresponding to f and and applicable to OBJ There 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) Object Oriented Software Construction /01/2019 1:45 PM
30
Consistency Rules (partial)
1/16/2019 1:45 PM Consistency Rules (partial) x: D … x.f(arg) Declaration Rule: Every entity (e.g. x) must be explicitly declared to be of a certain type Call rule: If a class C contains the call x.f(arg) there must be feature f in class D exported to C Attachment Rule: In an assignment x := y (or argument passing) the base class of y must be a descendant of the base class of x. Object Oriented Software Construction /01/2019 1:45 PM
31
(After Barry W. Boehm) LARGE PROJECTS SMALL PROJECTS 1/16/2019 1:45 PM
Cost of Fixing a Problem (y-axis) versus time/development phase (y-axis) Detecting problems (like type violations) earlier (at compile time) saves development costs SMALL PROJECTS Requirements Design Code Development Acceptance Operation test test Object Oriented Software Construction /01/2019 1:45 PM
32
Dynamic Language: Python
1/16/2019 1:45 PM Dynamic Language: Python Part of the program executed correctly! There is no compile time! Runtime error! Python is the interpreter language, you do not need to compile your code, and also you have no way to check for syntax errors until you run your python script. Either syntax errors or runtime errors will be throw to standard output through python exception handler by default. Python throws the exception with traceback info indicate which part of your scripts has gone wrong, it looks like this: Traceback (most recent call last): File "except.py", line 9, in main() File "except.py", line 5, in main print l[4] IndexError: list index out of range The traceback indicates that there is an IndexError happening in main function. Object Oriented Software Construction /01/2019 1:45 PM
33
Dynamic Typing: php Type Error: Argument “b” is not a number
1/16/2019 1:45 PM Dynamic Typing: php Type Error: Argument “b” is not a number Type Error: There is no routine “withdra” (spelling error) PHP Notice is a Warning: But now we are producing incorrect results $224 (instead of $223) PHP Fatal Error stops the program from further execution indigo 309 % /xsys/pkg/php/bin/php bank.php PHP Notice: Object of class Account could not be converted to int in /cs/home/jonathan/tools/php/bank.php on line (This is wrong! Account “b” interpreted as withdraw “1”) PHP Fatal error: Call to undefined method Account::withdra() in /cs/home/jonathan/tools/php/bank.php on line 18 Object Oriented Software Construction /01/2019 1:45 PM
34
Casting breaks the type system
What programming languages offer genericity that you know of? Java? C++? Other? C++ has the template: Set < int > s ; Java 5 added genericity What is the effect of genericity on compile time size of the generated code execution time execution space Warning: generics cheap in Eiffel – expensive in C++
35
Non-generic Java Stack
public class Stack { private int count; private int capacity; private int capacityIncrement; private Object[] itemArray; // instead of ARRAY[G] Stack() { //constructor limited to class name count= 0; capacity= 10; capacityIncrement= 5; itemArray= new Object[capacity]; } public boolean empty() { return (count == 0);
36
Java Stack (cont.) public void push(Object x) {
if(count == capacity) { capacity += capacityIncrement; Object[] tempArray= new Object[capacity]; for(int i=0; i < count; i++) tempArray[i]= itemArray[i]; itemArray= tempArray; } itemArray[count++]= x; public Object pop() { if(count == 0) return null; else return itemArray[--count];
37
Java Stack (cont.) public Object peek() { if(count == 0) return null;
else return itemArray[count-1]; } public class Point { public int x; public int y;
38
Java Stack runtime error
class testStack { public static void main(String[] args) { Stack s = new Stack(); Point upperRight = new Point(); upperRight.x= 1280; // breaks information hiding upperRight.y= 1024; // cannot guarantee any contract s.push("red"); s.push("green"); // push some String s.push("blue"); // objects on the stack s.push(upperRight); // push a POINT object on the stack while(!s.empty()) { // cast all items from OBJECT String color = (String) s.pop(); // to STRING in order to print System.out.println(color); }}} // causes a run-time error // ClassCastException: Point at testStack.main(testStack.java:18) // With genericity, it is a compile time error
39
Why Twitter Switched to Scala (2009)
1/16/2019 1:45 PM Why Twitter Switched to Scala (2009) Twitter began its life as a Ruby on Rails application, and still uses Ruby on Rails to deliver most user-facing web pages. In this interview, three developers from Twitter—Steve Jenson, system engineer; Alex Payne, API lead; and Robey Pointer, member of the service team—sit down with Bill Venners to discuss Twitter's real-world use of Scala. Bill Venners: I’m curious, and the Ruby folks will want it spelled out: Can you elaborate on what you felt the Ruby language lacked in the area of reliable, high performance code? Steve Jenson: ... Another thing we really like about Scala is static typing that’s not painful ... Reliable, high performance code Bill Venners: I’m curious, and the Ruby folks will want it spelled out: Can you elaborate on what you felt the Ruby language lacked in the area of reliable, high performance code? Steve Jenson:One of the things that I’ve found throughout my career is the need to have long-lived processes. And Ruby, like many scripting languages, has trouble being an environment for long lived processes. But the JVM is very good at that, because it’s been optimized for that over the last ten years. So Scala provides a basis for writing long-lived servers, and that’s primarily what we use it for at Twitter right now. Another thing we really like about Scala is static typing that’s not painful. Sometimes it would be really nice in Ruby to say things like, here’s an optional type annotation. This is the type we really expect to see here. And we find that really useful in Scala, to be able to specify the type information. Robey Pointer: Also, Ruby doesn’t really have good thread support yet. It’s getting better, but when we were writing these servers, green threads were the only thing available. Green threads don't use the actual operating system’s kernel threads. They sort of emulate threads by periodically stopping what they are doing and checking whether another “thread” wants to run. So Ruby is emulating threads within a single core or a processor. We wanted to run on multi-core servers that don’t have an infinite amount of memory. And if you don’t have good threading support, you really need multiple processes. And because Ruby’s garbage collector is not quite as good as Java’s, each process uses up a lot of memory. We can’t really run very many Ruby daemon processes on a single machine without consuming large amounts of memory. Whereas with running things on the JVM we can run many threads in the same heap, and let that one process take all the machine’s memory for its playground. Alex Payne: I’d definitely want to hammer home what Steve said about typing. As our system has grown, a lot of the logic in our Ruby system sort of replicates a type system, either in our unit tests or as validations on models. I think it may just be a property of large systems in dynamic languages, that eventually you end up rewriting your own type system, and you sort of do it badly. You’re checking for null values all over the place. There’s lots of calls to Ruby’s kind_of? method, which asks, “Is this a kind of User object? Because that’s what we’re expecting. If we don’t get that, this is going to explode.” It is a shame to have to write all that when there is a solution that has existed in the world of programming languages for decades now. Object Oriented Software Construction /01/2019 1:45 PM
40
Why Twitter Switched to Scala (2009)
1/16/2019 1:45 PM Why Twitter Switched to Scala (2009) Alex Payne: I’d definitely want to hammer home what Steve said about typing. As our system has grown, a lot of the logic in our Ruby system sort of replicates a type system, either in our unit tests or as validations on models. I think it may just be a property of large systems in dynamic languages, that eventually you end up rewriting your own type system, and you sort of do it badly. You’re checking for null values all over the place. There’s lots of calls to Ruby’s kind_of? method, which asks, “Is this a kind of User object? Because that’s what we’re expecting. If we don’t get that, this is going to explode.” It is a shame to have to write all that when there is a solution that has existed in the world of programming languages for decades now. Reliable, high performance code Bill Venners: I’m curious, and the Ruby folks will want it spelled out: Can you elaborate on what you felt the Ruby language lacked in the area of reliable, high performance code? Steve Jenson:One of the things that I’ve found throughout my career is the need to have long-lived processes. And Ruby, like many scripting languages, has trouble being an environment for long lived processes. But the JVM is very good at that, because it’s been optimized for that over the last ten years. So Scala provides a basis for writing long-lived servers, and that’s primarily what we use it for at Twitter right now. Another thing we really like about Scala is static typing that’s not painful. Sometimes it would be really nice in Ruby to say things like, here’s an optional type annotation. This is the type we really expect to see here. And we find that really useful in Scala, to be able to specify the type information. Robey Pointer: Also, Ruby doesn’t really have good thread support yet. It’s getting better, but when we were writing these servers, green threads were the only thing available. Green threads don't use the actual operating system’s kernel threads. They sort of emulate threads by periodically stopping what they are doing and checking whether another “thread” wants to run. So Ruby is emulating threads within a single core or a processor. We wanted to run on multi-core servers that don’t have an infinite amount of memory. And if you don’t have good threading support, you really need multiple processes. And because Ruby’s garbage collector is not quite as good as Java’s, each process uses up a lot of memory. We can’t really run very many Ruby daemon processes on a single machine without consuming large amounts of memory. Whereas with running things on the JVM we can run many threads in the same heap, and let that one process take all the machine’s memory for its playground. Object Oriented Software Construction /01/2019 1:45 PM
41
Using Scala/Joda library
1/16/2019 1:45 PM Using Scala/Joda library scala> import org.joda.time._ import org.joda.time._ scala> def time = new DateTime(2010, 5, 7, 0, 0, 0, 0) time: org.joda.time.DateTime scala> time res0: org.joda.time.DateTime = T00:00: :00 scala> def time = new DateTime(2010, 5, 7, 0, 0, 0) time: org.joda.time.DateTime scala> time java.lang.IllegalArgumentException: No instant converter found for type: scala.Tuple6 .... (July 2010) There is this library joda time which I'd always heard nice things about so I set out to use it today. Let me show you something. scala> import org.joda.time._ import org.joda.time._ scala> def time = new DateTime(2010, 5, 7, 0, 0, 0, 0) time: org.joda.time.DateTime scala> time res0: org.joda.time.DateTime = T00:00: :00 scala> def time = new DateTime(2010, 5, 7, 0, 0, 0) time: org.joda.time.DateTime scala> time java.lang.IllegalArgumentException: No instant converter found for type: scala.Tuple6 at org.joda.time.convert.ConverterManager.getInstantConverter(ConverterManager.java:165) at org.joda.time.base.BaseDateTime.<init>(BaseDateTime.java:169) This is a DEBACLE! The joda time constructors include one which takes Object. That means you lose 100% of your type safety unless you luck into a conflict it will notice, because scala thinks "oh, you must have meant to call the Object constructor with a 6-tuple, let me help you." No scala buddy, I didn't mean that. I knew this risk existed but now having experienced it in this way I consider it past indecent. I think we must do something. ==== Oh, wait, I didn't look closely enough at the example. I assume you specified the wrong number of arguments for the DateTime constructor in the second definition of time, so scalac happily tried to find a way to make it the right number of arguments. So when one would expect a compile error due to the wrong number of arguments, one receives runtime error because scalac tuplized your arguments into a single object. Object Oriented Software Construction /01/2019 1:45 PM
42
Genericity + Inheritance: Polymorphic data structures
1/16/2019 1:45 PM 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 fs (RECTANGLE) (SQUARE) (TRIANGLE) (POLYGON) Object Oriented Software Construction /01/2019 1:45 PM
43
Genericity vs. Inheritance
1/16/2019 1:45 PM Genericity vs. Inheritance Abstraction SET_OF_BOOKS Type parameterization Type parameterization LIST_OF_PEOPLE LIST_OF_BOOKS LIST_OF_ JOURNALS LIKED_LIST_OF_BOOKS Specialization Object Oriented Software Construction /01/2019 1:45 PM
44
Inheritance & Contracts
Object Oriented Software Construction /01/2019 1:45 PM
45
Invariant accumulation
1/16/2019 1:45 PM Invariant accumulation Every class inherits all the invariant clauses of its parents. These clauses are conceptually “and”-ed. Object Oriented Software Construction /01/2019 1:45 PM
46
Accumulating invariants
1/16/2019 1:45 PM Accumulating invariants Every routine will fail with an invariant contract violation Object Oriented Software Construction /01/2019 1:45 PM
47
Inheritance and assertions
1/16/2019 1:45 PM Inheritance and assertions What is the relationship between postcondition C in POLYGON and D in RECTANGLE? In the descendant RECTANGLE Require less Ensure more i.e. Why? So that RECTANGLE should not be able to change the meaning of perimeter to area Substitutivity Object Oriented Software Construction /01/2019 1:45 PM
48
1/16/2019 1:45 PM 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 Object Oriented Software Construction /01/2019 1:45 PM
49
Precondition Subcontracting
1/16/2019 1:45 PM Precondition Subcontracting Correct call: if a1. then a1.r (...) else ... end r is C A require a1: A … ensure a1.r (…) B r is require so that if a1. holds then so does a1. Require Less Ensure more Substitutability ensure Object Oriented Software Construction /01/2019 1:45 PM
50
Assertion redeclaration rule
1/16/2019 1:45 PM Assertion redeclaration rule 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: original_precondition or new_pre original_postcondition and new_post Object Oriented Software Construction /01/2019 1:45 PM
51
Why Contracts? Specifications (vs. implementations)
1/16/2019 1:45 PM Why Contracts? Specifications (vs. implementations) Documents the contract between client and supplier contract view (information hiding) Validating the implementation Check that the implementation satisfies the specification Catches many errors Verification via formal methods Defines an exception (contract violation) Subcontracting (ensures substitutivity) Object Oriented Software Construction /01/2019 1:45 PM
52
The meaning of inheritance
1/16/2019 1:45 PM The meaning of inheritance The type perspective: Automatic adaptation of operations to the dynamic form of their targets (extendibility): Representation independence. Factoring out reusable operations: Commonality. The module perspective (reusability): Open-closed modules Modularity The Single Choice Principle Object Oriented Software Construction /01/2019 1:45 PM
53
Hoare specification of code
{P} prog {Q} Execution of the code prog started in a state satisfying P is guaranteed to terminate in a state satisfying Q {a:ARRAY} sort {i:INT | 1ia.count a[i] a[i+1]} Object Oriented Software Construction /01/2019 1:45 PM
54
The dangers of static binding
1/16/2019 1:45 PM The dangers of static binding create a.make (…) For every creation procedure cp: {precp} docp {postcp and INV} For every exported routine r: {INV and prer} dor {INV and postr} The worst possible erroneous run-time situation in object-oriented software development: Producing an object that does not satisfy the invariant of its class. S1 a.f (…) S2 a.g (…) S3 a.f (…) S4 Object Oriented Software Construction /01/2019 1:45 PM
55
The dangers of static binding
1/16/2019 1:45 PM The dangers of static binding {INVA} dorA {INVA} {INVB} dorB {INVB} Consider a call of the form a1.r where a1 is polymorphic rA preserves INVA and rB preserves INVB But rA has no reason to preserves INVB So a1.r (under static binding) executes rA on objects of type B, thus resulting in an inconsistent object (one that does not satisfy INVB) rA A rB++ B Object Oriented Software Construction /01/2019 1:45 PM
56
Using original version of redefined feature
1/16/2019 1:45 PM 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 ... display_border is Object Oriented Software Construction /01/2019 1:45 PM
57
A concrete example w: WINDOW b: BUTTON create b w := b w.display
1/16/2019 1:45 PM A concrete example w: WINDOW b: BUTTON create b w := b w.display display WINDOW display++ BUTTON Static binding would execute {WINDOW}.display on the button rather than {BUTTON}.display Object Oriented Software Construction /01/2019 1:45 PM
58
Use of Precursor Not necessarily the first feature statement.
1/16/2019 1:45 PM 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 my_feature A my_feature++ B Object Oriented Software Construction /01/2019 1:45 PM
59
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. Object Oriented Software Construction /01/2019 1:45 PM
60
Forcing a type: the problem
1/16/2019 1:45 PM 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 If x is declared of type RECTANGLE, [1] will not compile. If x is declared of type FIGURE, [2] will not compile. [1] is invalid because POLYGONS on the stack Object Oriented Software Construction /01/2019 1:45 PM
61
What not to do! if “list.item is of type RECTANGLE” then … elseif
“list.item is of type CIRCLE” 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'? Object Oriented Software Construction /01/2019 1:45 PM
62
Assignment attempt (cont’d)
1/16/2019 1:45 PM 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. Object Oriented Software Construction /01/2019 1:45 PM
63
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 Object Oriented Software Construction /01/2019 1:45 PM
64
Feature Call Rule is Preserved
r ?= list.item if r /= Void then Result := Result.max(r.diagonal) end r.diagonal is guarded statically, by a compiler check that diagonal is a feature of class RECTANGLE dynamically by a guarantee that r /= Void Object Oriented Software Construction /01/2019 1:45 PM
65
Multiple inheritance A class may have two or more parents.
1/16/2019 1:45 PM 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. TEACHER STUDENT TEACHING_ASSISTANT Object Oriented Software Construction /01/2019 1:45 PM
66
The teaching assistant example
1/16/2019 1:45 PM The teaching assistant example This is in fact a case of repeated inheritance: id UNIVERSITY_PERSON ?? ?? TEACHER STUDENT Chapter 15: Page 543. Introduces ambiguities. But “id” is ok sharing TEACHING_ASSISTANT ???? Object Oriented Software Construction /01/2019 1:45 PM
67
Sharing and replication
1/16/2019 1:45 PM Sharing and replication Features such as age and birthday, not renamed along any of the inheritance paths, will be shared. Features such as tax_id, violation_count inherited under different names, will be replicated. address tax_id TAXPAYER age pay_taxes US_ TAXPAYER SWISS_ TAXPAYER address us_address address swiss_address tax_id us_tax_id tax_id swiss_tax_id SWISS_US_ TAXPAYER pay_taxes pay_us_taxes pay_taxes pay_swiss_taxes
68
Common examples of multiple inheritance
1/16/2019 1:45 PM Common examples of multiple inheritance Combining separate abstractions: Restaurant, train car Calculator, watch Plane, asset Object Oriented Software Construction /01/2019 1:45 PM
69
Multiple inheritance: Combining abstractions
1/16/2019 1:45 PM Multiple inheritance: Combining abstractions * * COMPARABLE NUMERIC INTEGER REAL STRING COMPLEX DOUBLE Object Oriented Software Construction /01/2019 1:45 PM
70
Multiple inheritance: Nested windows
1/16/2019 1:45 PM 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 Object Oriented Software Construction /01/2019 1:45 PM
71
Multiple inheritance: Composite figures
1/16/2019 1:45 PM Multiple inheritance: Composite figures Simple figures A composite figure Object Oriented Software Construction /01/2019 1:45 PM
72
Defining the notion of composite figure
1/16/2019 1:45 PM Defining the notion of composite figure * LIST [FIGURE] FIGURE display count hide put rotate remove move … … COMPOSITE_FIGURE Object Oriented Software Construction /01/2019 1:45 PM
73
Defining the notion of composite figure through multiple inheritance
1/16/2019 1:45 PM Defining the notion of composite figure through multiple inheritance * LIST [FIGURE] FIGURE OPEN_ FIGURE CLOSED_ FIGURE perimeter* SEGMENT POLYLINE COMPOSITE_FIGURE perimeter+ perimeter+ POLYGON ELLIPSE … diagonal … perimeter++ TRIANGLE RECTANGLE CIRCLE perimeter++ SQUARE perimeter++ Object Oriented Software Construction /01/2019 1:45 PM
74
A composite figure as a list
1/16/2019 1:45 PM A composite figure as a list item start forth after Object Oriented Software Construction /01/2019 1:45 PM
75
Composite figures class COMPOSITE_FIGURE inherit
1/16/2019 1:45 PM 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 Object Oriented Software Construction /01/2019 1:45 PM
76
1/16/2019 1:45 PM 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. Object Oriented Software Construction /01/2019 1:45 PM
77
Name clashes under multiple inheritance
1/16/2019 1:45 PM Name clashes under multiple inheritance A B foo foo C Object Oriented Software Construction /01/2019 1:45 PM
78
Resolving name clashes
1/16/2019 1:45 PM Resolving name clashes A B foo foo rename foo as fog rename foo as zoo C Object Oriented Software Construction /01/2019 1:45 PM
79
Resolving name clashes (cont’d)
1/16/2019 1:45 PM Resolving name clashes (cont’d) class C inherit A rename foo as fog end B foo as zoo feature ... Object Oriented Software Construction /01/2019 1:45 PM
80
Results of renaming a1: A b1: B c1: C ... c1.fog c1.zoo a1.foo b1.foo
1/16/2019 1:45 PM 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 Object Oriented Software Construction /01/2019 1:45 PM
81
Another application of renaming
1/16/2019 1:45 PM 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 Object Oriented Software Construction /01/2019 1:45 PM
82
The marriage of convenience
1/16/2019 1:45 PM The marriage of convenience class ARRAYED_STACK [G] inherit STACK [G] ARRAY [G] feature ... end class LINKED_STACK [G] LINKED_LIST [G] feature ... end Arrayed stack is a marriage of convenience (OOSC2 page 530) which unites the noble family of STACK with the rich family of ARRAY. Object Oriented Software Construction /01/2019 1:45 PM
83
The need for deferred classes
1/16/2019 1:45 PM 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? Object Oriented Software Construction /01/2019 1:45 PM
84
Deferred classes deferred class FIGURE feature
1/16/2019 1:45 PM 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 ... Object Oriented Software Construction /01/2019 1:45 PM
85
Example hierarchy * FIGURE * * OPEN_ FIGURE CLOSED_ FIGURE SEGMENT
1/16/2019 1:45 PM Example hierarchy extent* display* barycenter* * rotate … FIGURE … * * OPEN_ FIGURE CLOSED_ FIGURE perimeter* perimeter+ perimeter+ SEGMENT POLYLINE POLYGON ELLIPSE diagonal perimeter++ ... ... TRIANGLE RECTANGLE CIRCLE perimeter++ perimeter++ SQUARE Object Oriented Software Construction /01/2019 1:45 PM
86
Deferred classes and features
1/16/2019 1:45 PM 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). Object Oriented Software Construction /01/2019 1:45 PM
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.