Вы находитесь на странице: 1из 52

CS504D

Object Oriented Programming:


Origins and Importance

- Adapted by UD
Evolution of Programming Languages
• Programming has progressed through:
– machine code (Category 1: Code
– assembly language acting on data)
– machine-independent programming languages
(keywords, operators, punctuation)
Programming

– procedures & functions


Efficiency

– Object oriented (Category 2:


data controlling access to code
– Declare data and then routines permitted to act on data
– Closer to real world)

Note: Shovel vs. Tractor

2
Machine language – Mark I

3
Machine Language

0000 1001 1100 0110 1010 1111 0101 1000


1010 1111 0101 1000 0000 1001 1100 0110
1100 0110 1010 1111 0101 1000 0000 1001
0101 1000 0000 1001 1100 0110 1010 1111

4
Assembly Language – PDP-11

5
Assembly Language – Macro-11
GCD: TST B
BEQ SIMPLE
MOV A, R5
SXT R4
DIV B, R4
MOV B, A
MOV R5, B
CALL GCD
SIMPLE: RETURN
6
Assembly Language – Macro-11
GCD: TST B
BEQ SIMPLE
MOV A, R5
SXT R4
DIV B, R4
MOV B, A
MOV R5, B
CALL GCD
SIMPLE: RETURN
7
Machine-Independent Programming
Languages – Fortran
! This example program solves for roots of the quadratic equation,
! ax^2 +bx +c =0,for given values of a, b and c.
!
PROGRAM bisection
IMPLICIT NONE
INTEGER :: iteration
DOUBLE PRECISION :: CC, Er, xl, x0, x0_old, xr

! Set convergence criterion and guess for xl, xr.


CC = 1.d-4
xl = 8.d-1
xr = 11.d-1

! Bisection method.
Er =CC +1
iteration = 0
DO WHILE (Er > CC)
iteration = iteration + 1

! Compute x0 and the error.


x0_old = x0
x0 = (xl + xr) / 2.d0
Er = DABS((x0 - x0_old)/x0)*100.d0
WRITE (*,10) iteration, x0_old, x0, Er
10 FORMAT (1X,I4,3(2X,E10.4)) this is partial…

8
Procedures & Functions – Pascal
program ValueArg(output);
{Shows how to arrange for a procedure to have arguments.}

procedure PrintInitials(First, Last : char);


{Within this procedure, the names First and Last represent the
argument values. We’ll call write to print them.}
begin
write(‘My initials are: ’);
write(First);
writeln(Last)
end; {PrintInitials}

begin
PrintInitials (‘D’, ‘C’); {Any two characters can be arguments.}
PrintInitials (‘Q’, ‘T’); {Like strings, characters are quoted.}
PrintInitials (‘&’, ‘#’)
end. {ValueArg}

9
Objects
• (example from Java)
class Time {

private int hour, minute;

public Time (int h, int m) {


hour = h;
minute = m;
}

public void addMinutes (int m) {


int totalMinutes =
((60*hour) + minute + m) % (24*60);
if (totalMinutes<0)
totalMinutes = totalMinutes + (24*60);
hour = totalMinutes / 60;
minute = totalMinutes % 60;
}
}
this is partial…
10
Objects
class

Time
inTime
hour Attributes:
hour = 8
minute minute = 30
Methods:
void addMinutes(int m)
void addMinutes( int m )
outTime
Attributes:
hour = 17
minute = 35
Methods: objects
void addMinutes(int m)

11
Classes and Objects
• A class is a prototype for creating
objects
• In object-oriented programming, we
define classes and classes are used to
create objects
• A class has a constructor for creating
objects

12
A Simple Class, called “Time”
class Time {

private int hour, minute; constructor for Time


public Time (int h, int m) {
hour = h;
minute = m;
}

public void addMinutes (int m) {


int totalMinutes =
((60*hour) + minute + m) % (24*60);
if (totalMinutes<0)
totalMinutes = totalMinutes + (24*60);
hour = totalMinutes / 60;
minute = totalMinutes % 60;
}
}

13
C Example: Represent a Time
struct TimeTYPE {
short Hour;
short Minute;
}
struct TimeTYPE inToWork, outFromWork;
::
inToWork.Hour = 9;
inToWork.Minute = 30;

outFromWork.Hour = 19;
outFromWork.Minute = 35;

14
Java Example: Represent a Time
class Time { attributes of Time

private int hour, minute;

public Time (int h, int m) {


hour = h;
minute = m;
}

} constructor for Time

Time inToWork = new Time(9, 30);


Time outFromWork = new Time(19, 35);
15
Objects
class

Time
inToWork
hour Variables:
minute hour = 8
minute = 30
Methods:
void addMinutes( int m ) void addMinutes(int m)

outFromWork
Variables:
hour = 17
minute = 35
Methods: objects
void addMinutes(int m)

16
Structure of a Class Definition
class name {
variables and
declarations symbolic constants

how to create and


constructor definition(s) initialize objects

method definitions how to manipulate


the state of objects
} These parts of a class can
actually be in any order

17
History of Object-Oriented Programming
• SIMULA I (1962-65) and Simula 67 (1967) were
the first two object-oriented languages
– Developed at the Norwegian Computing Center,
Oslo, Norway by Ole-Johan Dahl and Kristen
Nygaard
– Simula 67 introduced most of the key concepts of
object-oriented programming: objects and classes,
subclasses (“inheritance”), virtual procedures

18
The Ideas Spread
• Alan Kay, Adele Goldberg and colleagues at
Xerox PARC extend the ideas of Simula in
developing Smalltalk (1970’s)
– Kay coins the term “object oriented”
– Smalltalk is first fully object oriented language
– Grasps that this is a new programming paradigm
– Integration of graphical user interfaces and
interactive program execution
• Bjarne Stroustrup develops C++ (1980’s)
– Brings object oriented concepts into the C
programming language

19
Other Object Oriented Languages
• Eiffel (B. Meyer)
• CLOS (D. Bobrow, G. Kiczales)
• SELF (D. Ungar et al.)
• Java (J. Gosling et al. at Sun Microsystems’1991;
initially this language was called Oak and renamed as
Java in ‘1995)
• BETA (B. Bruun-Kristensen, O. Lehrmann Madsen,
B. Møller-Pedersen, K. Nygaard)
• Other languages add object dialects, such as
TurboPascal
• …

20
Principles of OOP
• Encapsulation
• Polymorphism
• Inheritance

21
Encapsulation
• Mechanism for binding together code and data and
providing controlled access (safe from outside
interference and misuse)
• Code, data or both may be declared as private or public
• private code or data accessible only by another part of
the object and not outside; public can be accessed also
outside that object
• Java’s basic unit of encapsulation is class; defines the
form or prototype of object
• Different groups of programmers can work on different
parts of the project
22
Advantages of Encapsulation
Building the system as a group of interacting
objects:
• Allows extreme modularity between pieces
of the system
• May better match the way we (humans)
think about the problem
• Avoids recoding, increases code-reuse

23
Inheritance
• Process by which one object can acquire properties of
another object
• Classes can be arranged in a hierarchy
• Subclasses inherit attributes and methods from their
parent classes
• This allows us to organize classes, and to avoid rewriting
code – new classes extend old classes, with little extra
work!
• Allows for large, structured definitions

24
Example of Class Inheritance
Object

toString( )
equals( Object obj )
getClass( )
Objects made from this
class, for example, have extends extends
all the attributes and Shape Time
methods of the classes color hour
above them, all the way borderWidth minute
up the tree Color getColor( )
void setBorderWidth( int m ) void addMinutes( int m )

extends extends extends


Rectangle Circle Triangle
length radius base
width height
int computeArea( ) int computeArea( ) int computeArea( )

25
Polymorphism
• An object has “multiple identities”, based on
its class inheritance tree
• It can be used in different ways, e.g.

26
Polymorphism
• An object has “multiple identities”, based on
its class inheritance tree
• It can be used in different ways
• A Circle is-a Shape is-a Object
Object

toString( )
equals( Object obj )
getClass( )

extends
Shape
color
borderWidth
Color getColor( )
void setBorderWidth( int m )

extends
Circle
radius

int computeArea( )
27
Polymorphism
• An object has “multiple identities”, based on
its class inheritance tree
• It can be used in different ways
• A Circle is-a Shape is-a Object
Object

toString( ) Object
equals( Object obj )
getClass( )

extends Shape
Shape
color
borderWidth
Color getColor( )
void setBorderWidth( int m )
Circle
extends
Circle A Circle object really has 3 parts
radius

int computeArea( )
28
How Objects are Created
Circle c = new Circle( );

1. 2. 3.
Object Object Object

Shape Shape Shape

c Circle c Circle c Circle

Execution Time

29
Three Common Uses for Polymorphism
1. Using Polymorphism in Arrays
2. Using Polymorphism for Method
Arguments
3. Using Polymorphism for Method
Return Type

30
1) Using Polymorphism in Arrays
• We can declare an array to be filled with “Shape”
objects, then put in Rectangles, Circles, or
Triangles Object

toString( )
equals( Object obj )
getClass( )

extends
Shape
color
borderWidth
Color getColor( )
void setBorderWidth( int m )

extends extends extends


Rectangle Circle Triangle
length radius base
width height
int computeArea( ) int computeArea( ) int computeArea( )

31
1) Using Polymorphism in Arrays
• We can declare an array to be filled with “Shape”
objects, then put in Rectangles, Circles, or
Triangles

firstShape secondShape thirdShape


Attributes: Attributes: Attributes:
[2]= 17
length radius = 11 base = 15
samples width = 35 height = 7
(an array Methods: Methods: Methods:
int computeArea( ) int computeArea( ) int computeArea( )
of Shape
objects)

[0] [1] [2]

32
2) Using Polymorphism for Method
Arguments
• We can create a procedure that has Shape as
the type of its argument, then use it for objects
of type Rectangle, Circle, and Triangle

public int calculatePaint (Shape myFigure) {


final int PRICE = 5;

int totalCost = PRICE * myFigure.computeArea( );


return totalCost;
}

Actual definition of computeArea( ) is known only at


runtime, not compile time – this is “dynamic binding” 33
OOP: Major & Minor Elements
• Major Elements
(i) Abstraction, (ii) Encapsulation, (iii) Modularity,
(iv) Hierarchy
– Not OOP if any of these major elements are absent

• Minor elements
(i) Typing, (ii) Concurrency, (iii) Persistence
– Useful but not indispensable for OOP

34
Abstraction
• Denotes the essential characteristics of an object
that distinguish it from all other objects
While designing class Student, following attributes
typically included:
• roll_number
• Name
• course
• address…
…while following characteristics are eliminated:
• pulse_rate
• colour_of_hair..

35
Encapsulation & Modularity
• Discussed over previous slides.
• Questions?

36
Hierarchy
• Ranking or ordering of abstraction
• Using this, a system can be made up of interrelated subsystems
and levels of subsystems until the smallest level components
• Uses “Divide and conquer” principle
• Types: IS-A and PART-OF

If we derive a class Rose from a class Flower, we can say


that a rose “is–a” flower.
A flower is composed of sepals, petals, stamens, and
carpel. It can be said that a petal is a “part–of” flower.

37
Typing
• Characterization of a set of elements, e.g. a class is a type
having properties distinct from any other type

• Categories:
– Strong Typing: Object’ operation checked at the time of
compilation, e.g. Eiffel

– Weak Typing: Object’ operation checked at the time of


execution, e.g. Smalltalk, Java

38
Concurrency
• Concurrency (in operating systems) allows performing
multiple tasks or processes simultaneously:

– Single thread of control: When a single process exists in the


system

– Multi thread: Most systems with multiple threads - some


active, some waiting for CPU, some suspended and some
terminated. Available on multi-CPU or even on single-CPU

39
Persistence
• An object occupies a memory space and exists for a particular
period of time
• Lifespan of an object is typically the lifespan of the execution of
creator program
• In files or databases, the object lifespan is longer than the
duration of the creator process.
• Thru persistence, an object continues to exist even after its
creator ceases to exist

40
Links and Association
• Link: Connection thru which an object collaborates with other
objects, i.e. one object may invoke methods in another object
– Depicts relationship between 2 or more objects

• Association: Group of links having common structure and


common behavior.
– Depicts relationship between one or more classes
– Link defined as an instance of an association

e.g., Student and Faculty having association

41
Degree & Cardinality
• Degree of Association
– Unary (connects objects of same class)
– Binary or Ternary

• Cardinality of Binary Association


– One-to-one
• A single object of class A is associated with a single object of
class B, e.g. Employee and Project
– One-to-many, e.g. College and Student
– Many-to-many, e.g. Faculty and Subject

42
Aggregation
• Relationship among classes by which a class can be made with any
combination of objects of other classes.

• Allows objects to be placed directly within the body of other classes


• Referred as a “part–of” or “has–a” relationship, with the ability to navigate
from the whole to its parts.

• An aggregate object is an object composed of one or more other objects

• Composition: Aggregation in restricted form, e.g.


• Library and Students: having aggregation relationship
• Libray and Books: having composition relationship

43
Aggregation (contd.) & Meta-class
• In the relationship “a flower has–a petal”, flower is the whole
object or the aggregate and petal is a “part–of” the flower
• Aggregation may denote:
– Physical containment : e.g., a computer is composed of
monitor, CPU, mouse, keyboard etc.
– Conceptual containment : e.g., shareholder has–a share

Meta-class: Class of a class, i.e. class whose instances are classes,


e.g. directly supported in Small talk, Python etc.

44
POP vs. OOP

POP

45
POP vs. OOP (contd.)
# Category Procedure Oriented Object Oriented
Programming Programming
1. Priority Importance given to the sequence Importance given to the data
of functions to be done i.e.
algorithms
2. Program Larger programs divided into Larger programs divided into
Division functions objects
3. Data Most functions share global data Mostly the data is private and
Sharing i.e. data move freely around the only functions inside the
system from function to function. object can access the data.
4. Approach Follows a top down approach in Follows a bottom up
problem solving approach
5. Code Adding of data and function is Adding of data and function is
Extensibility difficult, as full program may need easier, and full program is not
to be changed required to be changed
6. Access There is no access specifier There is public, private and
Specifiers protected specifiers
46
POP vs. OOP (contd.)
# Category POP OOP
7. Communicat Procedure / function connect Objects communicate via message
ion across with each other by parameter passing
modules passing
8. Content of Every function contains Data & associated functions of
module different data each individual object act like a
single unit
9. Focus Functions with sequence get Data gets more importance than
more importance than data functions
10 Data hiding There is no perfect way for Data hiding possible which
data hiding prevent illegal access of functions
from outside
11 Overloading Operator cannot be Can be overloaded in OOP
overloaded. languages like C++ (not possible in
Java)
12 Security Less in the absence of data More as prevention of illegal
hiding. access is possible
13 Example Pascal, FORTRAN, C C++, Java, Small talk, Python etc.
47
Advantages of OOP
• Improved software-development productivity  extreme
modularity, easy extensibility & reusability of objects
• Improved software maintainability  part of the system can be
changed w/o affecting large-scale
• Faster development  Reusability of code & rich libraries of
objects
• Lower cost of development  Reuse of software (more effort
into OOAD)
• Higher-quality software  Above 2 points allow more time &
resources in the V&V

48
Disadvantages of OOP
• Steep learning curve: Complex to create programs based on
objects’ interaction. Initial challenges in conceptualizing
Inheritance & Polymorphism..
• Larger program size: Typically more lines of code..
• Slower programs: Typically slower as they typically require more
instructions to be executed
• Not suitable for all types of problems: Some problems can be
solved more efficiently with functional-programming style, logic-
programming style, or procedure-based programming style..

49
Why Java for OOP?
• Java is Object-Oriented (syntax inherited from C and object
model adapted from C++)
• Designed with lessons learnt and best experiences from
other OO languages used for many years
• Java has strong type checking
• Java handles its own memory allocation
• Java’s syntax is “standard” (similar to C and C++)
• More…
– Portability and Security via Java Bytecode
– Contribution to internet via Java Applets (server program
dynamically downloaded over the Web and run locally in client
browser)

50
Object-Oriented Programming in Industry

• Large projects are routinely programmed


using object-oriented languages..

• MS-Windows and applications in MS-


Office – all developed using object-
oriented languages

51
Conclusions
• OOP provides a superior way of organizing
programming projects:
– Encourages a high degree of modularity in programming,
making large projects easier to implement
– Provides powerful techniques like inheritance and
polymorphism to help organize and reuse code

• OOP matches real-world developments in computer


programming

52

Вам также может понравиться