Beruflich Dokumente
Kultur Dokumente
Seif Haridi
Peter Van Roy
State (attributes)
procedures (methods)
class ClassVariable
attr
AttrName1
:
AttrNameN
meth Pattern1 Statement end
:
meth PatternN Statement end
end
class $
attr
AttrName1
:
AttrNamen
meth Pattern Statement end
:
meth Pattern Statement end
end
class AccountWithFee
from VerboseAccount
VerboseAccount
attr fee:5
meth transfer(Amount)
...
end AccountWithFee
end
class D
O
a subclass of
an instance
C
of D
meth M
Non-Conservative
Non-Conservative extension inheritance is dangerous
class AccountWithFee because it might change
from VerboseAccount the relationship between
attr fee:5 methods and just
meth transfer(Amount) invariants the programmer
VerboseAccount, transfer(Amount - @fee) depends on
end
end
Account invariant:
getBalance(B1); transfer(S); getBalance(B2) B1+S=B2
No longer satisfied!
Copyright 2002 by S. Haridi and P. Van Roy 39
Inheritance graph
• Classes may inherit from one or several classes appearing after
the keyword from
• A class B is a superclass of a class A if:
– B appears in the from declaration of A, or
– B is a superclass of a class appearing in the from declaration
of A.
• The attributes and methods available in a class C (i.e. visible)
are defined through a precedence relation on the methods that
appear in the class hierarchy, called the overriding relation:
– A method in a class C overrides any method, with the same
label, in any super class of C.
m A (valid hierarchy)
C (invalid hierarchy)
class ListClass
… ListClass
end
class NilClass from ListClass
…
end NilClass ConsClass
class ConsClass from ListClass
…
end Copyright 2002 by S. Haridi and P. Van Roy 52
Constructing a hierarchy
by following the type II
class ListClass
meth append(_ _) raise undefinedMethod end end
end
class NilClass from ListClass declare L1 L2 L3 in
meth init skip end L1={New ConsClass
meth append(T U) U=T end init(1 {New ConsClass
end init(2 {New NilClass init})})}
class ConsClass from ListClass L2={New ConsClass
attr head tail init(3 {New NilClass init})}
meth init(H T) head:=H tail:=T end {L1 append(L2 L3)}
meth append(T U) {L3 display} % Definition not shown
U2 in
{@tail append(T U2)}
U={New ConsClass init(@head U2)}
end
end Copyright 2002 by S. Haridi and P. Van Roy 53
Abstract and concrete classes
ListClass
NilClass ConsClass
Control abstractions
class HO
meth forAll(LO M)
for O in LO do {O M} end
end
...
end
This technique allows messages as parameters