You are on page 1of 43

Object-Oriented Programming

Dr. Nguyen Hua Phung

HCMC University of Technology, Viet Nam

08, 2016

Dr. Nguyen Hua Phung Object-Oriented Programming 1 / 46


Outline

1 OOP Introduction

2 Case Study: Scala

3 Case Study: Python

Dr. Nguyen Hua Phung Object-Oriented Programming 2 / 46


Object-Oriented Programming Goals

Programs as collections of collaborating objects


Object has public interface, hidden implementation
Objects are classfied according to their behavior
Objects may represent real-world entities or entities
that produce services for a program
Objects may be reusable across programs

Dr. Nguyen Hua Phung Object-Oriented Programming 4 / 46


Introduction To OOP Languages

There are many object-oriented programming (OOP)


languages
Some are pure OOP language (e.g., Smalltalk).
Newer languages do not support other paradigms but
use their imperative structures (e.g., Java and C]).
Some support procedural and data-oriented
programming (e.g., Ada and C++).
Some support functional program (e.g., Scala)

Dr. Nguyen Hua Phung Object-Oriented Programming 5 / 46


Some Important Features of OOP

Abstract data types


Encapsulation
Information Hiding
Class Hierarchy
Inheritance
Polymorphism - Dynamic Binding

Dr. Nguyen Hua Phung Object-Oriented Programming 6 / 46


Data Abstraction

An abstract data type is data type that satisfies the


following two conditions:
Encapsulation:
Attributes and operations are combined in a single
syntactic unit
compiled separately
Information Hiding:
The access to members are controlled
Reliability increased

Dr. Nguyen Hua Phung Object-Oriented Programming 7 / 46


Information Hiding

Dr. Nguyen Hua Phung Object-Oriented Programming 8 / 46


ADT Example

Operations on a stack: Client code:


create(stack) ...
destroy(stack) create ( stk1 ) ;
push ( stk1 , c o l o r 1 ) ;
empty(stack) push ( stk1 , c o l o r 2 ) ;
push(stack,element) i f ( ! empty ( s t k 1 ) )
temp = t o p ( s t k 1 ) ;
pop(stack)
...
top(stack)

Implementation can be adjacent or linked list. Client: don’t


care!

Dr. Nguyen Hua Phung Object-Oriented Programming 9 / 46


Class Hierarchy

A class may have some Subclasses


A class may have one/many Superclass(es)

Animal

Fish Mammal WingedAnimal

Whale Dog Cat Bat

Dr. Nguyen Hua Phung Object-Oriented Programming 10 / 46


Inheritance

A subclass is able to inherit non-private members of


its superclasses
A subclass can add its own members and override
its inherited members
Single vs. multiple inheritance
Inheritance increases the reusability in OOP

Dr. Nguyen Hua Phung Object-Oriented Programming 11 / 46


Example of Inheritance
x,y
Point draw()
move(newX,newY)

radius
Circle draw()

Dr. Nguyen Hua Phung Object-Oriented Programming 12 / 46


Diamond Problem in Multiple Inheritance

B C

if D inherits from B and C different versions of the


same behaviour, which version will be effective in D?
this problem, called diamond problem, is solved
differently in different OO language
is there the diamond problem in Java?

Dr. Nguyen Hua Phung Object-Oriented Programming 13 / 46


Class vs. Object; Method vs. Message

Class vs. Object


A class defines the abstract characteristics of a thing
its attributes or properties and
its behaviors or methods or features.
A Dog has fur and is able to bark
An object is a particular instance of a class.
Lassie is a dog

Method vs. Message


A method describes a behavior of an object.
A dog can bark
A message is a process at which a method of an
object is invoked.
Lassie barks

Dr. Nguyen Hua Phung Object-Oriented Programming 14 / 46


Polymorphism

Polymorphism: different objects can respond to the


same message in different ways.
x,y
Point draw()

radius
Circle draw()

p.draw()

Dynamic binding

Dr. Nguyen Hua Phung Object-Oriented Programming 15 / 46


Other Concepts

There are two kinds of variables in a class:


Class variables
Instance variables
There are two kinds of methods in a class:
Class methods – accept messages to the class
Instance methods – accept messages to objects
Abstract class vs. Concrete class:
Abstract Class – no instance
Concrete Class - able to have its instances

Dr. Nguyen Hua Phung Object-Oriented Programming 16 / 46


Scala Programming Language

Invented by Martin Ordesky at EPFL, Lausanne,


Switzerland.
Similar to Java
Work smoothly with Java
Run on Java Virtual Machine
OOP + FP
Include lexer and parser generator

Dr. Nguyen Hua Phung Object-Oriented Programming 18 / 46


Classes and Objects in Scala

Class
class [1]
abstract class [5]
trait [2]
case class [3]

Object
new <class name>
<case class name>
object

Dr. Nguyen Hua Phung Object-Oriented Programming 19 / 46


Example [7]

class R a t i o n a l ( n : I n t , d : I n t ) {
r e q u i r e ( d != 0)

p r i v a t e v a l g = gcd ( n . abs , d . abs )


p r i v a t e def gcd ( a : I n t , b : I n t ) : I n t =
i f ( b == 0 ) a else gcd ( b , a % b )
v a l numer = n / g
v a l denom = d / g

def t h i s ( n : I n t ) = t h i s ( n , 1 )

def + ( t h a t : R a t i o n a l ) : R a t i o n a l =
new R a t i o n a l (
numer ∗ t h a t . denom + t h a t . numer ∗ denom ,
denom ∗ t h a t . denom
)

override def t o S t r i n g = numer + " / " + denom


}
Dr. Nguyen Hua Phung Object-Oriented Programming 20 / 46
Example on Abstract class [4]

a b s t r a c t class Element {
def c o n t e n t s : A r r a y [ S t r i n g ] / / no body : a b s t r a c t
val height = contents . length
val width =
i f ( h e i g h t == 0 ) 0 else c o n t e n t s ( 0 ) . l e n g t h
}
class ArrayElement ( c o n t s : A r r a y [ S t r i n g ] )
extends Element {
def c o n t e n t s : A r r a y [ S t r i n g ] = c o n t s
}
class LineElement ( s : S t r i n g )
extends ArrayElement ( A r r a y ( s ) ) {
override def w i d t h = s . l e n g t h
override def h e i g h t = 1
}

Dr. Nguyen Hua Phung Object-Oriented Programming 21 / 46


Example on Object [1]

object Element {

def elem ( c o n t e n t s : A r r a y [ S t r i n g ] ) : Element =


new ArrayElement ( c o n t e n t s )

def elem ( l i n e : S t r i n g ) : Element =


new LineElement ( l i n e )
}

v a l space = Element . elem ( " " )


v a l h e l l o = Element . elem ( A r r a y ( " h e l l o " , " w o r l d " ) )

Which kind of Element will be assigned to space and


hello?

Dr. Nguyen Hua Phung Object-Oriented Programming 22 / 46


Example on Case Class [3]

a b s t r a c t class Expr

case class Var ( name : S t r i n g ) extends Expr


case class Number (num : Double ) extends Expr
case class UnOp( o p e r a t o r : S t r i n g , arg : Expr )
extends Expr
case class BinOp ( o p e r a t o r : S t r i n g ,
l e f t : Expr , r i g h t : Expr ) extends Expr

v a l v = Var ( " x " )


v a l op = BinOp ( " + " , Number ( 1 ) , v )
v . name
op . l e f t

Dr. Nguyen Hua Phung Object-Oriented Programming 23 / 46


Example 1 on Traits [9]
Reusability:
a b s t r a c t class B i r d

t r a i t Flying {
def f l y M e s s : S t r i n g
def f l y ( ) = p r i n t l n ( f l y M e s s )
}
t r a i t Swimming {
def swim ( ) = p r i n t l n ( " I ’m swimming " )
}

class Penguin extends B i r d with Swimming

class Hawk extends B i r d with Swimming with F l y i n g {


v a l f l y M e s s = " I ’m a good f l y e r "
}
class F r i g a t e b i r d extends B i r d with F l y i n g {
v a l f l y M e s s = " I ’m an e x c e l l e n t f l y e r "
}

Dr. Nguyen Hua Phung Object-Oriented Programming 24 / 46


Example 2 on Traits [2]

Stackable Modifications:
a b s t r a c t class IntQueue {
def g e t ( ) : I n t
def p u t ( x : I n t ) : U n i t }
class BasicIntQueue extends IntQueue {
p r i v a t e v a l b u f = new A r r a y B u f f e r [ I n t ]
def g e t ( ) = b u f . remove ( 0 )
def p u t ( x : I n t ) : U n i t = { b u f += x } }
t r a i t Doubling extends IntQueue {
a b s t r a c t override def p u t ( x : I n t ) { super . p u t ( 2 ∗ x ) } }
t r a i t I n c r e m e n t i n g extends IntQueue {
a b s t r a c t override def p u t ( x : I n t ) { super . p u t ( x + 1 ) } }
v a l queue =
new BasicIntQueue with I n c r e m e n t i n g with Doubling
queue . p u t ( 1 0 )
queue . g e t ( ) / / ? ? ?

Trait Linearization: Doubling-> Incrementing->


BasicIntQueue-> IntQueue-> AnyRef-> Any
Dr. Nguyen Hua Phung Object-Oriented Programming 25 / 46
Trait Linearization: Resolving Diamond Problem in Scala

A class extends just a single class but is able to have


many "with" traits
If these traits have the same method, which method
is inherited
Solution in Scala: Trait linearization
1 Take the first extended trait/class and write its
complete inherited hierarchy in vertical form, store
this hierarchy as X
2 Take the next trait/class after the with clause, write its
complete hierarchy and cancel the classes or traits
that are repeated in hierarchy X. Add the remaining
traits/classes to the front of the hierarchy X.
3 Go to step 2 and repeat the process, until no
trait/class is left out.
4 Place the class itself in front of hierarchy as head for
which the hierarchy is being written.
Dr. Nguyen Hua Phung Object-Oriented Programming 26 / 46
Example on Trait Linearization

trait A {
d e f name : S t r i n g
}
t r a i t B extends A {
o v e r r i d e d e f name : S t r i n g =" c l a s s b "
}
t r a i t C extends A {
o v e r r i d e d e f name : S t r i n g =" c l a s s c "
}
c l a s s D extends B w i t h C { }
v a r c l a s s _ d = new D
p r i n t l n ( c l a s s _ d . name )
B: B->A->AnyRef->Any
C: C->A->AnyRef->Any
C->B->A->AnyRef->Any
D: D->C->B->A->AnyRef->Any
Dr. Nguyen Hua Phung Object-Oriented Programming 27 / 46
Scala Hierarchy [8]

Dr. Nguyen Hua Phung Object-Oriented Programming 28 / 46


Access Modifiers [6] in Scala

protected
private
protected[<name>]
private[<name>]
Example,
package Assignment
...
protected [ Assignment ] v a l f i e l d 1 = 100
private [ t h i s ] val f i e l d 2 = 2;

Dr. Nguyen Hua Phung Object-Oriented Programming 29 / 46


OOP in Python

Class vs. Object


Instance vs. static fields
Instance, Class, Static methods
Encapsulation
Inheritance
Polymorphism

Dr. Nguyen Hua Phung Object-Oriented Programming 31 / 46


Class vs. Object

Class is a user-defined prototype for an object


class <Clsname > : => Clsname: name of the class
’ O p t i o n a l c l a s s documentation s t r i n g ’
< c l a s s _ s u i t e > => fields, methods
Object: an instance of the class
class Employee :
’Common base c l a s s f o r a l l employees ’
empCount = 0 => empCount: static field
def _ _ i n i t _ _ ( s e l f , n , s ) : =>constructor
s e l f . name = n =>name: instance field
self . salary = s =>salary: instance field
Employee . empCount += 1
o b j = Employee ( "Nam" , 3 0 ) => create object

Dr. Nguyen Hua Phung Object-Oriented Programming 32 / 46


Instance Methods

Instance Method: method belongs to the instance


class Employee :
def displayEmployee ( s e l f ) : => first param-
eter for instance
p r i n t ( "Name : " , s e l f . name ,
" , Salary : " , s e l f . salary )
o b j = Employee ( "Nam" , 3 0 )
o b j . displayEmployee ( ) =>obj is passed to self
able to access to instance fields through first
parameter and ’.’ => self.name
able to access to static field through class name and
’.’ => Employee.empCount

Dr. Nguyen Hua Phung Object-Oriented Programming 33 / 46


Class and Static Methods

class Employee :
@classmethod =>to define class method
def c r e a t e ( c l s , n , s ) : =>first parameter for class
p r i n t ( c l s . empCount ) =>access to static fields
return c l s ( n , s )
@staticmethod =>to define static method
def i s H i g h S a l ( s ) : =>no parameter for class
i f s > 8: =>unable to access any fields
p r i n t ( " High S a l a r y " )
o b j = Employee . c r e a t e ( "Nam" , 3 0 ) =>Employee is
passed to cls
Employee . i s H i g h S a l ( 3 0 ) =>Employee is used to re-
solve

Dr. Nguyen Hua Phung Object-Oriented Programming 34 / 46


Information Hiding

to hide fields and methods


based on name of fields and methods
Protected: prefix by a single underscore (_example)
Private: prefix by a double underscores (__example)
Public: begin with a letter

Dr. Nguyen Hua Phung Object-Oriented Programming 35 / 46


Class Hierarchy

Python 3: root is object


Multiple Inheritance
class <clsname >( < parent >( , < parent > ) ∗ ) ? :
For example,
class A : => superclass is object
class Rectangle ( P a r a l l e l o g r a m ) :
=> superclass is Parallelogram
class Square ( Rhombus , Rectangle ) :
=> superclasses are Rhombus and Rectangle

Dr. Nguyen Hua Phung Object-Oriented Programming 36 / 46


Inheritance

Subclass inherits non-private fields and methods


from super-classes
Diamond problem
A

B C

D
Method Resolution Order: determine search
sequence of a class

Dr. Nguyen Hua Phung Object-Oriented Programming 37 / 46


Method Resolution Order (MRO)

MRO is used to determine search sequence L(M) of


class M
L(object) = [object]
L(M(A,B,C)) = [M] + merge(L(A),L(B),L(C),[A,B,C])
merge([H1 |T1 ],[H2 |T2 ],[H3 |T3 ])
Step 1: if H1 is a good head which is NOT in the tail
of other lists, take H1 out as an output, remove H1 out
of all lists, back to Step 1.
Step 2: if H1 is not a good head, check if H2 is a good
head. If it is, apply Step1 for H2 . If it is not, check for
H3 and so on. If there is no good head, give an error.

Dr. Nguyen Hua Phung Object-Oriented Programming 38 / 46


Example

B(A) C(A)

D(B,C)

L(A) = [A,object]
L(B) = [B] + merge(L(A),[A]) = [B,A,object]
L(C) = [C] + merge(L(A),[A]) = [C,A,object]
L(D) = [D]+merge(L(B),L(C),[B,C]) = [D,B,C,A,object]
merge([B,A,o],[C,A,o],[B,C]) =>
B is a good head => [B]+merge([A,o],[C,A,o],[C])
A is NOT a good head, check C, and C is a good
head => [B,C] + merge([A,o],[A,o],[])
A is a good head => [B,C,A] + merge([o],[o],[])
o is a good head => [B,C,A,o]
Dr. Nguyen Hua Phung Object-Oriented Programming 39 / 46
super, isinstance, type

super() => refer to the superclass


1 class A :
2 def f o o ( s e l f , x ) :
3 print ( x )
4 class B ( A ) :
5 def f o o ( s e l f , x ) :
6 super ( ) . f o o ( x )
7 B ( ) . f o o ( 3 ) => 3
isinstance(o,T) => check if object o is of type T
class A : pass
class B ( A ) : pass
x = B()
isinstance(x,B) => Trueisinstance(x,A) => Truetype(x)
is B => Truetype(x) is A => False
type(o) => return the type of object o
Dr. Nguyen Hua Phung Object-Oriented Programming 40 / 46
Polymorphism

Overloading:
def f u n c ( param1 , param2 = 0 ) : pass
func ( 1 , 2 )
f u n c ( " asbc " )
Universal Polymorphism:
Parametric Polymorphism Subtyping Polymorphism
class A : class A :
def func1 ( s e l f ) : def func1 ( s e l f ) :
p r i n t ( "A" ) p r i n t ( "A" )
def func2(self): pass def func2(self): pass
class B : class B ( A ) :
def func1 ( s e l f ) : def func1 ( s e l f ) :
p r i n t ( "B" ) p r i n t ( "B" )
for x in [A ( ) , B ( ) ] : for x in [A ( ) , B ( ) ] :
x . func1 ( ) x . func1 ( )
x.func2() x.func2()
Dr. Nguyen Hua Phung Object-Oriented Programming 41 / 46
Some other issues

id(): address of the specified object


x,y,z = 3,3,4
id(x) => address of object 3 which x points to
id(y) => same above address => x, y -> same object
id(z) => z points to different object

is vs. ==
is: True just when they are same object
==: True even when they are different objects but their
attributes are equal

x,y = [1,2,3],[1,2,3]
x is y => False
id(x) == id(y) => False
x == y => True

Dr. Nguyen Hua Phung Object-Oriented Programming 42 / 46


Some other issues

Context manager by with statement


with <expression> as <variable>:
<stmt−list>
<expression> must return an object which has
__enter__ and __exit__ methods
The with statement is executed like:
<variable> = <expression>
<variable>.__enter__()
<stmt_list>
<variable>.__exit__()
__exit__ method is always executed before the
control goes out of the <stmt_list>
used for managing resources: file, database,...
with open(’abc.txt’,’r’) as f:
print(f.read())
f.closed => True
Dr. Nguyen Hua Phung Object-Oriented Programming 43 / 46
Summary

What are still in your mind?

Dr. Nguyen Hua Phung Object-Oriented Programming 44 / 46


References I

[1] Classes and Objects, http://www.artima.com/pins1ed/


classes-and-objects.html, 19 06 2014.

[2] Traits, http://www.artima.com/pins1ed/traits.html,


19 06 2014.
[3] Case Class and Pattern Matching, http://www.artima.com/
pins1ed/case-classes-and-pattern-matching.html,
19 06 2014.
[4] Abstract Members, http:
//www.artima.com/pins1ed/abstract-members.html,
19 06 2014.
[5] Compositions and Inheritance, http://www.artima.com/
pins1ed/composition-and-inheritance.html, 19 06
2014.
[6] Packages and Imports, http://www.artima.com/pins1ed/
packages-and-imports.html, 19 06 2014.

Dr. Nguyen Hua Phung Object-Oriented Programming 45 / 46


References II

[7] Functional Objects, http://www.artima.com/pins1ed/


functional-objects.html, 19 06 2014.

[8] Scala Hierarchy, http:


//www.artima.com/pins1ed/scalas-hierarchy.html,
19 06 2014.
[9] Learning Scala part seven -Traits, http://joelabrahamsson.
com/learning-scala-part-seven-traits/, 19 06 2014.

[10] Object-Oriented Programming in Python 3,


https://realpython.com/
python3-object-oriented-programming/, 01-10-2020.

[11] Python - Object-Oriented, https://realpython.com/


python3-object-oriented-programming/, 01-10-2020.

[12] The Python 2.3 Method Resolution Order, https:


//www.python.org/download/releases/2.3/mro/,
01-10-2020.

Dr. Nguyen Hua Phung Object-Oriented Programming 46 / 46

You might also like