copyright s. haridi & p. van roy1 object-oriented programming seif haridi peter van roy
TRANSCRIPT
Copyright S. Haridi & P. Van Roy 1
Object-Oriented Programming
Seif Haridi
Peter Van Roy
Copyright S. Haridi & P. Van Roy 2
Object-oriented programming
• We present a rich style in program structure based on a collection of stateful entities (abstract data types)
• Most popular current representatives are C++, and Java
• Most popular design model is UML, an object-oriented design model
• Principle programming techniques
• Relation to other models (higher-order programming, component based programming, functional)
• Case-study in object-oriented language (based on Mozart/Oz)
Copyright S. Haridi & P. Van Roy 3
Component based programming
• Supports
– Encapsulation
– Compositionality
– Instantiation
Copyright S. Haridi & P. Van Roy 4
Object-oriented programming
• Supports
– Encapsulation
– Compositionality
– Instantiation
• Plus
– Inheritance
Copyright S. Haridi & P. Van Roy 5
Inheritance
• Programs can be built in hierarchical structure from data abstractions that depend on other data abstractions (Components)
• Object-oriented programming (inheritance) is based on the idea that data abstractions have much in common
• Example, sequences (stacks, lists, queues)
• Object oriented programming builds data abstractions incrementally, this is done by inheritance
• A data abstraction can be defined to ”inherit” from another abstract datatype, have substantially the same functionality of the other abstract datatype
• Only the difference between a data abstraction and its ancestor has to be specified
Copyright S. Haridi & P. Van Roy 6
What is object-oriented programming?
• OOP (Object-oriented programming) = encapsulated state + inheritance
• Object– An entity with unique identity that encapsulates state– State can be accessed in a controlled way from outside– The access is provided by means of methods
(procedures that can directly access the internal state)• Class
– A specification of objects in an incremental way– Incrementality is achieved inheriting from other classes – and by specifying how its objects (instances) differ
from the objects of the inherited classes
Copyright S. Haridi & P. Van Roy 7
Instances (objects)
Interface (what methods are available)
State (attributes)
procedures (methods)
Copyright S. Haridi & P. Van Roy 8
Classes as complete specof a data abstraction
• We start our case study
• elements of a class (members)
– attributes (mutable instance variables)
– features (stateless info about objects)
– methods
Copyright S. Haridi & P. Van Roy 9
Classes (syntax simple)
A class is a statement
class ClassVariableattr AttrName1
: AttrNameNmeth Pattern1 Statement end
:meth PatternN Statement end
end
Copyright S. Haridi & P. Van Roy 10
Classes (syntax simplified)
A class is also a value that can be in an expression position
class $attr AttrName1
: AttrNamenmeth Pattern Statement end
:meth Pattern Statement end
end
Copyright S. Haridi & P. Van Roy 11
Classes in Oz
The class Counter has the syntactic form
class Counter attr val meth browse {Browse @val} end meth inc(Value) val := @val + Value end meth init(Value) val := Value endend
Copyright S. Haridi & P. Van Roy 12
Attributes of Classes
The class Counter has the syntactic form
class Counter attr val meth browse {Browse @val} end meth inc(Value) val := @val + Value end meth init(Value) val := Value endend
val is an attributea modifiable cellthat is access by theatom val
Copyright S. Haridi & P. Van Roy 13
Attributes of classesThe class Counter has the syntactic form
class Counter attr val meth browse {Browse @val} end meth inc(Value) val := @val + Value end meth init(Value) val := Value endend
the attribute val is accessed by theoperator @val
Copyright S. Haridi & P. Van Roy 14
Attributes of classesThe class Counter has the syntactic form
class Counter attr val meth browse {Browse @val} end meth inc(Value) val := @val + Value end meth init(Value) val := Value endend
the attribute val is assigned by theoperator :=as val := ...
Copyright S. Haridi & P. Van Roy 15
Methods of classes
The class Counter has the syntactic form
class Counter attr val meth browse {Browse @val} end meth inc(Value) val := @val + Value end meth init(Value) val := Value endend
methodsare statementsmethod head is arecord (tuple) pattern
Copyright S. Haridi & P. Van Roy 16
Classes in OzThe class Counter has the syntactic form
class Counter attr val meth browse {Browse @val} end meth inc(Value) val := @val + Value end meth init(Value) val := Value endend
Copyright S. Haridi & P. Van Roy 17
Example
• The following shows how an object is created from a class using the procedure New/3, whose first argument is the class, the second is the initial method, and the result is the object.
• New/3 is a generic procedure for creating objects from classes.
declare C = {New Counter init(0)}{C browse}{C inc(1)}{C browse}
Copyright S. Haridi & P. Van Roy 18
The procedure-based approach
fun {Counter}
X
SS = {Record.toDictionary state(val:X)} % new variable X
proc {Inc inc(Value)} S.val := S.val + Value end
proc {Display browse} {Browse S.val} end
proc {Init init(Value)} SS.val := Value end
D = o(inc:Inc browse:Display init:Init)
in proc{$ M} {D.{Label M} M} end
end
Copyright S. Haridi & P. Van Roy 19
The procedure-based approach
fun {Counter}
X
SS = {Record.toDictionary state(val:X)} % new variable X
...
D = o(inc:Inc browse:Display init:Init)
in proc{$ M} {D.{Label M} M} end
end
fun {New Class InitialMethod}
O = {Class}
in {O InitialMethod} O end
Copyright S. Haridi & P. Van Roy 20
Example
• The following shows how an object is created from a class using the procedure New/3, whose first argument is the class, the second is the initial method, and the result is the object.
• New/3 is a generic procedure for creating objects from classes.
declare C = {New Counter init(0)}{C browse}{C inc(1)}{C browse}
Object interface is as a procedurewith one argument (see proceduredispatch method Chapter 8)
Copyright S. Haridi & P. Van Roy 21
• A class X is defined by:
– class X ... end• Attributes are defined using the attribute-declaration
part before the method-declaration part:
– attr A1 ... AN
• Then follows the method declarations, each has the form:
– meth E S end• The expression E evaluates to a method head, which is
a record whose label is the method name.
Summary
Copyright S. Haridi & P. Van Roy 22
• An attribute A is accessed using @A.
• An attribute is assigned a value using A := E
• A class can be defined as a value:• X = class $ ... end
Summary
Copyright S. Haridi & P. Van Roy 23
Attribute Initialization
• Stateful (may be updated by :=)
• Initialized at object creation time, all instanceshave the initial balance = 0
• class Account
attr balance:0
meth … end
…
end
In general the initial valueof an attribute could be anylegal value (including classes and objects)
Copyright S. Haridi & P. Van Roy 24
Attribute Initialization
• Initialization by instanceclass Account attr balance meth init(X) balance := X end
…
end• C1 = {New Account init(100)}
• C1 = {New Account init(50)}
Copyright S. Haridi & P. Van Roy 25
Attribute Initialization
• Initialization by branddeclare L=linuxclass RedHat attr ostype:L meth get(X) X = @ostype endend class SuSE attr ostype:L meth get(X) X = @ostype endend class Debian attr ostype:L meth get(X) X = @ostype endend
Copyright S. Haridi & P. Van Roy 26
Exampleclass Queue attr front back count meth init Q in front := Q back := Q count := 0 end meth put(X) Q in @back = X|Q back := Q count := @count + 1 end
... end
Copyright S. Haridi & P. Van Roy 27
Exampleclass Queue attr front back count meth init Q in front := Q back := Q count := 0 end meth put(X) Q in @back = X|Q back := Q count := @count + 1 end
... end
front
back
Q0
front
back
a | Q1
put(a)
Copyright S. Haridi & P. Van Roy 28
Example
class Queue
attr front back count
...
meth get(?X)
Q in
X|Q = @front
front := Q count := @count - 1
end
meth count(X) X = @count end
...
end
front
back
a | Q1
X
front
back
a | Q1
X
Copyright S. Haridi & P. Van Roy 29
Classes as incremental specsof data abstractions
• Object-oriented programming allows allows us to define a class by extending existing classes
• Three things have to be introduced
– How to express inheritance, and what does it mean?
– How to access particular methods in the new class and in preexisting classes
– Visibility – what part of the program can see the attributes and methods of a class
• The notion of delegation as a substitute for inheritance
Copyright S. Haridi & P. Van Roy 30
Inheritance• Inheritance should be used as a
way to specialize a class while retaining the relationship between methods
• In this way it is a just an extension of a data abstraction
• The other view is inheritance is just a (lazy) way to construct new abstract data types !
• No relationships are preserved
generalclass
specializedclass
Copyright S. Haridi & P. Van Roy 31
Inheritanceclass Account attr balance:0 meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance endend
A={New Account transfer(100)}
Copyright S. Haridi & P. Van Roy 32
Inheritance II
Conservative extensionclass VerboseAccount from Account meth verboseTransfer(Amount)
... endend
The class VerboseAccount has the methods: transfer, getBal, and verboseTransfer
Copyright S. Haridi & P. Van Roy 33
Inheritance II
Non-Conservative extension
class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) ... endend
The class AccountWithFee has the mothods: transfer, getBal, and verboseTransferThe method transfer has been redefined (overridden) with another definition
Copyright S. Haridi & P. Van Roy 34
Inheritance II
Non-Conservative extension
class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) ... endend
Account
VerboseAccount
AccountWithFee
Copyright S. Haridi & P. Van Roy 35
Static and dynamic binding
Dynamic binding
• Inside an object O we want to invoke a method M
• This is written as {self M}, and chooses the method visible in the current object (M of D)
class Cmeth M
class Da subclass of
Cmeth M
Oan instance
of D
Copyright S. Haridi & P. Van Roy 36
Static and dynamic binding
Static binding
• Inside an object O we want to invoke a method M in a specific (super) class
• This is written as C, M and chooses the method visible in the super class C (M of C)
class Cmeth M
class Da subclass of
Cmeth M
Oan instance
of D
Copyright S. Haridi & P. Van Roy 37
Static method calls• Given a class and a method head m(…), a static method-call
has the following form:C, m(…)
• Invokes the method defined in the class argument.
• A static method call can only be used inside class definitions.
• The method call takes the current object denoted by self as implicit argument.
• The method m could be defined in the class C, or inherited from a super class.
Copyright S. Haridi & P. Van Roy 38
Inheritanceclass Account attr balance:0 meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance endend
A={New Account transfer(100)}
Copyright S. Haridi & P. Van Roy 39
Inheritance II
Conservative extensionclass VerboseAccount from Account meth verboseTransfer(Amount)
{self transfer(Amount)} {Show @balance} endend
The class VerboseAccount has the methods: transfer, getBal, and verboseTransfer
Copyright S. Haridi & P. Van Roy 40
Inheritance II
Non-Conservative extensionclass AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount, transfer(Amount - @fee) endend
The class AccountWithFee has the mothods: transfer, getBal, and verboseTransferThe method transfer has been redefined (overridden) with another definition
Copyright S. Haridi & P. Van Roy 41
Inheritance II
Non-Conservative extensionclass AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount, transfer(Amount - @fee) endend
Non-Conservative inheritance is dangerousbecause it might change the relationship between methods and the invariants the programmer depends on
AccountgetBalance(B); transfer(S); getBalance(B1) => B1 = B-S
Copyright S. Haridi & P. Van Roy 42
Inheritance II
Non-Conservative extensionclass AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount, transfer(Amount - @fee) endend
Non-Conservative inheritance is dangerousbecause it might change the relationship between methods and the invariants the programmer depends on
AccountWithFreegetBalance(B); transfer(S) iff getBalance(B-S-@fee)
Copyright S. Haridi & P. Van Roy 43
Inheritance III
• 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 methods (attributes and features) available in a class C (i.e. visible) are defined through a precedence relation on the methods that appear in the class hierarchy based on the overriding relation:
– A method in a class C overrides any method, with the same label, in any super class of C.
Copyright S. Haridi & P. Van Roy 44
SuperClass relation
C
• SuperClass relation is directed and acyclic.
Copyright S. Haridi & P. Van Roy 45
SuperClass relation
C
• SuperClass relation is directed and acyclic.
• After striking out all overridden methods each remaining method should have a unique label and is defined only in one class in the
hierarchy.
Copyright S. Haridi & P. Van Roy 46
Inheritance relation
C
m
m
m
A (valid hierarchy)
(invalid hierarchy)
Copyright S. Haridi & P. Van Roy 47
Multiple Inheritance Exampleclass Account attr balance:0 meth transfer(Amount) balance := @balance+Amount end meth getBal(?B) B = @balance endendclass Customer attr name meth init(N) name := N endendclass CustomerAccount from Customer Account end
A={New CustomerAccount init}
Copyright S. Haridi & P. Van Roy 48
Illegal inheritanceclass Account attr balance meth init(Amount) balance := Amount end meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance endendclass Customer attr name meth init(N) name := N endendclass CustomerAccount from Customer Account end
There are two init methodsvisible for CustomerAccountThis is illegal
Copyright S. Haridi & P. Van Roy 49
Legal inheritanceclass Account attr balance meth init(Amount) balance := Amount end meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance endendclass Customer attr name meth init(N) name := N endendclass CustomerAccount from Customer Account meth init(N A) Customer, init(N) Account, init(A) endend
CustomerAccount hasattributes balance and namemethods init, transfer and getBalance
This overriding is notharmful it does notchange relationshipsin super classes
Copyright S. Haridi & P. Van Roy 50
Controlling visibility
• Visibility is the control given to the user to limit access to members of a class (attributes, methods and features)
• Each member is defined with a scope (part of program text that the member can be accessed by name)
• Programming languages uses words like public, private and protected to define visibility
• Unfortunately different languages use these keywords to define different scopes
Copyright S. Haridi & P. Van Roy 51
Public and private scopes in objects
• A private member is one which is only visible in the object instance (it is used for implementing the object)
• The object instance can see all the private members in its class and its super classes
• A public member is visible anywhere in the program
• It is part of the interface of the object
• In Oz (and Smalltalk) attributes are private and methods are public (the default rule)
• In Java and C++ private has another meaning
Copyright S. Haridi & P. Van Roy 52
The meaning of Private
C
SubC
SubSubC
I1 I4I2 I3Instances
Class Hierarchy
Copyright S. Haridi & P. Van Roy 53
The meaning of Private
C
SubC
SubSubC
I1 I4I2 I3Instances
Class Hierarchy According toSmalltalk and Oz
All private memebersin this region are visibleto I3
Copyright S. Haridi & P. Van Roy 54
The meaning of Private
C
SubC
SubSubC
I1 I4I2 I3Instances
Class Hierarchy According toC++ and Java
All private memebersin this region are visibleto I3
Copyright S. Haridi & P. Van Roy 55
Public and private scopes in objects
• In Oz (and Smalltalk) attributes are private and methods are public
• It is possible in Oz to make a method private within a class
• Using a variable identifier as a method head will make the method local to the class
• The variable is automatically bound to a unique name
class C meth A(...) ... end....end
Copyright S. Haridi & P. Van Roy 56
Public and private scopes in objects
• In Oz (and Smalltalk) attributes are private and methods are public
• It is possible in Oz to make a method private within a class
• Using a variable identifier as a method head will make the method local to the class
• The variable is automatically bound to a unique name
• ! is an escape character, !A means escape the class scope
class C meth A(...) ... end....end
local AA = {NewName} in class C meth !A(...)!A(...) ... end .... endend
Copyright S. Haridi & P. Van Roy 57
Programming techniques
• First class messages (higher order programming)
• Parameterized classes
• Use of multiple inheritance
Copyright S. Haridi & P. Van Roy 58
Techniques of higher order programming
Control abstractions
class HigherOrderControl
meth forAll(ListObjects M)
for O in ListObjects do {O M} end
end
...
end
This technique allows messages as parameters
Copyright S. Haridi & P. Van Roy 59
Techniques of higher order programming
Control abstractions
class HigherOrderControl
...
meth nil skip end
meth ’|’(M Ms)
{self M} {self Ms}
end
end
C = {New class $ from HigherOrderControl Counter end init(0)}
{C [inc(2) browse inc(3) browse]}
Copyright S. Haridi & P. Van Roy 60
Patemeterized classes
• Classes are values like any other value
• Therefore is it possible to define functions that return new classes as output
fun {MakeClassAcountWithFee Fee} class $ %% Fee is in context environment from Account
meth init(Amount) Account, init(Amount-Fee) end
endendAccount={MakeClassAccountWithFee 100}{New Account init(1000)}
Copyright S. Haridi & P. Van Roy 61
Classes as first-class values
fun {MakeClassAcountWithFee Fee} class $ %% Fee is in closure from Account
meth init(Amount) Account,init(Amount-Fee)end
endendAccount={MakeClassAccountWithFee 100}{New Account init(1000)}
Copyright S. Haridi & P. Van Roy 62
Delegation
Some object systems do not use inheritance (SELF)They use a notion known as delegation
Every class is an objectInheritance is implemented by forwarding messages the object cannot handle to a ”delegate”which behaves as a super-class
More dynamic, inheritance can be dynamic
Copyright S. Haridi & P. Van Roy 63
DelegationAccount = {New
class $ attr balance
meth init balance := 0 end
meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance end
end init}
Copyright S. Haridi & P. Van Roy 64
Programming techniqueswith multiple inheritance
Copyright S. Haridi & P. Van Roy 65
DelegationVerboseAccount = {New class $ from BaseObject attr delegate:Account meth verboseTransfer(Amount)
B in {self transfer(Amount)} {self getBalance(B)}
{Show B} end meth otherwise(M) {@delegate M} end end init}
Copyright S. Haridi & P. Van Roy 66
Multiple inheritance
• Multiple Inheritance is useful when an object has to be two different things in the same program (mixin inheritance)
• Example, we have graphical objects
– Line, circle, etc
– Composite graphical objects (groups)
• We use multiple inheritance to add the ability of grouping figures
Copyright S. Haridi & P. Van Roy 67
Class diagrams
Figure
Line Circle
canvasx1, x2, y1, y2
canvasx, y, r
init, move(X Y),display
init, move(X Y),display
LinkListelem, next
init, add(O),forall(P)
CompositeFigure
init, move(X Y),display
Copyright S. Haridi & P. Van Roy 68
LinkedList Class
class LinkedList
attr items
meth init items := nil end
meth add(E) items := E|@items end
meth forall(M)
for O in @items do {O M} end
end
end
Copyright S. Haridi & P. Van Roy 69
LinkedList (pure object) Java style
class LinkedList attr item next meth init(item:E<=null next:N<=null) item := E next := N end meth add(E) next :={New LinkedList init(item:E next:@next)} end meth forall(M) if @elem\=null then {@item M} end if @next\=null then {@next forall(M)} end end end
Copyright S. Haridi & P. Van Roy 70
Lineclass Line from Figure attr canvas x1 y1 x2 y2 meth init(Can X1 Y1 X2 Y2) canvas := Can x1 := X1 y1 := Y1 x2 := X2 y2 := Y2 end meth move(X Y) x1 := @x1+X y1 := @y1+Y x2 := @x2+X y2 := @y2+Y end meth display {@canvas create(line @x1 @y1 @x2 @y2)} end end
Copyright S. Haridi & P. Van Roy 71
CompositeFigure
class CompositeFigure from Figure LinkedList meth init LinkedList, init end meth move(X Y) {self forall(move(X Y))} end meth display {self forall(display)} end end
Copyright S. Haridi & P. Van Roy 72
Use of single inheritance
LinkListelem, next
init, add(O),forall(P)
CompositeFigure
init, move(X Y),display, add(O)
Figure
linkList
1 1
association
Copyright S. Haridi & P. Van Roy 73
CompositeFigureclass CompositeFigure from Figure attr linkList meth init figlist {New LinkedList init} end meth add(F) {@linkList add(F)} end meth move(X Y) {@linkList forall(move(X Y))} end meth display {@linkList forall(display)} end end
Copyright S. Haridi & P. Van Roy 74
Multiple vs. Single inheritance
• With multiple inheritance a composite figure is also a linked list.
• In general use multiple inheritence in this case if you want all operations of linked list to be available
• With single inheritance a composite figure completely hides the linked list
• Use single inheritance if you want to hide the linked list functionality
Copyright S. Haridi & P. Van Roy 75
Rules for using inheritance
• Do not violate the substitution property. Programs working on objects of a given class should work on all the objects of its subclasses
• Do not use subclassing to fix small problem. That is to say do not patch up a class by making a subclass. The class hierarchy tends to get large and the program slower
Copyright S. Haridi & P. Van Roy 76
When does multiple inheritance work?
• Multiple inheritance works well when combining two completely independent abstractions
• Multiple inheritance does not work when abstractions have something in common
• Mutiple inheritance does not work when their is a shared class with mutable attributes
Copyright S. Haridi & P. Van Roy 77
When it does not work?
• Mutiple inheritance does not work when there is a shared class with mutable attributes
• Creating a BHistoryPoint object could replicate the operations on Point though
• HistroyPoint and BoundedPoint
• Known as the implementation sharing problem
Point
HistoryPoint BoundedPoint
BHistoryPoint
Copyright S. Haridi & P. Van Roy 78
HOP vs.OOP
• We show how to get some of the flexibility of higher order programming in OOP
proc {NewSort Order ?SortRoutine} proc {SortRoutine InL ?OutL}
... {Order X Y Z} endend
class SortRoutineClass attr ord meth init(Order) ord Order end meth sort(InL ?OutL) ... {@ord order(X Y Z)} endend
Copyright S. Haridi & P. Van Roy 79
HOP vs.OOP
• We show how to get some of the flexibility of higher order programming in OOP
X ... YP = proc{$} Some Statement with free X Y end
.... {P}
class Proc attr x y meth init(X Y) x X y Y end meth apply Some statement with @x and @Y endend
X ... YP = {New Proc init(X Y)}
.... {P apply}
Copyright S. Haridi & P. Van Roy 80
HOP vs.OOP
• We show how to get some of the flexibility of higher order programming in OOP
• A lot of the higher order functionality can be coded
proc {Map Xs P Ys} .... {P X Y} Ys = Y|Yr {Map Xr P Yr}
meth map(Xs O Ys) .... {O apply(X Y)} Ys = Y|Yr map(Xr O Yr)