Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright S. Haridi & P. Van Roy1 Object-Oriented Programming Seif Haridi Peter Van Roy.

Similar presentations


Presentation on theme: "Copyright S. Haridi & P. Van Roy1 Object-Oriented Programming Seif Haridi Peter Van Roy."— Presentation transcript:

1 Copyright S. Haridi & P. Van Roy1 Object-Oriented Programming Seif Haridi Peter Van Roy

2 Copyright S. Haridi & P. Van Roy2 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)

3 Copyright S. Haridi & P. Van Roy3 Component based programming Supports –Encapsulation –Compositionality –Instantiation

4 Copyright S. Haridi & P. Van Roy4 Object-oriented programming Supports –Encapsulation –Compositionality –Instantiation Plus –Inheritance

5 Copyright S. Haridi & P. Van Roy5 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

6 Copyright S. Haridi & P. Van Roy6 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

7 Copyright S. Haridi & P. Van Roy7 Instances (objects) Interface (what methods are available) State (attributes) procedures (methods)

8 Copyright S. Haridi & P. Van Roy8 Classes as complete spec of a data abstraction We start our case study elements of a class (members) –attributes (mutable instance variables) –features (stateless info about objects) –methods

9 Copyright S. Haridi & P. Van Roy9 Classes (syntax simple) A class is a statement class  ClassVariable  attr  AttrName1  :  AttrNameN  meth  Pattern1   Statement  end : meth  PatternN   Statement  end end

10 Copyright S. Haridi & P. Van Roy10 Classes (syntax simplified) A class is also a value that can be in an expression position class $ attr  AttrName1  :  AttrNamen  meth  Pattern   Statement  end : meth  Pattern   Statement  end end

11 Copyright S. Haridi & P. Van Roy11 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 end end

12 Copyright S. Haridi & P. Van Roy12 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 end end val is an attribute a modifiable cell that is access by the atom val

13 Copyright S. Haridi & P. Van Roy13 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 end end the attribute val is accessed by the operator @ val

14 Copyright S. Haridi & P. Van Roy14 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 end end the attribute val is assigned by the operator := as val :=...

15 Copyright S. Haridi & P. Van Roy15 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 end end methods are statements method head is a record (tuple) pattern

16 Copyright S. Haridi & P. Van Roy16 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 end end

17 Copyright S. Haridi & P. Van Roy17 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}

18 Copyright S. Haridi & P. Van Roy18 The procedure-based approach fun {Counter} X S 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 S 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

19 Copyright S. Haridi & P. Van Roy19 The procedure-based approach fun {Counter} X S 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

20 Copyright S. Haridi & P. Van Roy20 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)

21 Copyright S. Haridi & P. Van Roy21 A class X is defined by: –class X... end Attributes are defined using the attribute-declaration part before the method-declaration part: –attr A 1... A N 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

22 Copyright S. Haridi & P. Van Roy22 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

23 Copyright S. Haridi & P. Van Roy23 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)

24 Copyright S. Haridi & P. Van Roy24 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)}

25 Copyright S. Haridi & P. Van Roy25 Attribute Initialization Initialization by brand declare L=linux class RedHat attr ostype:L meth get(X) X = @ostype end end class SuSE attr ostype:L meth get(X) X = @ostype end end class Debian attr ostype:L meth get(X) X = @ostype end end

26 Copyright S. Haridi & P. Van Roy26 Example class 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

27 Copyright S. Haridi & P. Van Roy27 Example class 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)

28 Copyright S. Haridi & P. Van Roy28 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

29 Copyright S. Haridi & P. Van Roy29 Classes as incremental specs of 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

30 Copyright S. Haridi & P. Van Roy30 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 general class specialized class

31 Copyright S. Haridi & P. Van Roy31 Inheritance class Account attr balance:0 meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance end A={New Account transfer(100)}

32 Copyright S. Haridi & P. Van Roy32 Inheritance II Conservative extension class VerboseAccount from Account meth verboseTransfer(Amount)... end The class VerboseAccount has the methods: transfer, getBal, and verboseTransfer

33 Copyright S. Haridi & P. Van Roy33 Inheritance II Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount)... end The class AccountWithFee has the mothods: transfer, getBal, and verboseTransfer The method transfer has been redefined (overridden) with another definition

34 Copyright S. Haridi & P. Van Roy34 Inheritance II Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount)... end Account VerboseAccount AccountWithFee

35 Copyright S. Haridi & P. Van Roy35 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 C meth M class D a subclass of C meth M O an instance of D

36 Copyright S. Haridi & P. Van Roy36 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

37 Copyright S. Haridi & P. Van Roy37 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.

38 Copyright S. Haridi & P. Van Roy38 Inheritance class Account attr balance:0 meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance end A={New Account transfer(100)}

39 Copyright S. Haridi & P. Van Roy39 Inheritance II Conservative extension class VerboseAccount from Account meth verboseTransfer(Amount) { self transfer(Amount)} {Show @balance} end The class VerboseAccount has the methods: transfer, getBal, and verboseTransfer

40 Copyright S. Haridi & P. Van Roy40 Inheritance II Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount, transfer(Amount - @fee) end The class AccountWithFee has the mothods: transfer, getBal, and verboseTransfer The method transfer has been redefined (overridden) with another definition

41 Copyright S. Haridi & P. Van Roy41 Inheritance II Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount, transfer(Amount - @fee) end Non-Conservative inheritance is dangerous because it might change the relationship between methods and the invariants the programmer depends on Account getBalance(B); transfer(S); getBalance(B1) => B1 = B-S

42 Copyright S. Haridi & P. Van Roy42 Inheritance II Non-Conservative extension class AccountWithFee from VerboseAccount attr fee:5 meth transfer(Amount) VerboseAccount, transfer(Amount - @fee) end Non-Conservative inheritance is dangerous because it might change the relationship between methods and the invariants the programmer depends on AccountWithFree getBalance(B); transfer(S) iff getBalance(B-S-@fee)

43 Copyright S. Haridi & P. Van Roy43 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.

44 Copyright S. Haridi & P. Van Roy44 SuperClass relation C SuperClass relation is directed and acyclic.

45 Copyright S. Haridi & P. Van Roy45 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.

46 Copyright S. Haridi & P. Van Roy46 Inheritance relation C m m m A (valid hierarchy) (invalid hierarchy)

47 Copyright S. Haridi & P. Van Roy47 Multiple Inheritance Example class Account attr balance:0 meth transfer(Amount) balance := @balance+Amount end meth getBal(?B) B = @balance end end class Customer attr name meth init(N) name := N end end class CustomerAccount from Customer Account end A={New CustomerAccount init}

48 Copyright S. Haridi & P. Van Roy48 Illegal inheritance class Account attr balance meth init(Amount) balance := Amount end meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance end end class Customer attr name meth init(N) name := N end end class CustomerAccount from Customer Account end There are two init methods visible for CustomerAccount This is illegal

49 Copyright S. Haridi & P. Van Roy49 Legal inheritance class Account attr balance meth init(Amount) balance := Amount end meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance end end class Customer attr name meth init(N) name := N end end class CustomerAccount from Customer Account meth init(N A) Customer, init(N) Account, init(A) end CustomerAccount has attributes balance and name methods init, transfer and getBalance This overriding is not harmful it does not change relationships in super classes

50 Copyright S. Haridi & P. Van Roy50 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

51 Copyright S. Haridi & P. Van Roy51 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

52 Copyright S. Haridi & P. Van Roy52 The meaning of Private C SubC SubSubC I1I4I2I3 Instances Class Hierarchy

53 Copyright S. Haridi & P. Van Roy53 The meaning of Private C SubC SubSubC I1I4I2I3 Instances Class Hierarchy According to Smalltalk and Oz All private memebers in this region are visible to I3

54 Copyright S. Haridi & P. Van Roy54 The meaning of Private C SubC SubSubC I1I4I2I3 Instances Class Hierarchy According to C++ and Java All private memebers in this region are visible to I3

55 Copyright S. Haridi & P. Van Roy55 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

56 Copyright S. Haridi & P. Van Roy56 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 A local A = {NewName} in class C !A(...) meth !A(...)... end.... end

57 Copyright S. Haridi & P. Van Roy57 Programming techniques First class messages (higher order programming) Parameterized classes Use of multiple inheritance

58 Copyright S. Haridi & P. Van Roy58 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

59 Copyright S. Haridi & P. Van Roy59 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]}

60 Copyright S. Haridi & P. Van Roy60 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)}

61 Copyright S. Haridi & P. Van Roy61 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)}

62 Copyright S. Haridi & P. Van Roy62 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

63 Copyright S. Haridi & P. Van Roy63 Delegation Account = {New class $ attr balance meth init balance := 0 end meth transfer(Amount) balance := @balance+Amount end meth getBal(B) B = @balance end end init }

64 Copyright S. Haridi & P. Van Roy64 Programming techniques with multiple inheritance

65 Copyright S. Haridi & P. Van Roy65 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) {@delegate M} end end init }

66 Copyright S. Haridi & P. Van Roy66 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

67 Copyright S. Haridi & P. Van Roy67 Class diagrams Figure Line Circle canvas x1, x2, y1, y2 canvas x, y, r init, move(X Y), display init, move(X Y), display LinkList elem, next init, add(O), forall(P) CompositeFigure init, move(X Y), display

68 Copyright S. Haridi & P. Van Roy68 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

69 Copyright S. Haridi & P. Van Roy69 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

70 Copyright S. Haridi & P. Van Roy70 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 := @x1+X y1 := @y1+Y x2 := @x2+X y2 := @y2+Y end meth display {@canvas create(line @x1 @y1 @x2 @y2)} end

71 Copyright S. Haridi & P. Van Roy71 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

72 Copyright S. Haridi & P. Van Roy72 Use of single inheritance LinkList elem, next init, add(O), forall(P) CompositeFigure init, move(X Y), display, add(O) Figure linkList 1 1 association

73 Copyright S. Haridi & P. Van Roy73 CompositeFigure class 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

74 Copyright S. Haridi & P. Van Roy74 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

75 Copyright S. Haridi & P. Van Roy75 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

76 Copyright S. Haridi & P. Van Roy76 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

77 Copyright S. Haridi & P. Van Roy77 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 HistoryPointBoundedPoint BHistoryPoint

78 Copyright S. Haridi & P. Van Roy78 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)... {@ord order(X Y Z)} end

79 Copyright S. Haridi & P. Van Roy79 HOP vs.OOP We show how to get some of the flexibility of higher order programming in OOP X... Y P = 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 end X... Y P = {New Proc init(X Y)}.... {P apply}

80 Copyright S. Haridi & P. Van Roy80 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)


Download ppt "Copyright S. Haridi & P. Van Roy1 Object-Oriented Programming Seif Haridi Peter Van Roy."

Similar presentations


Ads by Google