Você está na página 1de 61

Object-Oriented Programming

Seif Haridi
Peter Van Roy

Copyright 2002 by S. Haridi and P. Van Roy 1


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
• 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 2002 by S. Haridi and P. Van Roy 2


Component based programming
• Supports
– Encapsulation
– Compositionality
– Instantiation

Copyright 2002 by S. Haridi and P. Van Roy 3


Object-oriented programming
• Supports
– Encapsulation
– Compositionality
– Instantiation
• Plus
– Inheritance

Copyright 2002 by S. Haridi and P. Van Roy 4


Inheritance
• Programs can be built in hierarchical structure from data abstractions
that depend on other data abstractions (Components)
• The object style of data abstraction is the default, not the ADT style
• 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 2002 by S. Haridi and P. Van Roy 5


What is object-oriented
programming?
• OOP (Object-oriented programming) = encapsulated state
+ inheritance
• Object
– An entity with unique identity that encapsulate 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
– By inheriting from other classes
– And specifying how its objects (instances) differ from
the objects of the inherited classes
Copyright 2002 by S. Haridi and P. Van Roy 6
Instances (objects)

Interface (what methods


are available)

State (attributes)

procedures (methods)

Copyright 2002 by S. Haridi and P. Van Roy 7


Classes as complete spec of a
data abstraction
• We start our case study
• elements of a class (members)
– attributes (multable instance variables)
– features (stateless info about objects)
– methods

Copyright 2002 by S. Haridi and P. Van Roy 8


Classes (syntax simple)
A class is a statement

class ClassVariable
attr
AttrName1
:
AttrNameN
meth Pattern1 Statement end
:
meth PatternN Statement end
end

Copyright 2002 by S. Haridi and P. Van Roy 9


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

Copyright 2002 by S. Haridi and P. Van Roy 10


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
Copyright 2002 by S. Haridi and P. Van Roy 11
Attributes of Classes
The class Counter has the syntactic form
class Counter val is an attribute
attr val a modifiable cell
meth browse
that is access by the
{Browse @val}
end atom val
meth inc(Value)
val := @val + Value
end
meth init(Value)
val := Value
end
end
Copyright 2002 by S. Haridi and P. Van Roy 12
Attributes of classes
The class Counter has the syntactic form
class Counter
attr val
meth browse
{Browse @val} the attribute val
end is accessed by the
meth inc(Value)
operator @val
val := @val + Value
end
meth init(Value)
val := Value
end
end
Copyright 2002 by S. Haridi and P. Van Roy 13
Attributes of classes
The class Counter has the syntactic form
class Counter
attr val
meth browse
{Browse @val} the attribute val
end is assigned by the
meth inc(Value)
operator :=
val := @val + Value
end as val := ...
meth init(Value)
val := Value
end
end
Copyright 2002 by S. Haridi and P. Van Roy 14
Methods of classes
The class Counter has the syntactic form
class Counter methods
attr val are statements
meth browse method head is a
{Browse @val} record (tuple) pattern
end
meth inc(Value)
val := @val + Value
end
meth init(Value)
val := Value
end
end
Copyright 2002 by S. Haridi and P. Van Roy 15
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
Copyright 2002 by S. Haridi and P. Van Roy 16
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 2002 by S. Haridi and 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} Object interface is as a procedure
{C inc(1)} with one argument (see procedure
{C browse} dispatch method Chapter 8)

Copyright 2002 by S. Haridi and P. Van Roy 18


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 2002 by S. Haridi and P. Van Roy 19
Summary

• 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

Copyright 2002 by S. Haridi and P. Van Roy 20


Attribute Initialization
• Stateful (may be updated by :=)
• Initialized at object creation time, all instances
have the initial balance = 0

• class Account In general the initial value


attr balance:0 of an attribute could be any
meth … end legal value (including
classes and objects)

end

Copyright 2002 by S. Haridi and P. Van Roy 21


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 2002 by S. Haridi and P. Van Roy 22


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
Copyright 2002 by S. Haridi and P. Van Roy 23
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

Copyright 2002 by S. Haridi and P. Van Roy 24


Example
class Queue
attr front back count
meth init front
Q in Q0
front := Q back := Q count := 0 back
end
meth put(X) put(a)
Q in
@back = X|Q
back := Q front
count := @count + 1 a | Q1
end back
...
end
Copyright 2002 by S. Haridi and P. Van Roy 25
Example
class Queue
attr front back count front
a | Q1
...
back
meth get(?X)
Q in X
X|Q = @front
front := Q
count := @count - 1
front
end a | Q1
meth count(X) X = @count end back
...
end X

Copyright 2002 by S. Haridi and P. Van Roy 26


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

Copyright 2002 by S. Haridi and P. Van Roy 27


Inheritance
• Inheritance should be seen as a
way to specialize a class while
retaining the relationship general
between methods class
• 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
specialized
class

Copyright 2002 by S. Haridi and P. Van Roy 28


Inheritance
class Account
attr balance:0
meth transfer(Amount)
balance := @balance+Amount
end
meth getBal(B)
B = @balance
end
end

A={New Account transfer(100)}

Copyright 2002 by S. Haridi and P. Van Roy 29


Inheritance II
The class VerboseAccount has
the methods:
transfer, getBal, and
verboseTransfer
Conservative extension
class VerboseAccount
from Account
meth verboseTransfer(Amount)
...
end
end

Copyright 2002 by S. Haridi and P. Van Roy 30


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

Copyright 2002 by S. Haridi and P. Van Roy 31


Inheritance II

Non-Conservative extension Account

class AccountWithFee
from VerboseAccount
VerboseAccount
attr fee:5
meth transfer(Amount)
...
end AccountWithFee
end

Copyright 2002 by S. Haridi and P. Van Roy 32


Static and dynamic binding
Dynamic binding
• Inside an object O we want to class C
invoke a method M meth M
• This is written as {self M}, and
chooses the method visible in
the current object (M of D)

class D
O
a subclass of
an instance
C
of D
meth M

Copyright 2002 by S. Haridi and P. Van Roy 33


Static and dynamic binding
Static binding
• Inside an object O we want to class C
invoke a method M in a specific meth M
(super) class
• This is written as C, M and
chooses the method visible in
the super class C (M of C)
class D
O
a subclass of
an instance
C
of D
meth M

Copyright 2002 by S. Haridi and P. Van Roy 34


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 2002 by S. Haridi and P. Van Roy 35
Inheritance
class Account
attr balance:0
meth transfer(Amount)
balance := @balance+Amount
end
meth getBal(B)
B = @balance
end
end

A={New Account transfer(100)}

Copyright 2002 by S. Haridi and P. Van Roy 36


Inheritance II
The class VerboseAccount has
the methods:
transfer, getBal, and
verboseTransfer
Conservative extension
class VerboseAccount
from Account
meth verboseTransfer(Amount)
{self transfer(Amount)}
{Show @balance}
end
end

Copyright 2002 by S. Haridi and P. Van Roy 37


Inheritance III
The class
AccountWithFee has the
Non-Conservative extension mothods:
class AccountWithFee transfer, getBal, and
from VerboseAccount verboseTransfer
attr fee:5 The method transfer
meth transfer(Amount)
has been redefined
VerboseAccount, transfer(Amount - @fee)
end
(overridden) with
end another definition

Copyright 2002 by S. Haridi and P. Van Roy 38


Inheritance IV

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.

Copyright 2002 by S. Haridi and P. Van Roy 40


SuperClass relation
• SuperClass relation is directed
and acyclic.

Copyright 2002 by S. Haridi and P. Van Roy 41


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 2002 by S. Haridi and P. Van Roy 42


Inheritance relation
m m

m A (valid hierarchy)

C (invalid hierarchy)

Copyright 2002 by S. Haridi and P. Van Roy 43


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}

Copyright 2002 by S. Haridi and P. Van Roy 44


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

Copyright 2002 by S. Haridi and P. Van Roy 45


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 CustomerAccount has
class Customer attributes balance and name
attr name methods init, transfer and
meth init(N) name := N end getBalance
end
class CustomerAccount from Customer Account
meth init(N A)
Customer, init(N) This overriding is not
Account, init(A) harmful it does not
end
end change relationships
in super classes
Copyright 2002 by S. Haridi and P. Van Roy 46
Controlling visibility
• Visibility is the control given to the user to limit access to
members of a class (attributes and methods)
• Each member (attribute or method) is defined with a scope
(part of program text that the member can be accessed by
name)
• Programming languages use words like public, private,
and protected to define visibility
• Unfortunately, different languages use these keywords to
define different scopes
– Source of enormous confusion! Be careful!

Copyright 2002 by S. Haridi and P. Van Roy 47


Public and private scopes

• In Smalltalk and Oz, a private member is one which is


only visible in the object instance
– The object instance can see all the private members in
its class and its super classes
• In C++ and Java, a private member is visible among all
instances of a given class, but not to subclasses
• A public member is visible anywhere in the program
• By default, attributes are private and methods are public

Copyright 2002 by S. Haridi and P. Van Roy 48


Public and private scopes
• Other scopes can be programmed by local A={NewName}
using name values (as we saw for
secure ADTs) in
• For example, let us make a method class C
private within a class (like C++ and meth !A(...) ... end
Java) ...
• The method name is a name value
end
– Define a new name A
end
– Use the syntax !A for the method
name
• Short-cut: class C
– Use the syntax A for the method meth A(...) ... end
name makes the NewName implicit ...
• With names, any kind of privacy can be
programmed end
Copyright 2002 by S. Haridi and P. Van Roy 49
Summary of scopes
• In Java, in order from least to most visible:
• Private: accessible within a class (among all its objects)
• Package: accessible within a package
• Protected: accessible within a package and to subclasses
• Public: accessible to all

• In Oz, in order from least to most visible:


• Private: accessible within one object (not possible in Java!)
• Programmed (with name value): any accessibility
• Public: accessible to all
Copyright 2002 by S. Haridi and P. Van Roy 50
Programming techniques

• Constructing a hierarchy by following the type


• Abstract and concrete classes
• First class messages
• Parameterized classes
• Use of multiple inheritance

Copyright 2002 by S. Haridi and P. Van Roy 51


Constructing a hierarchy
by following the type I
• General lists have the following definition
list T ::= nil [] T | list
• Constructing a hierarchy following this definition
guarantees that the substitution principle is followed

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

• ListClass is an abstract class, i.e., a class in which some methods


are left undefined (such as init and append)
• Abstract classes are not intended to be instantiated, but inherited
from
• Inheritance “fills in the blanks” by adding the missing methods
• The result is a concrete class, i.e., a class that can be instantiated
since all its methods are defined
• NilClass and ConsClass are concrete classes
• This technique is an example of higher-order programming (namely
genericity: passing a procedure value, i.e., a method)
Copyright 2002 by S. Haridi and P. Van Roy 54
Techniques of
higher-order programming

Control abstractions
class HO
meth forAll(LO M)
for O in LO do {O M} end
end
...
end
This technique allows messages as parameters

Copyright 2002 by S. Haridi and P. Van Roy 55


Parameterized 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
end
end
Account={MakeClassAccountWithFee 100}
{New Account init(1000)}

Copyright 2002 by S. Haridi and P. Van Roy 56


Classes as first-class values

fun {MakeClassAcountWithFee Fee}


class $ %% Fee is in closure
from Account
meth init(Amount)
Account,init(Amount-Fee)
end
end
end
Account={MakeClassAccountWithFee 100}
{New Account init(1000)}

Copyright 2002 by S. Haridi and P. Van Roy 57


Forwarding and delegation
• Inheritance, as we saw it, is one way to define new functionality from
existing functionality
• Inheritance can be tricky to use well, because it implies a tight binding
between the original and new classes
• Two looser approaches, which are sometimes better, are forwarding
and delegation:
– “If object O1 does not understand message M, then it passes M to
object O2”
• Forwarding and delegation differ in how they treat self:
– In forwarding, O1 and O2 keep separate identities: a self call in O2
stays in O2
– In delegation, there is just one identity, namely O1: a self call in
O2 will call O1 (delegation implies a common self)

Copyright 2002 by S. Haridi and P. Van Roy 58


Forwarding I
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}

Copyright 2002 by S. Haridi and P. Van Roy 59


Forwarding II
VerboseAccount =
{New
class $ from BaseObject
attr forward:Account
meth verboseTransfer(Amount)
B in
{self transfer(Amount)}
{self getBalance(B)}
{Browse B}
end
meth otherwise(M) {@forward M} end
end
init
} Copyright 2002 by S. Haridi and P. Van Roy 60
The three approaches

Inheritance Delegation Forwarding


Defined on classes Defined on objects Defined on objects
Common self No common self No common self

Tight binding between original Loose binding


and derived object/class

Static approach: Dynamic approaches:


At class definition Can be defined at run-time

Copyright 2002 by S. Haridi and P. Van Roy 61

Você também pode gostar