Title: Introduction to Object Oriented Programming (OOP)
1Introduction to Object Oriented Programming (OOP)
Angel de Vicente PostDoc Software Support Ext.
387 angelv_at_iac.es
2Summary
- Paradigms of programming
- Introduction to OOP
- Examples of OOP with Python
3Paradigms of Programming
- Procedural (FORTRAN, Pascal, C, )
- Functional (LISP, )
- Logic (PROLOG, )
- Object-oriented (Smalltalk, )
- Visual (Visual Basic, )
4Procedural Programming
while ( programming art ) incr(
pleasure ) decr( bugs ) incr(
portability ) incr( maintainability )
incr( quality ) incr( salary )
// live happily ever after
5O-O Vs. Procedural
- Procedural paradigm
- Program defines data and then calls subprogram to
act on the data - Object paradigm
- Program creates objects that encapsulate the data
and procedures that operate on the data
6Some OO Languages
- Smalltalk -- a radical change in programming
languages - Eiffel -- a language with assertions
- C -- is much more than a better C
- Java -- the dial-tone of the Internet
- DLP -- introduces logic into object orientation
- But also
- Python, Perl, IDL,
7Benefits of OOP
- OO encapsulation inheritance
- Modularity -- autonomous entities, cooperation
through exchanges of messages - Deferred commitment -- the internal workings of
an object can be redefined without changing
other parts of the system - Reusability -- refining classes through
inheritance - Naturalness -- object-oriented analysis/design,
modeling - Maintainability
8What Is Object Oriented Programming?
- Identifying objects and assigning
responsibilities to these objects. - Objects communicate to other objects by sending
messages. - Messages are received by the methods of an object.
- An object is like a black box.
- The internal details are hidden.
9Object Terminology
- Objects -- packet containing data and procedures
- Class -- template for creating objects
- Instance -- an object that belongs to a class
- Methods -- deliver service
- Message -- request to execute a method
- Encapsulation -- information hiding by objects
- Inheritance -- allowing the reuse of class spec.S
class - Hierarchy -- tree structure inheritance
relations - Polymorphism -- to hide different
implementations - Aggregation -- to include classes as part of
other classes
10What Is an Object?
- Tangible things as a car, printer, ...
- Roles as employee, boss, ...
- Incidents as flight, overflow, ...
- Interactions as contract, sale, ...
- Specifications as colour, shape,
11Objects in the Real World
- Objects have attributes and interact with each
other by passing messages.
Can I order this sofa set
Alex 1 Robinson Rd 2,000
Lawrence 15 200
No problem. Its 199, sir.
12Objects Differentiate Each Other by Their
Attributes.
Can I have this dinning table
Can I order this sofa set
Alex 1 Robinson Rd 2,000
Julia 18 Nanyang Ave 1,000
13Similar Objects Can Be Grouped Into a Group
name address budget placeOrder
Customers
14Objects Can Be Categorized Into Different Groups
People in Furniture Shop
name employeeNo commission takeOrder
name address budget placeOrder
Customers
SalesPerson
15Objects and Classes
Interpretation in the real world
Representation in the model
An object represents anything in the real world
that can be distinctly identified.
Object
An object has a unique identity, a state, and
behaviors
A class represents a set of objects with similar
characteristics and behaviors. These objects are
called instance of the class
A class characterizes the structure of states
and behaviors that are shared by all its
instances.
Class
16Objects and Classes (2)
- Objects in programming
- alex, julia and lawrence are objects
- identity - object reference
- state - value of attributes
- behavior - definition of methods
- Customer and SalesPerson are classes
- Objects alex and julia are instances of class
Customer and object lawrence is an instance of
class SalesPerson - Objects interact through message passing
- Customer and SalesPerson classes are the
specialization of PeopleInFurnitureShop class
17The Two Parts of an Object
- Object Data Methods
- or to say the same differently
- An object has the responsibility to know and the
responsibility to do.
18Basic TerminologyBehaviour and Messages
- The most important aspect of an object is its
behaviour (the things it can do). A behaviour is
initiated by sending a message to the object
(usually by calling a method).
19Message Components
- The object to receive the message
- The method to execute
- Any other necessary information needed by the
method (parameters)
Object.method(parameters)
20Example The Person class
- includeltstringgt
- includeltiostreamgt
- class Person
- char name20
- int yearOfBirth
- public
- void displayDetails()
- cout ltlt name ltlt " born in "
- ltlt yearOfBirth ltlt endl
-
- //...
private data
public processes
21Basic Terminology
- Abstraction is the representation of the
essential features of an object. These are
encapsulated into an abstract data type. - Encapsulation is the practice of including in an
object everything it needs hidden from other
objects. The internal state is usually not
accessible by other objects.
22Encapsulation - Real Life
- Bank machine
- Hidden data
- account balance
- personal information
- Interface
- deposit, withdraw, transfer
- display account information
23Interaction Among Classes
- A program is composed of multiple classes
- Classes may contain references to other classes
within the set of attributes or behaviours - Start in an application class (main)
- construct one or more objects and call methods
associated with those objects
24Basic TerminologyInheritance
- Inheritance means that one class inherits the
characteristics of another class.This is also
called a is a relationship
A car is a vehicle
A dog is an animal
A teacher is a person
25Inheritance
- The inheriting class contains all the attributes
and behaviours of the class it inherited from
plus any attributes and behaviours it defines - The inheriting class can override the definition
of existing methods by providing its own
implementation - The code of the inheriting class consists only of
the changes and additions to the base class
26Inheritance Terminology
- Class one above
- Parent class, Super class
- Class one below
- Child class
- Class one or more above
- Ancestor class, Base class
- Class one or more below
- Descendent class
27Why Use Inheritance?
- Modular coding
- less code, easier to understand
- Code reuse
- dont break what is already working
- easier updates
- May not have access to modify the original source
code - Polymorphism
28Basic TerminologyPolymorphism
- Polymorphism means having many forms. It allows
different objects to respond to the same message
in different ways, the response specific to the
type of the object.
E.g. the message displayDetails() in our
furniture shop should give different results when
send to a Customer or a SalesPerson.
29Basic TerminologyAggregation
- Aggregation describes a has a relationship. One
object is a part of another object. - We distinguish between composite aggregation (the
composite owns the part) and shared aggregation
(the part is shared by more than one composite).
A car has wheels.
30Inheritance, polymorphism and aggregation
31The Two Steps of Object Oriented Programming
- Making Classes Creating, extending or reusing
abstract data types. - Making Objects interact Creating objects from
abstract data types and defining their
relationships.
32Python simplest OO program!
- !/usr/local/bin/python
- class House
- pass
- my_house House()
- my_house.number 40
- print "My house is", my_house.number
- angelv_at_guinda Python ./first.py
- My house is 40
33Class constructors
- ! /usr/local/bin/python
- class House
- def __init__(self, number, rooms, garden)
- self.number number
- self.rooms rooms
- self.garden garden
- my_house House(20, 1, 0)
- print "My house is number", my_house.number
- print "It has", my_house.rooms, "rooms"
- if my_house.garden
- garden_text "has"
- else
- garden_text "does not have"
- print "It", garden_text, "a garden"
-
angelv_at_guinda Python ./second.py My house is
number 20 It has 1 rooms It does not have a
garden angelv_at_guinda Python
34Example Atom class
- class atom
- def __init__(self,atno,x,y,z)
- self.atno atno
- self.position (x,y,z)
- def symbol(self) a class method
- return Atno_to_Symbolatno
- def __repr__(self) overloads printing
- return 'd 10.4f 10.4f 10.4f'
- (self.atno, self.position0,
- self.position1,self.position2)
- gtgtgt at atom(6,0.0,1.0,2.0)
- gtgtgt print at
- 6 0.0000 1.0000 2.0000
- gtgtgt at.symbol()
- 'C'
35Atom class
- Overloaded the default constructor
- Defined class variables (atno,position) that are
persistent and local to the atom object - Good way to manage shared memory
- instead of passing long lists of arguments,
encapsulate some of this data into an object, and
pass the object. - much cleaner programs result
- Overloaded the print operator
- We now want to use the atom class to build
molecules...
36Molecule Class
- class molecule
- def __init__(self,name'Generic')
- self.name name
- self.atomlist
- def addatom(self,atom)
- self.atomlist.append(atom)
- def __repr__(self)
- str 'This is a molecule named s\n'
self.name - str str'It has d atoms\n'
len(self.atomlist) - for atom in self.atomlist
- str str atom '\n'
- return str
37Using Molecule Class
- gtgtgt mol molecule('Water')
- gtgtgt at atom(8,0.,0.,0.)
- gtgtgt mol.addatom(at)
- gtgtgt mol.addatom(atom(1,0.,0.,1.))
- gtgtgt mol.addatom(atom(1,0.,1.,0.))
- gtgtgt print mol
- This is a molecule named Water
- It has 3 atoms
- 8 0.000 0.000 0.000
- 1 0.000 0.000 1.000
- 1 0.000 1.000 0.000
- Note that the print function calls the atoms
print function - Code reuse only have to type the code that
prints an atom once this means that if you
change the atom specification, you only have one
place to update.
38Public and Private Data
- Currently everything in atom/molecule is public,
thus we could do something really stupid like - gtgtgt at atom(6,0.,0.,0.)
- gtgtgt at.position 'Grape Jelly'
- that would break any function that used
at.poisition - We therefore need to protect the at.position and
provide accessors to this data - Encapsulation or Data Hiding
- accessors are "gettors" and "settors"
- Encapsulation is particularly important when
other people use your class
39Encapsulated Atom
- class atom
- def __init__(self,atno,x,y,z)
- self.atno atno
- self.__position (x,y,z) position is private
- def getposition(self)
- return self.__position
- def setposition(self,x,y,z)
- self.__position (x,y,z) typecheck first!
- def translate(self,x,y,z)
- x0,y0,z0 self.__position
- self.__position (x0x,y0y,z0z)
40Why Encapsulate?
- By defining a specific interface you can keep
other modules from doing anything incorrect to
your data - By limiting the functions you are going to
support, you leave yourself free to change the
internal data without messing up your users - Write to the Interface, not the Implementation
- Makes code more modular, since you can change
large parts of your classes without affecting
other parts of the program, so long as they only
use your public functions
41Specializing Inherited Methods
- class Super
- def method(self)
- print in Super.method
- def delegate(self)
- self.action()
- Simple inheritance
- class Inheritor(Super)
- pass
42Specializing Inherited Methods (2)
- class Super
- def method(self)
- print in Super.method
- def delegate(self)
- self.action()
- Replacing behaviour
- class Replacer(Super)
- def method(self)
- print in Replacer.method
43Specializing Inherited Methods (3)
- class Super
- def method(self)
- print in Super.method
- def delegate(self)
- self.action()
- Extending behaviour
- class Extender(Super)
- def method(self)
- print starting Extender.method
- Super.method(self)
- print ending Extender.method
44Specializing Inherited Methods (4)
- class Super
- def method(self)
- print in Super.method
- def delegate(self)
- self.action()
- Providing behaviour
- class Provider(Super)
- def action(self)
- print in Provider.action
45Specializing Inherited Methods (5)
- What we get
- python specialize.py
- Inheritor
- in Super.method
- Replacer
- in Replacer.method
- Extender
- starting Extender.method
- in Super.method
- ending Extender.method
- Provider
- in Provider.action
46Conclusions
- OOP is just another paradigm of programming
- Features of OOP encapsulation, abstraction,
aggregation and inheritance. - Benefits of OOP are modularity, reusability,
naturalness and maintainability. - Syntax and OOP concepts quite simple.
- Steps for OOP making classes, creating objects
and making them interact. - For beginners the most difficult part is the
classes hierarchy design.