Eif f el: Analysis, Design and Programming Bertrand Meyer (Nadia - - PowerPoint PPT Presentation

eif f el analysis design and programming
SMART_READER_LITE
LIVE PREVIEW

Eif f el: Analysis, Design and Programming Bertrand Meyer (Nadia - - PowerPoint PPT Presentation

Eif f el: Analysis, Design and Programming Bertrand Meyer (Nadia Polikarpova) Chair of Softw are Engineering - 8 - I nherit ance 2 Ove verview rview Basics Redef init ion Polymor phism and dynamic binding I nherit ance


slide-1
SLIDE 1

Eif f el: Analysis, Design and Programming

Bertrand Meyer (Nadia Polikarpova)

Chair of Softw are Engineering

slide-2
SLIDE 2

2

  • 8 -

I nherit ance

slide-3
SLIDE 3

3

Ove verview rview

Basics Redef init ion Polymor phism and dynamic binding I nherit ance and cont ract s Def erred classes Polymorphic cont ainers I nher it ance and genericit y: const rained gener icit y Mult iple inherit ance Non-conf or ming inher it ance Covar iance and anchor ed t ypes

slide-4
SLIDE 4

4

Ext Exten endi ding ng the bas the basic ic noti notion

  • n of class
  • f class

LIST_OF_ CARS BAG_OF_ CARS

LINKED_LIST_ OF_CARS LIST_OF_ CITIES

LIST_OF_ PERSONS

Abst ract ion Specializat ion Type paramet er izat ion Type paramet er izat ion

Genericity I nheritance

slide-5
SLIDE 5

5

Inher nherita itance ba nce basi sics cs

Principle: Describe a new class as ext ension or specializat ion of an exist ing class (or sever al wit h multiple inherit ance) I f B inherit s f rom A : As modules: all t he services of A are available in B (possibly wit h a dif f er ent implement at ion) As t ypes: whenever an inst ance of A is r equired, an inst ance of B will be accept able (“is-a” relat ionship)

slide-6
SLIDE 6

6

Te Termin rminology

  • logy

I f B inherit s f rom A (by list ing A in it s inherit clause): B is an heir of A A is a parent of B For a class A: The descendants of A ar e A it self and (recursively) t he descendant s of A ’s heir s Proper descendants exclude A it self Rever se not ions: Ancestor Proper ancestor Mor e pr ecise not ion of inst ance: Direct instances of A I nstances of A : t he dir ect inst ances

  • f A and it s descendant s

(Ot her t er minology: subclass, superclass, base class)

B A C D E

slide-7
SLIDE 7

7

Wha What t you can you can do to inhe do to inheri rite ted d feat featur ures

Ef f ect (implicit ) Redef ine Undef ine Rename Change expor t st at us Select

slide-8
SLIDE 8

8

Example Example hierarch hierarchy

cent er* per imet er* per imet er +

. . . . . .

* def erred + ef f ect ive ++ redef ined display* r ot at e* move*

* FI GURE * OPEN_FI GURE * CLOSED_FI GURE SEGMENT POLYLI NE + ELLI P SE CI RCLE + POLYGON TRI ANGLE SQUARE RECTANGLE

per imet er + display + r ot at e + move + per imet er ++ side1 side2 diagonal per imet er ++ display + r ot at e + move + per imet er ++ display ++ r ot at e ++ move ++

slide-9
SLIDE 9

9

Re Redefin definition ition

Class may redef ine (“override”) inherit ed f eat ures Redef init ion is explicit I n line wit h Unif or m Access principle, may redef ine inher it ed f unct ion int o at t ribut e Not t he ot her way around!

slide-10
SLIDE 10

10

Re Redefin definition ition 1: 1: pol polygon ygons

class POLYGON inherit CLOSED_FI GURE create make f eature ver t ex : ARRAY [POI NT] vert ex_count : I NTEGER per imet er : REAL is

  • - P

er imet er lengt h do f rom ... until ... loop Result := Result + ver t ex [i ] . dist ance (ver t ex [i + 1]) ... end end invariant vert ex_count > = 3 vert ex_count = ver t ex.count end

ver t ex [i ] ver t ex [i + 1]

slide-11
SLIDE 11

11

Re Redefin definition ition 2: 2: rec rectang tangles les

class RECTANGLE inherit POLYGON redef ine per imet er end create make f eature diagonal, side1, side2 : REAL per imet er : REAL is

  • - P

er imet er lengt h do Result := 2 (side1 + side2) end invariant vert ex_count = 4 end side1 side2 diagonal

slide-12
SLIDE 12

12

Inh Inheritance, t eritance, typ yping a ing and p nd pol

  • lymor

ymorphism phism

(POLYGON) (RECTANGLE)

p r

  • Assume:

p : POLYGON ; r : RECTANGLE ; t : TRI ANGLE x : REAL Permit t ed: x := p.perimet er x := r.perimet er x := r.diagonal p := r NOT permit t ed: x := p.diagonal

  • - Even j ust af t er p := r !

r := p

slide-13
SLIDE 13

13

Dynamic bin Dynamic binding ding

What is t he ef f ect of t he f ollowing (if some_t est is t rue)?

if some_t est then

p := r

else

p := t

end

x := p.perimet er Redef init ion: A class may change an inherit ed f eat ure, as wit h POLYGON redef ining perimet er . Polymorphism: p may have dif f er ent f orms at run-t ime. Dynamic binding: Ef f ect of p.perimet er depends on run- t ime f orm of p.

slide-14
SLIDE 14

14

Wit Witho hout dy t dynam namic bi c bindi nding? g? display (f : FI GURE)

do if “f is a CI RCLE” then

...

elseif “f is a POLYGON” then

...

end end

and similarly f or all ot her rout ines! Tedious; must be changed whenever t here’s a new f igure t ype

slide-15
SLIDE 15

15

With in With inherit heritanc ance an e and associated techniq d associated technique ues

Wit h: I nit ialize: and: Then j ust use: f : FI GURE c : CI RCLE p : POLYGON

create c.make (...) create p.make (...) if ... then

f := c

else

f := p

end

f.move (...) f.rot at e (...) f.display (...)

  • - and so on f or every
  • - operat ion on f !
slide-16
SLIDE 16

16

Binding Binding

Binding is t he process in which A rout ine invocat ion f (a), x.f (a) is connect ed t o code t hat is execut ed Accessing or writ ing t o a variable a a := E is connect ed a memor y locat ion.

slide-17
SLIDE 17

17

Stat Static v c vs. dynam

  • s. dynamic

ic bind bindin ing

I f binding is done at compile t ime, t his is called “St at ic Binding” using “St at ic Linking”. I f binding is done at progr am load t ime, t his is called “St at ic Binding” using “Dynamic Linking”. I f binding is done at runt ime t his is called “Dynamic Binding”.

slide-18
SLIDE 18

18

Stat Static Bind c Bindin ing g in C in C

I n t he .h header f ile:

extern int f oo (ar g c); ext ern f loat my_variable;

I n t he .c f ile:

int f oo (ar g c); f loat my_variable;

slide-19
SLIDE 19

19

Execution n of f a a call l in n C

On t he caller side: Push t he argument s on t he st ack Push t he current PC + 1 on t he st ack (ret urn address) J ump t o t he code t o execut e This is “f illed out ” dur ing linking/ binding Clean t he st ack

slide-20
SLIDE 20

20

Exec Executio ution of a n of a ca call in C ll in C (cont.) (cont.)

On t he callee side: Add some ext r a memory on t he st ack f or t he local var iables I nit ialize t he local variables (if necessary) Execut e t he implement at ion of t he r out ine Read t he r et urn address f rom t he st ack J ump t o t he ret urn address

slide-21
SLIDE 21

21

Dyna Dynamic Bind c Bindin ing g in non-O in non-OO

Dynamic binding is not exclusive f or obj ect -or ient at ion: Lisp (1958) For t h (1970) - a mixt ure called “Threaded Code” C (1970) - Why ?

slide-22
SLIDE 22

22

Dyna Dynamic Bind c Bindin ing g in C in C

# include < st dio.h> void hello () { print f ("Hello\ n"); } void wor ld () { print f ("World\ n"); } int main (int argc, char **argv) { void (*f unc)(void); if (argc > 1) f unc = hello; else f unc = wor ld; f unc (); / * Dynamic Binding */ }

slide-23
SLIDE 23

23

Dyna Dynamic Bind c Bindin ing g and OO and OO

We need dynamic binding in obj ect -orient at ion I dent if iers used in progr am t ext are r elat ive t o t he curr ent

  • bj ect :

At t r ibut es are r elat ive t o Current Rout ines may be redef ined in subclasses

slide-24
SLIDE 24

24

Using c Using cla lass tables ss tables

Class Table Point er I nt eger Field I nt eger Field I nt eger Field Class A Point er t o f eat ure f Point er t o f eat ur e g

  • 1. Read f ir st f ield f r om Current
  • 2. Add second f ield f rom Current
  • 3. St ore result in t hird f ield of Current
  • 4. Go t o t he second ent ry in Current' s

class t able

class A f eature

a,b,c : I NTEGER f is

do

c := a + b g

end

g is ...

end

slide-25
SLIDE 25

25

Wi With inheritanc th inheritance

Class Table Point er I nt eger Field I nt eger Field I nt eger Field Class B Point er t o f eat ure f Point er t o f eat ure g Boolean Field Point er t o f eat ure h A B

class B inherit A redef ine f f eature

d: BOOLEAN f is ... h is ...

end

slide-26
SLIDE 26

26

Contracts and in Contracts and inherita heritance nce

I ssue: what happens, under inherit ance, t o

Class invariant s? Rout ine precondit ions and post condit ions?

slide-27
SLIDE 27

27

Inva nvariants riants

I nvar iant I nherit ance rule:

The invariant of a class aut omat ically includes t he

invariant clauses f r om all it s parent s, “and”-ed. Accumulat ed result visible in f lat and int erf ace f or ms.

slide-28
SLIDE 28

28

Contracts and in Contracts and inherita heritance nce

r require

  • ensure
  • r

require

  • ensure
  • a1: A

a1.r (… ) …

Cor rect call in C:

if a1. t hen

a1.r (...)

  • - Her e a1. holds

end

r ++

C A D B

client of inherit s f rom ++ redef init ion

slide-29
SLIDE 29

29

Assertion redeclar Assertion redeclaratio ation rule n rule

When redeclar ing a r out ine, we may only:

Keep or weaken t he precondit ion Keep or st r engt hen t he post condit ion

slide-30
SLIDE 30

30

A simple language rule does t he t rick! Redef ined ver sion may have not hing (assert ions kept by def ault ), or require else new_pr e ensure then new_post Result ing assert ions are:

  • riginal_precondit ion or new_pr e
  • riginal_post condit ion and new_post

Assertion Assertion redeclarat redeclaration rule in ion rule in Eif Eiffel fel

slide-31
SLIDE 31

31

The ro The role of le of deferred classes deferred classes

Express abst ract concept s independent ly of implement at ion Express common element s of various implement at ions Terminology: Ef f ective = non-def erred (i.e. f ully implement ed)

slide-32
SLIDE 32

32

I n e.g. LI ST: f or t h

def erred end

A A de defe ferred fe rred feature ature

ensure

index = old index + 1

require not af t er

slide-33
SLIDE 33

33

Def er r ed!

I n t he same class search (x : G)

  • - Move t o f ir st posit ion af t er current
  • - where x appears, or af t er if none.

do f rom until af t er or else it em = x loop

f or t h

end end “Programs with holes”

Mixing Mixing deferre deferred and effectiv d and effective featur e features es

Ef f ect ive!

slide-34
SLIDE 34

34

“Do “Don’ n’t call t call us, we’l us, we’ll l call you! call you!”

A powerf ul f orm of reuse:

The reusable element def ines a general scheme Specif ic cases f ill in t he holes in t hat scheme

Combine r euse wit h adapt at ion

slide-35
SLIDE 35

35

Defe Deferr rred clas d classe ses in Eiff s in Eiffel elBa Base se

CONTAI NER

*

BOX

*

COLLECTI ON

*

TRAVERSABLE

*

FI NI TE

*

I NFI NI TE

*

BOUNDED

*

UNBOUNDED

*

COUNTABLE

*

RESI ZABLE

*

BAG

*

SET

*

HI ERARCHI CAL

*

LI NEAR

*

TABLE

*

ACTI VE

*

I NTEGER_ I NTERVAL

*

BI LI NEAR

*

I NDEXABLE

*

CURSOR_ STRUCTURE

*

DI SPENSER

*

SEQUENCE

*

ARRAY STRI NG HASH_TABLE STACK

*

QUEUE

*

… …

* def erred

slide-36
SLIDE 36

36

def erred class VAT inherit TANK f eature in_valve, out _valve: VALVE f ill is

  • - Fill t he vat .

require in_valve.open

  • ut _valve.closed

def erred ensure in_valve.closed

  • ut _valve.closed

is_f ull end empt y, is_f ull, is_empt y, gauge, maximum, ... [Ot her f eat ures] ... invariant is_f ull = (gauge > = 0.97 * maximum) and (gauge < = 1.03 * maximum) end

Defe Deferr rred cla d classes es for an for anal alys ysis is

slide-37
SLIDE 37

37

Polymor Polymorph phic data structures ic data structures

class LI ST [G] f eature ... last : G is ... ext end (x: G) is ... end f l: LI ST [FI GURE] r : RECTANGLE s: SQUARE t : TRI ANGLE p: POLYGON ... f l.ext end (p); f l.ext end (t ); f l.ext end (s); f l.ext end (r ) f rom f l.st ar t until f l.af t er loop f l.it em.display; f l.f ort h end

(SQUARE) (RECTANGLE) (TRI ANGLE) (POLYGON)

f l

slide-38
SLIDE 38

38

Figure hierar Figure hierarchy (remin chy (reminder) der)

cent er* per imet er* per imet er +

. . . . . .

* def erred + ef f ect ive ++ redef ined display* r ot at e* move*

* FI GURE * OPEN_FI GURE * CLOSED_FI GURE SEGMENT POLYLI NE + ELLI P SE CI RCLE + POLYGON TRI ANGLE SQUARE RECTANGLE

per imet er + display + r ot at e + move + per imet er ++ side1 side2 diagonal per imet er ++ display + r ot at e + move + per imet er ++ display ++ r ot at e ++ move ++

slide-39
SLIDE 39

39

Enforcing Enforcing a a type: th type: the pro e problem blem

f l.st or e ("FI LE_NAME") ...

  • - Two year s lat er:

f l := ret rieved ("FI LE_NAME“) x := f l.last

  • - [1]

print (x.diagonal )

  • - [2]

What ’s wr ong wit h t his?

I f x is declared of t ype RECTANGLE, [1] is invalid. I f x is declared of t ype FI GURE, [2] is invalid.

slide-40
SLIDE 40

40

Obj ect -Test Local

Enforcing g a a type: : the e Object t Test

if attached {RECTANGLE } f l.last as r then

print (r.diagonal ) … Do anyt hing else wit h r , guarant eed t o be non-void … and of dynamic t ype (descendant of ) RECTANGLE

else

print ("Too bad.")

end

Expr ession t o be t est ed SCOPE of t he Obj ect -Test Local Opt ional (if omit t ed j ust t est s f or void)

slide-41
SLIDE 41

41

Earlier mechan Earlier mechanism ism: assignmen : assignment attempt t attempt

f : FI GURE r : RECTANGLE ... f l.r et r ieve ("FI LE_NAME") f := f l.last r ?= f

if r / = Void t hen

print (r.diagonal )

else

print ("Too bad.")

end

slide-42
SLIDE 42

42

As Assi signment a gnment att ttempt empt

x ?= y wit h x : A Semant ics:

I f y is at t ached t o an obj ect whose t ype conf or ms t o

A, perf or m normal r ef erence assignment .

Ot herwise, make x void.

slide-43
SLIDE 43

43

What we h What we have seen ave seen

Basics Redef init ion Polymor phism and dynamic binding I nherit ance and cont ract s Def erred classes Polymorphic cont ainers

slide-44
SLIDE 44

44

Top Topic ics for t s for today

  • day

I nher it ance and genericit y: const rained gener icit y Mult iple inherit ance Non-conf or ming inher it ance Covar iance and anchor ed t ypes

slide-45
SLIDE 45

45

Inherit Inheritanc ance + Ge + Generi nericity city

Unconst rained genericit y LI ST [G] e.g. LI ST [I NTEGER], LI ST [PERSON] Const r ained gener icit y HASH_TABLE [G, H > HASHABLE ] VECTOR [G > NUMERI C ]

slide-46
SLIDE 46

46

Constraine Constrained genericity d genericity

class VECTOR [G ] f eature plus alias "+" (ot her : VECTOR [G]): VECTOR [G]

  • - Sum of cur rent vect or and ot her .

require lower = ot her.lower upper = ot her.upper local a, b, c: G do ... See next ... end ... Ot her f eat ur es ... end

slide-47
SLIDE 47

47

Adding two vectors Adding two vectors i a b c = + i a b c = + + = u v w

1 2

slide-48
SLIDE 48

48

Constraine Constrained genericity d genericity

Body of plus alias "+":

create Result.make (lower, upper ) f rom

i := lower

until

i > upper

loop

a := it em (i ) b := ot her.it em (i ) c := a + b

  • - Requires “+” operat ion on G!

Result.put (c, i )

i := i + 1

end

slide-49
SLIDE 49

49

The s The solut

  • lutio

ion

Declare class VECTOR as

class VECTOR [G –> NUMERI C] f eature

... The rest as bef ore ...

end

Class NUMERI C (f rom t he Kernel Library) provides f eat ures plus alias "+", minus alias "-"and so on.

slide-50
SLIDE 50

50

Im Impro proving the solution ving the solution

Make VECTOR it self a descendant of NUMERI C, ef f ect ing t he corr esponding f eat ures:

class VECTOR [G –>

NUMERI C] inherit NUMERI C

f eature

... Rest as bef ore, including inf ix "+"...

end

Then it is possible t o def ine v : VECTOR [I NTEGER ] vv : VECTOR [VECTOR [I NTEGER ]] vvv : VECTOR [VECTOR [VECTOR [I NTEGER]]]

slide-51
SLIDE 51

51

In the end In the end.. ...

Genericit y is always const rained because LI ST [G] is j ust an abbr eviat ion of LI ST [G -> ANY]

slide-52
SLIDE 52

52

Combining abstracti Combining abstractions

  • ns

Given t he classes

TRAI N_CAR, RESTAURANT

how would you implement a DI NER?

slide-53
SLIDE 53

53

Examples of m Examples of multipl ultiple inheritan e inheritance ce

Combining separat e abst ract ions:

Rest aurant , t r ain car Calculat or , wat ch Plane, asset Home, vehicle Tram, bus

slide-54
SLIDE 54

54

Com Composite fig posite figures ures

slide-55
SLIDE 55

55

Multiple in Multiple inherit heritance ance: Co : Compos mposite figures ite figures

A composite figure Simple figures

slide-56
SLIDE 56

56

De Definin fining the n g the notion of

  • tion of co

compos mposite figure ite figure

COMPOSI TE_ FI GURE

cent er display hide r ot at e move … count put r emove …

FI GURE LI ST [FI GURE]

slide-57
SLIDE 57

57

In In the the ove

  • verall structure

rall structure

COMPOSI TE_ FI GURE FI GURE LI ST [FI GURE]

OPEN_ FI GURE CLOSED_ FI GURE SEGMENT POLYLI NE P OLYGON ELLI PSE RECTANGLE SQUARE CI RCLE TRI ANGLE per imet er + per imet er* per imet er ++ diagonal per imet er ++ per imet er ++ per imet er +

slide-58
SLIDE 58

58

A comp A composit ite e figu figure re as a list as a list

Cur sor it em f or t h af t er bef or e

slide-59
SLIDE 59

59

Com Composite fig posite figures ures

class COMPOSI TE_FI GURE inherit

FI GURE LI ST [FI GURE]

f eature

display

  • - Display each const it uent f igure in t urn.

do f rom st ar t until af t er loop

it em.display f or t h

end end

... Similarly f or move, rot at e et c. ...

end

Requir es dynamic binding

slide-60
SLIDE 60

60

Goin Going g one lev

  • ne level

el of abstr

  • f abstrac

acti tion hig n highe her

A simpler f orm of procedures display, move et c. can be

  • bt ained t hr ough t he use of it er at ors

Use agent s f or t hat pur pose

slide-61
SLIDE 61

61

Multipl Multiple inheritance e inheritance: Combining : Combining abstraction abstractions

COMPARABLE NUMERI C STRI NG COMPLEX I NTEGER REAL

< , < =, > , > =, … +, –, , / …

(t ot al or der r elat ion) (commut at ive r ing)

slide-62
SLIDE 62

62

The Jav The Java- a-C# solu # soluti tion

No mult iple inher it ance f or classes “I nt er f aces”: specif icat ion only (but no cont r act s)

Similar t o complet ely def erred classes (wit h no

ef f ect ive f eat ure) A class may inherit f rom:

At most one class Any number of int erf aces

slide-63
SLIDE 63

63

Multipl Multiple inheritance e inheritance: Combining : Combining abstraction abstractions

COMPARABLE NUMERI C STRI NG COMPLEX I NTEGER REAL

< , < =, > , > =, … +, –, , / …

(t ot al or der r elat ion) (commut at ive r ing)

slide-64
SLIDE 64

64

How How do we writ do we write e CO COMPARABLE MPARABLE?

def erred class COMPARABLE [G] f eature end

less alias "< " (x : COMPARABLE [G]): BOOLEAN

def erred end

less_equal alias "< =" (x : COMPARABLE [G]): BOOLEAN

do Result := Current <

x or Current ~ x

end

great er alias "> " (x : COMPARABLE [G]): BOOLEAN

do Result := x <

Current end

great er _equal alias "> =" (x : COMPARABLE [G ]): BOOLEAN

do Result := x <

= Current end

slide-65
SLIDE 65

65

Less Lesson

  • ns fr

s from t

  • m this exa

his exampl ple

Typical example of progr am wit h holes We need t he f ull spect rum f r om f ully abst r act (f ully def err ed) t o f ully implement ed classes Mult iple inher it ance is t here t o help us combine abst r act ions

slide-66
SLIDE 66

66

Mu Multip ltiple i le inheri heritance: N tance: Name c me clashes shes f C f

A B

?

slide-67
SLIDE 67

67

Re Resolving nam solving name cl e clashes ashes f

rename f as A_f

C f

A B

A_f , f

slide-68
SLIDE 68

68

Conseque Consequences nces of

  • f renaming

renaming a1: A b1: B c1: C ... c1.f c1.A_f a1.f b1.f

rename f as A_f C f A B A_f , f f

I nvalid:

a1.A_f b1.A_f

slide-69
SLIDE 69

69

Are Are all name all name clas clashe hes bad s bad?

A name clash must be r emoved unless it is:

Under repeat ed inherit ance (i.e. not a real clash) Bet ween f eat ures of which at most one is ef f ect ive

(i.e. ot hers are def er red)

slide-70
SLIDE 70

70

Featur Feature me e mergin rging A B C D f +

f * f * Def erred + Ef f ect ive

slide-71
SLIDE 71

71

Featur Feature me e mergin rging: with dif g: with differe ferent names nt names A B C D h +

g * f * Def erred + Ef f ect ive Renaming g f h f

class D inherit A rename g as f end B C rename h as f end f eature ... end

slide-72
SLIDE 72

72

Featur Feature merging: e merging: effective feature effective features A B C D f + f + f +

Def erred + Ef f ect ive

  • - Undef ine

f -- f --

slide-73
SLIDE 73

73

Un Undefin definition ition

def erred class

T

inherit

S

undef ine v end f eature

...

end

slide-74
SLIDE 74

74

Mer Merging ging thro through ugh un undefinit definition ion

class D inherit A undef ine f end B C undef ine f end f eature ... end

A B C D f + f + f + f -- f --

Def erred + Ef f ect ive

  • - Undef ine
slide-75
SLIDE 75

75

Merging effective feature Merging effective features with di s with different fferent na names mes A B C D h + f + g + f -- f --

class D inherit A undef ine f end B rename g as f undef ine f end C rename h as f end f eature ... end

h f g f

slide-76
SLIDE 76

76

Accepta Acceptable ble na name clashes me clashes

I f inherit ed f eat ures have all t he same names, t here is no harmf ul name clash if : They all have compat ible signat ur es At most one of t hem is ef f ect ive Semant ics of such a case: Merge all f eat ures int o one I f t here is an ef f ect ive f eat ure, it imposes it s implement at ion

slide-77
SLIDE 77

77

Featur Feature merging: e merging: effective feature effective features

a1: A b1: B c1: C d1: D a1.g b1.f c1.h d1.f

A B C D g+ f + h+ g f h f f - f -

slide-78
SLIDE 78

78

A A spe special case of cial case of mu multiple ltiple in inherita heritance nce

TEACHER STUDENT ASSI STANT UNI VERSI TY _MEMBER

id This is a case of repeat ed inher it ance

?? ?? ????

slide-79
SLIDE 79

79

Indirec Indirect and di t and direct repeat rect repeated inherit ed inheritanc ance

A D B C A D

slide-80
SLIDE 80

80

Multiple is Multiple is al also rep so repeate eated inheritanc d inheritance

A t ypical case: copy ++ is_equal ++

copy is_equal

?? copy C_copy is_equal C_is_equal C LI ST D ANY

slide-81
SLIDE 81

81

Sha Sharing ring an and re d replicatio plication

Feat ures such as f , not renamed along any of t he inherit ance pat hs, will be shared. Feat ures such as g, inher it ed under dif f erent names, will be replicat ed.

A B C D f g g g_b g g_c

slide-82
SLIDE 82

82

The nee The need d for s for selec elect

A pot ent ial ambiguit y ar ises because of polymor phism and dynamic binding: a1: ANY d1: D … a1 := d1 a.copy (… )

copy ++ is_equal ++ copy C_copy is_equal C_is_equal

C LI ST D

copy is_equal

ANY

slide-83
SLIDE 83

83

Removing th Removing the a e ambiguity mbiguity

class

D

inherit

LI ST [T ]

select

copy, is_equal

end

C

rename

copy as C_copy, is_equal as C_is_equal, ...

end

slide-84
SLIDE 84

84

Whe When n is a name is a name clas clash h acce accept ptabl ble?

(Bet ween n f eat ures of a class, all wit h t he same name, immediat e or inherit ed.)

They must all have compat ible signat ures. I f more t han one is ef f ect ive, t hey must all come

f rom a common ancest or f eat ure under repeat ed inher it ance.

slide-85
SLIDE 85

85

Another Another app applicatio lication of r n of renaming enaming

Provide locally bet t er adapt ed t erminology. Example: child (TREE ); subwindow (WI NDOW)

slide-86
SLIDE 86

86

Multiple In Multiple Inherit heritan ance and C ce and Class T lass Tables ables

Why does t his not work wit h mult iple subt yping ? Can we st ill do O(1) lookup ?

slide-87
SLIDE 87

87

The dy The dynam namic ic bind bindin ing fun g funct ctio ion

Name × St at icType × DynamicType Code

slide-88
SLIDE 88

88

The dy The dynam namic ic bind bindin ing fun g funct ctio ion

(Name × St at icType) DynamicType Code

slide-89
SLIDE 89

89

The dy The dynam namic ic bind bindin ing fun g funct ctio ion

St at ic Dynamic (Name × St at icType) DynamicType Code

slide-90
SLIDE 90

90

Featu Feature Tables re Tables

f of A g of A h of B g of C A B C Dynamic Type St at ic Type Code Point er Code Point er Code Point er Code Point er Code Point er Code Point er Code Point er Code Point er

slide-91
SLIDE 91

91

Non-confor Non-conformi ming inheritanc ng inheritance

class ARRAY [G] f eature ... lower , upper : I NTEGER r esize (l, u: I NTEGER) ensure lower = l; upper = u end class ARRAYED_LI ST [G] inherit LI ST [G] ARRAY [G] ... invariant st ar t s_f r om_1: lower = 1 end a: ARRAY [I NTEGER]; l: ARRAYED_LI ST [I NTEGER] ... a := l a.r esize (-10, 10)

ARRAYED_LI ST LI ST ARRAY

Class invar iant violat ion

slide-92
SLIDE 92

92

Inher nherita itance ba nce basi sics: e cs: exte xtended nded

I f B inherit s f rom A : As modules: all t he services of A are available in B (possibly wit h a dif f er ent implement at ion) As t ypes: whenever an inst ance of A is r equired, an inst ance of B will be accept able (“is-a” relat ionship) I f B inherit s f rom A in a non-conf orming way: As modules: all t he services of A are available in B (possibly wit h a dif f er ent implement at ion) No relat ionship bet ween t ypes!

slide-93
SLIDE 93

93

Non-confor Non-conformi ming inheritanc ng inheritance

class ARRAYED_LI ST [G] inherit LI ST [G] inherit {NONE} ARRAY [G] ... invariant st ar t s_f r om_1: lower = 1 end a: ARRAY [I NTEGER]; l: ARRAYED_LI ST [I NTEGER] ... a := l a.r esize (-10, 10)

ARRAYED_LI ST LI ST ARRAY

Non-conf or ming inher it ance Not allowed

slide-94
SLIDE 94

94

No n No need for eed for select select

count count capacit y

ARRAY LI ST ARRAYED_LI ST FI NI TE Pot ent ial ambiguit y is r esolved is f avor of conf orming parent : f : FI NI TE [...] al: ARRAYED_LI ST [...] … f := al print (f .count )

Ver sion f r om LI ST

slide-95
SLIDE 95

95

Covarian Covariance ce

class LI ST [G] f eature cur sor : CURSOR go_t o (c: CURSOR) is do …end … end class LI NKED_LI ST [G] inherit LI ST [G] redef ine cursor , go_t o, ... end f eature cur sor : LI NKED_CURSOR go_t o (c: LI NKED_CURSOR) is do …end … end

LI NKED_LI ST LI ST LI NKED_CURSOR CURSOR

slide-96
SLIDE 96

96

Ancho Anchore red types d types

class LI ST [G] f eature cur sor : CURSOR go_t o (c: like cur sor ) is do …end … end class LI NKED_LI ST [G] inherit LI ST [G] redef ine cur sor , ... end f eature cur sor : LI NKED_CURSOR

  • - No need t o redef ine ` go_t o’

… end

slide-97
SLIDE 97

97

Sema Semantic ics of an s of anch chore red d ty types pes

I n class C : x: SOME_TYPE y: like x I n class C, y is t reat ed exact ly as wit h y: SOME_TYPE I n a descendant D of C, if x has been redeclared t o some

  • t her t ype, y will be t r eat ed as it if also had t hat t ype.
slide-98
SLIDE 98

98

Type re Type redefin definitio ition rule n rule

Eif f el: covar iant redef init ion of result (may change t ype t o a descendant of t he or iginal t ype) covar iant redef init ion of ar gument s Tradit ional not ion of subt yping : covar iant redef init ion of result cont r avar iant redef init ion of argument s (may change t ype t o an ancest or of t he or iginal t ype) Cont ravariant redef init ion: saf e but useless

slide-99
SLIDE 99

99

Th The p e pro roblem w blem with th cova variance riance

list : LI ST [...] linked_list : LI NKED_LI ST [...] c: CURSOR … list := linked_list list .go_t o (c)

class LI ST f eature cursor: CURSOR go_t o (c: like cursor ) is do … end … end class LI NKED_LI ST inherit LI ST redef ine cursor, ... end f eature cursor: LI NKED_CURSOR

  • - No need t o redef ine ` go_t o’

… end

Cat call!

slide-100
SLIDE 100

100

CAT CAT call calls

CAT st ands f or Changing Availabilit y or Type A rout ine is a CAT if some redef init ion changes it s expor t st at us or t he t ype of any of it s ar gument s A call is a cat call if some redef init ion of t he rout ine would make it invalid because of a change of export st at us

  • r ar gument t ype
slide-101
SLIDE 101

101

Cat Catcall ll cas cases es

Covar iant redef init ion of argument s

  • Non-gener ic case
  • Gener ic case

Descendant hiding (in earlier versions of Eif f el)

slide-102
SLIDE 102

102

Covarian Covariant redefinit t redefinition ion: non-gen : non-generi eric ca c case se

class ANI MAL f eature

eat (a_f ood: FOOD)

def erred end end class WOLF inherit ANI MAL redef ine eat end f eature

eat (a_meat : MEAT)

do … end end

WOLF ANI MAL FOOD MEAT GRASS

slide-103
SLIDE 103

103

animal: ANI MAL wolf : WOLF f ood: FOOD grass: GRASS

create wolf create grass

animal := wolf f ood := grass animal.eat (grass)

Covarian Covariant redefinit t redefinition ion: non-gen : non-generi eric ca c case se

WOLF ANI MAL FOOD MEAT GRASS

slide-104
SLIDE 104

104

animal_list : LI NKED_LI ST [ANI MAL] sheep_list : LI NKED_LI ST [SHEEP] sheep: SHEEP wolf : WOLF sheep_list .ext end (sheep) animal_list := sheep_list animal_list .ext end (wolf )

Cov Covar arian ant t rede redefi finit itio ion: gen : gener eric cas c case

WOLF ANI MAL SHEEP

slide-105
SLIDE 105

105

class LI NKED_LI ST [ANY] f eature ext end (v: ANY) do …end end class LI NKED_LI ST [SHEEP] f eature ext end (v: SHEEP) do …end end class LI NKED_LI ST [WOLF] f eature ext end (v: WOLF) do …end end

Cov Covar arian ant t rede redefi finit itio ion: gen : gener eric cas c case

slide-106
SLIDE 106

106

class RECTANGLE inherit POLYGON export {NONE}

add_vert ex

end

invariant

ver t ex_count = 4

end

r : RECTANGLE; p: POLYGON ... p := r p.add_ver t ex (...)

Descend scendant h ant hidi ding ng

RECTANGLE POLYGON

Ear lier : cat call! Now: not allowed

slide-107
SLIDE 107

107

class RECTANGLE inherit {NONE} POLYGON export {NONE}

add_vert ex

end

invariant

ver t ex_count = 4

end

r : RECTANGLE; p: POLYGON ... p := r p.add_ver t ex (...)

Descend scendant h ant hidi ding: s ng: solutio ution 1 n 1

RECTANGLE POLYGON

Not allowed Nonconf or ming inher it ance

slide-108
SLIDE 108

108

class POLYGON f eature ... var iable_ver t ex_count : BOOLEAN do Result := True end add_ver t ex (...) require var iable_ver t ex_count do ... end end class RECTANGLE inherit POLYGON redef ine var iable_ver t ex_count end f eature ... var iable_ver t ex_count : BOOLEAN = False end p: POLYGON ... if p.var iable_ver t ex_count then p.add_ver t ex (...) end

Descend scendant h ant hidi ding: s ng: solutio ution 2 n 2

RECTANGLE POLYGON

slide-109
SLIDE 109

109

Inher nherita itance: s nce: summ mmary ( ary (1)

Type mechanism: let s you or ganize our dat a abst r act ions

int o t axonomies

Module mechanism: let s you build new classes as

ext ensions of exist ing ones

Polymorphism: f lexibilit y wit h t ype saf et y Dynamic binding: aut omat ic adapt at ion of oper at ion t o

t arget , f or mor e modular sof t ware archit ect ures

Cont r act s inherit ance: ensures proper t ies t o client s in

presence of polymorphism

Def erred classes: a mechanism t o express propert ies of

abst r act concept s

slide-110
SLIDE 110

110

Inher nherita itance: s nce: summ mmary ( ary (2)

Polymorphic cont ainer s + obj ect t est : f lexible and t ype-

saf e

Const r ained gener icit y: allows calling specif ic f eat ur es

  • n expression of paramet er t ypes

Mult iple inherit ance: power f ul way of combining

abst r act ions

Non-conf or ming inherit ance: a way t o express code

reuse wit hout subt yping

Cat calls: result f rom covariant r edef init ion of argument

t ypes (even mor e t ricky wit h genericit y!)