Introduction to Object Oriented Programming (OOP)
Angel de VicentePostDoc Software Support
Ext. [email protected]
Summary
• Paradigms of programming
• Introduction to OOP
• Examples of OOP with Python
Paradigms of Programming
• Procedural (FORTRAN, Pascal, C, …)
• Functional (LISP, …)
• Logic (PROLOG, …)
• Object-oriented (Smalltalk, …)
• Visual (Visual Basic, …)
•…
Procedural Programming
while ( programming == art ) { incr( pleasure ); decr( bugs ); incr( portability ); incr( maintainability ); incr( quality ); incr( salary ); } // live happily ever after
O-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
• 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, …
Some OO Languages
Benefits 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
What Is Object Oriented Programming?
An object is like a black box.
The internal details are hidden.
• 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.
Object 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
What 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, …
Objects in the Real World
• Objects have attributes and interact with each other by passing messages.
Alex1 Robinson Rd
$2,000Lawrence15$200
Can I order this sofa
set
No problem.It’s $199, sir.
Objects Differentiate Each Other by Their Attributes.
Alex1 Robinson Rd
$2,000
Can I order this sofa
set
Can I have this dinning
tableJulia18 Nanyang Ave$1,000
Similar Objects Can Be Grouped Into a Group
nameaddressbudget
placeOrder
Customers
Objects Can Be Categorized Into Different Groups
nameaddressbudget
placeOrder
nameemployeeNocommission
takeOrder
Customers SalesPerson
People in Furniture Shop
Objects and Classes
Interpretation in the real world
Representation in the model
Object
Class
An object represents anything in the real world that can be distinctly identified.
An object has a unique identity, a state, and behaviors
A class represents a set ofobjects 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.
Objects 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
Object = Data + Methods or to say the same differently:
An object has the responsibility to know and the responsibility to do.
= +
The Two Parts of an Object
Basic Terminology:Behaviour 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).
Message Components
• The object to receive the message• The method to execute
• Any other necessary information needed by the method (parameters)
Telephone.call(2416881)
Object.method(parameters)
Example: The Person class#include<string>#include<iostream>class Person{ char name[20]; int yearOfBirth;public: void displayDetails() { cout << name << " born in " << yearOfBirth << endl; } //...};
private data
public processes
Basic 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.
Encapsulation - Real Life
• Bank machine
• Hidden data– account balance– personal information
• Interface– deposit, withdraw, transfer– display account information
Interaction 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
Basic Terminology:Inheritance
• 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 teacher is a person
A dog is an animal
Inheritance• 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
Inheritance 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
Why Use Inheritance?• Modular coding
– less code, easier to understand
• Code reuse– don’t break what is already working– easier updates
• May not have access to modify the original source code
• Polymorphism
Basic Terminology:Polymorphism
• 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.
Basic Terminology:Aggregation
• 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.
Inheritance, polymorphism and aggregation
BankAccount
int acctNumClient acctHolderdouble balanceBankAccount(Client info)void deposit(double amt)boolean withdraw(double amt)void printStatement()
SavingsAccount
double interestRatedouble accruedInterestTime lastBalanceChangeSavingsAccount(...)void updateIntRate(double rate)void deposit(double amt)boolean withdraw(double amt)
ChequingAccount
double minBalance
ChequingAccount(…)boolean withdraw(double amt)double calcServiceFee()
The 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.
Python 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@guinda Python]$ ./first.pyMy house is 40
Class constructors#! /usr/local/bin/pythonclass House:
def __init__(self, number, rooms, garden):self.number = numberself.rooms = roomsself.garden = garden
my_house = House(20, 1, 0)
print "My house is number", my_house.numberprint "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@guinda Python]$ ./second.py My house is number 20It has 1 roomsIt does not have a garden[angelv@guinda Python]$
Example: Atom classclass atom:
def __init__(self,atno,x,y,z):self.atno = atnoself.position = (x,y,z)
def symbol(self): # a class methodreturn Atno_to_Symbol[atno]
def __repr__(self): # overloads printingreturn '%d %10.4f %10.4f %10.4f' %
(self.atno, self.position[0], self.position[1],self.position[2])
>>> at = atom(6,0.0,1.0,2.0)>>> print at6 0.0000 1.0000 2.0000>>> at.symbol()'C'
Atom 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...
Molecule 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
Using Molecule Class
>>> mol = molecule('Water')>>> at = atom(8,0.,0.,0.)>>> mol.addatom(at)>>> mol.addatom(atom(1,0.,0.,1.))>>> mol.addatom(atom(1,0.,1.,0.))>>> print molThis is a molecule named WaterIt has 3 atoms8 0.000 0.000 0.0001 0.000 0.000 1.0001 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.
Public and Private Data
• Currently everything in atom/molecule is public, thus we could do something really stupid like
• >>> at = atom(6,0.,0.,0.)• >>> 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
Encapsulated 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 = (x0+x,y0+y,z0+z)
Why 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
Specializing Inherited Methods
class Super:
def method(self):
print ‘in Super.method’
def delegate(self):
self.action()
• Simple inheritance
class Inheritor(Super):
pass
Specializing 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’
Specializing Inherited Methods (3)
class Super:
def method(self):
print ‘in Super.method’
def delegate(self):
self.action()
• Extending behaviourclass Extender(Super):
def method(self):
print ‘starting Extender.method’
Super.method(self)
print ‘ending Extender.method’
Specializing 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’
Specializing Inherited Methods (5)
• What we get…% python specialize.pyInheritor…in Super.method
Replacer…in Replacer.method
Extender…starting Extender.methodin Super.methodending Extender.method
Provider…in Provider.action
Conclusions
• 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.