Download presentation
Presentation is loading. Please wait.
1
Object-Oriented Programming
Seif Haridi Peter Van Roy Copyright by S. Haridi and 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 by S. Haridi and P. Van Roy
3
Component based programming
Supports Encapsulation Compositionality Instantiation Copyright by S. Haridi and P. Van Roy
4
Object-oriented programming
Supports Encapsulation Compositionality Instantiation Plus Inheritance Copyright by S. Haridi and P. Van Roy
5
Copyright by S. Haridi and P. Van Roy
Inheritance Programs can be built in hierarchical structure from ADT’s that depend on other ADT’s (Components) Object-oriented programming (inheritance) is based on the idea that ADT has so much in common Example, sequences (stacks, lists, queues) Object oriented programming builds ADT incrementally, this is done by inheritance An ADT can be defined to ”inherit” from another abstract datatype, have substantially the same functionality of the other abstract datatype Only the difference between an abstract datatype and its ancestor has to be specified Copyright by S. Haridi and 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 by S. Haridi and P. Van Roy
7
Copyright by S. Haridi and P. Van Roy
Instances (objects) Interface (what methods are available) State (attributes) procedures (methods) Copyright by S. Haridi and P. Van Roy
8
Classes as complete spec of ADT
We start our case study elements of a class (members) attributes (mutable instance variables) features (stateless info about objects) methods Copyright by S. Haridi and P. Van Roy
9
Classes (syntax simple)
A class is a statement class ClassVariable attr AttrName1 : AttrNameN meth Pattern1 Statement end meth PatternN Statement end end Copyright by S. Haridi and P. Van Roy
10
Classes (syntax simplified)
A class is also a value that can be in an expression position class $ attr AttrName1 : AttrNamen meth Pattern Statement end end Copyright by S. Haridi and P. Van Roy
11
Copyright by S. Haridi and P. Van Roy
Classes in Oz The class Counter has the syntactic form class Counter attr val meth browse end meth inc(Value) val + Value end meth init(Value) val Value end end Copyright by S. Haridi and P. Van Roy
12
Copyright by S. Haridi and P. Van Roy
Attributes of Classes The class Counter has the syntactic form class Counter attr val meth browse end meth inc(Value) val + Value end meth init(Value) val Value end end val is an attribute a modifiable cell that is access by the atom val Copyright by S. Haridi and P. Van Roy
13
Copyright by S. Haridi and P. Van Roy
Attributes of classes The class Counter has the syntactic form class Counter attr val meth browse end meth inc(Value) val + Value end meth init(Value) val Value end end the attribute val is accessed by the Copyright by S. Haridi and P. Van Roy
14
Copyright by S. Haridi and P. Van Roy
Attributes of classes The class Counter has the syntactic form class Counter attr val meth browse end meth inc(Value) val + Value end meth init(Value) val Value end end the attribute val is assigned by the operator as val ... Copyright by S. Haridi and P. Van Roy
15
Copyright by S. Haridi and P. Van Roy
Methods of classes The class Counter has the syntactic form class Counter attr val meth browse end meth inc(Value) val + Value end meth init(Value) val Value end end methods are statements method head is a record (tuple) pattern Copyright by S. Haridi and P. Van Roy
16
Copyright by S. Haridi and P. Van Roy
Classes in Oz The class Counter has the syntactic form class Counter attr val meth browse end meth inc(Value) val + Value end meth init(Value) val Value end end Copyright by S. Haridi and P. Van Roy
17
Copyright by S. Haridi and P. Van Roy
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 by S. Haridi and P. Van Roy
18
The procedure-based approach
fun {Counter} X S = {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)} S.val := Value end D = o(inc:Inc browse:Display init:Init) in proc{$ M} {D.{Label M} M} end end Copyright by S. Haridi and P. Van Roy
19
The procedure-based approach
fun {Counter} X S = {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 by S. Haridi and P. Van Roy
20
Copyright by S. Haridi and P. Van Roy
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 procedure with one argument (see procedure dispatch method Chapter 8) Copyright by S. Haridi and P. Van Roy
21
Copyright by S. Haridi and P. Van Roy
Summary 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. Copyright by S. Haridi and P. Van Roy
22
Copyright by S. Haridi and P. Van Roy
Summary An attribute A is accessed An attribute is assigned a value using A E A class can be defined as a value: X = class $ ... end Copyright by S. Haridi and P. Van Roy
23
Attribute Initialization
Stateful (may be updated by ) Initialized at object creation time, all instances have the initial balance = 0 class Account attr balance:0 meth … end … end In general the initial value of an attribute could be any legal value (including classes and objects) Copyright by S. Haridi and P. Van Roy
24
Attribute Initialization
Initialization by instance class Account attr balance meth init(X) balance X end … end C1 = {New Account init(100)} C1 = {New Account init(50)} Copyright by S. Haridi and P. Van Roy
25
Attribute Initialization
Initialization by brand declare L=linux class RedHat attr ostype:L meth get(X) X end end class SuSE class Debian Copyright by S. Haridi and P. Van Roy
26
Copyright by S. Haridi and P. Van Roy
Example class Queue attr front back count meth init Q in front Q back Q count 0 end meth put(X) @back = X|Q back Q count + 1 ... Copyright by S. Haridi and P. Van Roy
27
Copyright by S. Haridi and P. Van Roy
Example class Queue attr front back count meth init Q in front Q back Q count 0 end meth put(X) @back = X|Q back Q count + 1 ... front Q0 back put(a) front a | Q1 back Copyright by S. Haridi and P. Van Roy
28
Copyright by S. Haridi and P. Van Roy
Example class Queue attr front back count ... meth get(?X) Q in X|Q front Q count - 1 end meth count(X) X end front a | Q1 back X front a | Q1 back X Copyright by S. Haridi and P. Van Roy
29
Classes as incremental ADTs
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 by S. Haridi and P. Van Roy
30
Copyright by S. Haridi and P. Van Roy
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 an ADT The other view is inheritance is just a (lazy) way to construct new abstract data types ! No relationships are preserved general class specialized class Copyright by S. Haridi and P. Van Roy
31
Copyright by S. Haridi and P. Van Roy
Inheritance class Account attr balance:0 meth transfer(Amount) balance end meth getBal(B) B A={New Account transfer(100)} Copyright by S. Haridi and P. Van Roy
32
Copyright by S. Haridi and P. Van Roy
Inheritance II The class VerboseAccount has the methods: transfer, getBal, and verboseTransfer Conservative extension class VerboseAccount from Account meth verboseTransfer(Amount) ... end Copyright by S. Haridi and P. Van Roy
33
Copyright by S. Haridi and P. Van Roy
Inheritance II The class AccountWithFee has the mothods: transfer, getBal, and verboseTransfer The method transfer has been redefined (overridden) with another definition Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) ... end Copyright by S. Haridi and P. Van Roy
34
Copyright by S. Haridi and P. Van Roy
Inheritance II Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) ... end Account VerboseAccount AccountWithFee Copyright by S. Haridi and P. Van Roy
35
Static and 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 C meth M class D a subclass of C meth M O an instance of D Copyright by S. Haridi and 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 C meth M class D a subclass of C meth M O an instance of D Copyright by S. Haridi and P. Van Roy
37
Copyright by S. Haridi and P. Van Roy
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 by S. Haridi and P. Van Roy
38
Copyright by S. Haridi and P. Van Roy
Inheritance class Account attr balance:0 meth transfer(Amount) balance end meth getBal(B) B A={New Account transfer(100)} Copyright by S. Haridi and P. Van Roy
39
Copyright by S. Haridi and P. Van Roy
Inheritance II The class VerboseAccount has the methods: transfer, getBal, and verboseTransfer Conservative extension class VerboseAccount from Account meth verboseTransfer(Amount) {self transfer(Amount)} end Copyright by S. Haridi and P. Van Roy
40
Copyright by S. Haridi and P. Van Roy
Inheritance II The class AccountWithFee has the mothods: transfer, getBal, and verboseTransfer The method transfer has been redefined (overridden) with another definition Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount, transfer(Amount end Copyright by S. Haridi and P. Van Roy
41
Copyright by S. Haridi and P. Van Roy
Inheritance II Non-Conservative inheritance is dangerous because it might change the relationship between methods and the invariants the programmer depends on Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount, transfer(Amount end Account getBalance(B); transfer(S); getBalance(B1) => B1 = B-S Copyright by S. Haridi and P. Van Roy
42
Copyright by S. Haridi and P. Van Roy
Inheritance II Non-Conservative inheritance is dangerous because it might change the relationship between methods and the invariants the programmer depends on Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount, transfer(Amount end AccountWithFree getBalance(B); transfer(S) iff Copyright by S. Haridi and P. Van Roy
43
Copyright by S. Haridi and P. Van Roy
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 by S. Haridi and P. Van Roy
44
Copyright by S. Haridi and P. Van Roy
SuperClass relation SuperClass relation is directed and acyclic. C Copyright by S. Haridi and P. Van Roy
45
Copyright by S. Haridi and P. Van Roy
SuperClass relation 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. C Copyright by S. Haridi and P. Van Roy
46
Copyright by S. Haridi and P. Van Roy
Inheritance relation m m A (valid hierarchy) m C (invalid hierarchy) Copyright by S. Haridi and P. Van Roy
47
Multiple Inheritance Example
class Account attr balance:0 meth transfer(Amount) balance end meth getBal(?B) B end class Customer attr name meth init(N) name N end class CustomerAccount from Customer Account end A={New CustomerAccount init} Copyright by S. Haridi and P. Van Roy
48
Copyright by S. Haridi and P. Van Roy
Illegal inheritance class Account attr balance meth init(Amount) balance Amount end meth transfer(Amount) balance meth getBal(B) B end class Customer attr name meth init(N) name N end class CustomerAccount from Customer Account end There are two init methods visible for CustomerAccount This is illegal Copyright by S. Haridi and P. Van Roy
49
Copyright by S. Haridi and P. Van Roy
Legal inheritance class Account attr balance meth init(Amount) balance Amount end meth transfer(Amount) balance end meth getBal(B) B end end class Customer attr name meth init(N) name N end class CustomerAccount from Customer Account meth init(N A) Customer, init(N) Account, init(A) CustomerAccount has attributes balance and name methods init, transfer and getBalance This overriding is not harmful it does not change relationships in super classes Copyright by S. Haridi and 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 by S. Haridi and P. Van Roy
51
Public and private scopes in ADTs
A private member is one which is only visible in the object instance (it is used for implementing the ADT) 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 ADT In Oz (and Smalltalk) attributes are private and methods are public (the default rule) In Java and C++ private has another meaning Copyright by S. Haridi and P. Van Roy
52
Copyright by S. Haridi and P. Van Roy
The meaning of Private C Class Hierarchy SubC SubSubC I1 I2 I3 I4 Instances Copyright by S. Haridi and P. Van Roy
53
Copyright by S. Haridi and P. Van Roy
The meaning of Private C Class Hierarchy According to Smalltalk and Oz SubC All private memebers in this region are visible to I3 SubSubC I1 I2 I3 I4 Instances Copyright by S. Haridi and P. Van Roy
54
Copyright by S. Haridi and P. Van Roy
The meaning of Private C Class Hierarchy According to C++ and Java All private memebers in this region are visible to I3 SubC SubSubC I1 I2 I3 I4 Instances Copyright by S. Haridi and P. Van Roy
55
Public and private scopes in ADTs
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 by S. Haridi and P. Van Roy
56
Public and private scopes in ADTs
class C meth A(...) ... end .... end 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 local A = {NewName} in class C meth !A(...) ... end .... end Copyright by S. Haridi and P. Van Roy
57
Programming techniques
First class messages (higher order programming) Parameterized classes Use of multiple inheritance Copyright by S. Haridi and 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 ... This technique allows messages as parameters Copyright by S. Haridi and 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 C = {New class $ from HigherOrderControl Counter end init(0)} {C [inc(2) browse inc(3) browse]} Copyright by S. Haridi and 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 Account={MakeClassAccountWithFee 100} {New Account init(1000)} Copyright by S. Haridi and 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 Account={MakeClassAccountWithFee 100} {New Account init(1000)} Copyright by S. Haridi and P. Van Roy
62
Copyright by S. Haridi and P. Van Roy
Delegation Some object systems do not use inheritance (SELF) They use a notion known as delegation Every class is an object Inheritance 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 by S. Haridi and P. Van Roy
63
Copyright by S. Haridi and P. Van Roy
Delegation Account = {New class $ attr balance meth init balance 0 end meth transfer(Amount) balance end meth getBal(B) B end init} Copyright by S. Haridi and P. Van Roy
64
Programming techniques with multiple inheritance
Copyright by S. Haridi and P. Van Roy
65
Copyright by S. Haridi and P. Van Roy
Delegation VerboseAccount = {New class $ from BaseObject attr delegate:Account meth verboseTransfer(Amount) B in {self transfer(Amount)} {self getBalance(B)} {Show B} end meth otherwise(M) M} end init } Copyright by S. Haridi and P. Van Roy
66
Copyright by S. Haridi and P. Van Roy
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 by S. Haridi and P. Van Roy
67
Copyright by S. Haridi and P. Van Roy
Class diagrams LinkList Figure elem, next init, add(O), forall(P) Line Circle CompositeFigure canvas x1, x2, y1, y2 canvas x, y, r init, move(X Y), display init, move(X Y), display init, move(X Y), display Copyright by S. Haridi and P. Van Roy
68
Copyright by S. Haridi and P. Van Roy
LinkedList Class class LinkedList attr items meth init items nil end meth add(E) items end meth forall(M) for O do {O M} end end Copyright by S. Haridi and 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 meth forall(M) then M} end then forall(M)} end Copyright by S. Haridi and P. Van Roy
70
Copyright by S. Haridi and P. Van Roy
Line class 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 y1 x2 y2 meth display @y2)} Copyright by S. Haridi and P. Van Roy
71
Copyright by S. Haridi and P. Van Roy
CompositeFigure class CompositeFigure from Figure LinkedList meth init LinkedList, init end meth move(X Y) {self forall(move(X Y))} meth display {self forall(display)} Copyright by S. Haridi and P. Van Roy
72
Use of single inheritance
Figure association 1 1 CompositeFigure LinkList elem, next linkList init, add(O), forall(P) init, move(X Y), display, add(O) Copyright by S. Haridi and P. Van Roy
73
Copyright by S. Haridi and P. Van Roy
CompositeFigure class CompositeFigure from Figure attr linkList meth init figlist {New LinkedList init} end meth add(F) add(F)} meth move(X Y) forall(move(X Y))} meth display forall(display)} Copyright by S. Haridi and 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 by S. Haridi and 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 by S. Haridi and 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 by S. Haridi and P. Van Roy
77
Copyright by S. Haridi and P. Van Roy
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 by S. Haridi and P. Van Roy
78
Copyright by S. Haridi and P. Van Roy
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} end class SortRoutineClass attr ord meth init(Order) ord Order end meth sort(InL ?OutL) ... order(X Y Z)} Copyright by S. Haridi and P. Van Roy
79
Copyright by S. Haridi and P. Van Roy
HOP vs.OOP We show how to get some of the flexibility of higher order programming in OOP class Proc attr x y meth init(X Y) x X y Y end meth apply Some statement X ... Y P = proc{$} Some Statement with free X Y end .... {P} X ... Y P = {New Proc init(X Y)} .... {P apply} Copyright by S. Haridi and P. Van Roy
80
Copyright by S. Haridi and P. Van Roy
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 meth map(Xs O Ys) .... {O apply(X Y)} Ys = Y|Yr map(Xr O Yr) proc {Map Xs P Ys} .... {P X Y} Ys = Y|Yr {Map Xr P Yr} Copyright by S. Haridi and P. Van Roy
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.