Sunteți pe pagina 1din 18

JOMO KENYATTA UNIVERSITY

OF
AGRICULTURE AND TECHNOLOGY
INSTITUTE OF COMPUTER SCIENCE AND INFORMATION TECHNOLOGY

P.O. BOX 62000 - 00200 NAIROBI

MSC COMPUTER SCIENCE

OBJECT ORIENTED PROGRAMMING PRINCIPLES

KAARIA FRANCIS MURIUNGI

Contents
Abstract ......................................................................................................................................................... 3
Definitions of Fundamental Principles of OOP ............................................................................................. 3
Objectives of the Topic ................................................................................................................................. 3
A Brief History of Object-Oriented Programming ......................................................................................... 4
Discussing the OOP Principles ....................................................................................................................... 4
Inheritance................................................................................................................................................ 4
Abstraction ............................................................................................................................................... 8
Encapsulation ......................................................................................................................................... 11
Polymorphism ........................................................................................................................................ 13
CONCLUSION ............................................................................................................................................... 18
REFERENCES ................................................................................................................................................ 18

Abstract
Object-oriented programming (OOP) is a programming paradigm that represents concepts as
"objects" that have data fields (attributes that describe the object) and associated procedures known
as methods. Objects, which are usually instances of classes, are used to interact with one another
to design applications and computer programs.[1][2] C++, Objective-C, Smalltalk, Java, C#, Perl,
Python, Ruby and PHP are examples of object-oriented programming languages. Object-oriented
programming is a practical and useful programming methodology that encourages modular design
and software reuse. There are four fundamental OOP principles namely: Inheritance, Abstraction,
encapsulation and polymorphism. This paper discusses each of them in details.

Definitions of Fundamental Principles of OOP

Inheritance - Inherit members from parent class. The process by which objects of one class
acquired the properties of objects of another classes. It supports the concept of hierarchical
classification.
Abstraction - The process of hiding the details and exposing only the essential features of
a particular concept or object without including the background details or explanation.
Encapsulation - Hide the internals of a class. Objects expose functionality only through
methods, properties, and events, and hide the internal details such as state and variables
from other objects. This makes it easier to update or replace objects, as long as their
interfaces are compatible, without affecting other objects and code.
Polymorphism- A Greek term, means the ability to take more than one form. An operation
may exhibit different behavior in different instances. The behavior depends upon the types
of data used in the operation.

Objectives of the Topic


(i)

Describe the principles of the OOP principles

(ii)

Describe the application of the principles.

(iii)

Highlight the benefits of each principle in OOP.

A Brief History of Object-Oriented Programming


SIMULA was the first object language. As its name suggests it was used to create simulations.
Alan Kay, who was at the University of Utah at the time, liked what he saw in the SIMULA
language. He had a vision of a personal computer that would provide graphics-oriented
applications and he felt that a language like SIMULA would provide a good way for nonspecialists to create these applications. He sold his vision to Xerox Parc and in the early 1970s, a
team headed by Alan Kay at Xerox Parc created the first personal computer called the Dynabook.
Smalltalk was the object-oriented language developed for programming the Dynabook. It was a
simulation and graphics-oriented programming language. Smalltalk exists to this day although it
is not widely used commercially.
The idea of object-oriented programming gained momentum in the 1970s and in the early 1980s
Bjorn Stroustrup integrated object-oriented programming into the C language. The resulting
language was called C++ and it became the first object-oriented language to be widely used
commercially.
In the early 1990s a group at Sun led by James Gosling developed a simpler version of C++ called
Java that was meant to be a programming language for video-on-demand applications. This project
was going nowhere until the group re-oriented its focus and marketed Java as a language for
programming Internet applications. The language has gained widespread popularity as the Internet
has boomed, although its market penetration has been limited by its inefficiency.

Discussing the OOP Principles


Inheritance
In object-oriented programming, Inheritance means the inheritance of another object's interface,
and possibly its implementation as well. Inheritance is accomplished by stating that a new class is
a subclass of an existing class. The class that is inherited from is called the superclass. The subclass
always inherits the superclass's complete interface. It can extend the interface but it cannot delete
any operations from the interface. The subclass also inherits the superclass's implementation, or in
other words, the functions that implement the superclass's operations. However, the subclass is
free to define new functions for these operations. This is called overriding the superclass's

implementation. The subclass can selectively pick and choose which functions it overrides. Any
functions that are not overridden are inherited.
There is a great deal of debate about how to use inheritance. In particular, the debate swirls about
whether inheritance should be used when you want to inherit an interface or whether it should be
used when you want to inherit implementation. For example, suppose that you want to define a
search object that stores (key, value) pairs and allows values to be looked up by providing their
keys. More precisely, let us say that the search object supports the following operations:

insert: Adds a (key, value) pair to the object.


delete: Deletes a (key, value) pair from the object.
lookup: Given a key retrieves the value associated with that key from the object.

Later we decide that we want a new object that allows us to traverse the (key, value) pairs in sorted
order. The new object should support the above operations plus two additional operations, rewind
that puts us back to the beginning, and next that returns the next (key, value) pair. Since the new
object supports all of the operations of the original search object, we can make the new object
inherit the original object's interface. This is an example of interface inheritance.
Example/ Analogy
To motivate inheritance, think of a radio alarm clock. A radio alarm clock has all of the functions
of a radio plus additional functions to handle the alarm clock. If we adopt the radio's interface for
the radio alarm clock, then someone who knows how to operate a radio will also know how to
operate the radio portion of the radio alarm clock. Hence, rather than designing the radio alarm
clock from scratch, we can extend or inherit the interface defined by the radio. Of course, we can
also use the existing implementation for a radio and extend it to handle the alarm clock functions.
Benefits of Inheritance

A programmer can tailor a derived class as needed by adding new variables or methods,
or by modifying the inherited ones.
Software reuse is a fundamental benefit of inheritance

By using existing software components to create new ones, we capitalize on all the effort
that went into the design, implementation, and testing of the existing software
Inheritance allows child classes to inherit the characteristics of existing parent class
o Attributes (fields and properties)

o Operations (methods)
Child class can extend the parent class
o Add new fields and methods

o Redefine methods (modify existing behavior)


A class can implement an interface by providing implementation for all its methods.
Therefore Inheritance enhances Extensibility, Reusability, Provides abstraction and
Eliminates redundant code.

Important Aspects of Inheritance

Structures cannot be inherited


In C# there is no multiple inheritance , Only multiple interfaces can be implemented
Instance and static constructors are not inherited
Inheritance is transitive relation
If C is derived from B, and B is derived from A, then C inherits A as well
A derived class extends its base class, It can add new members but cannot remove
derived ones
Declaring new members with the same name or signature hides the inherited ones
A class can declare virtual methods and properties
Derived classes can override the implementation of these members
Using inheritance we can create inheritance hierarchies, Easily represented by UML class
diagrams
In UML class diagrams Classes are represented by rectangles containing their methods
and data
Relations between classes are shown as arrows
Closed triangle arrow means inheritance
Other arrows mean some kind of associations

interface
ISurfaceCalculatable

struct
Point

Shape
#Position:Point

+CalculateSurface:float

+X:int
+Y:int
+Point

Square
-Size:float
+Square
+CalculateSurface:float

-Width:float
-Height:float
+Rectangle
+CalculateSurface:float

FilledSquare

FilledRectangle

-Color:Color

-Color:Color

+FilledSquare

+FilledRectangle

UML Class Diagram Example

struct
Color

Rectangle

+RedValue:byte
+GreenValue:byte
+BlueValue:byte
+Color

Abstraction
Abstraction is the process of hiding the details and exposing only the essential features of a
particular concept or object without including the background details or explanation. Classes use
the concept of abstraction and are defined as a list of abstract attributes such as size, wait, and cost,
and function operate on these attributes.
Eg:-When we change the gear of a car, we know the gears will be changed without knowing how
they are functioning internally.
Abstraction focuses on the outside view of an object (i.e. the interface).
The attributes are sometimes called data members because they hold information. The functions
that operate on these data are sometimes called methods or member function.
Computer scientists use abstraction to understand and solve problems and communicate their
solutions with the computer in some particular computer language. This allows you to reduce a
complex operation into a generalization that retains the base characteristics of the operation. For
example, an abstract interface can be a well-known definition that supports data access operations
using simple methods such as Get and Update. Another form of abstraction could be metadata used
to provide a mapping between two formats that hold structured data.
Abstraction is something we do every day e.g Looking at an object, we see those things about it
that have meaning to us.
We abstract the properties of the object, and keep only what we need
E.g. students get "name" but not "color of eyes"
Abstraction allows us to represent a complex reality in terms of a simplified model
Abstraction highlights the properties of an entity that we need and hides the others

Abstract Data Types


Abstract Data Types (ADT) are data types defined by a set of operations (interface)
This abstract approach to define and use new types constitutes an excellent way to deal with
complexity: we reduce it by separating the services offered by the type (what) from the type
implementation (how). The implementation issues are deferred to a later time or are provided by
somebody else (e.g., the authors of a library of types). As a result, we only have to focus on one
aspect at a time. This issue is usually referred to as separation of concerns.
Since we define these new high-level types from an abstract point of view, they may be called
abstract types. An abstract type denotes a set of entities characterized by a list of operations that
may be applied to them together with a precise specification of each one of these operations.
Usually, the list of operations that define a type and their specification are referred to as the type
behaviour, type specification or the type contract. An abstract type is also called interface.

The set of entities which share the operations defined for a type are called instances of that type.
An example of abstract type may be the type Student. This is an abstract type whose instances are
each one of the specific students (Joe, Ann ...) and its operations can be:

set the name of a student, enroll a student in a subject,


get the list of subjects in which a specific student has enrolled, etc.

Usually, we will refer to abstract types just as types.


This approach is coincident to what we do in everyday life to manage complexity. For instance,
cars are very complicated machines. However, the only thing that a car driver needs to care about
is that when he/she presses the accelerator the car speeds up; he/she does not care about the
background mechanics and electronics that make this action possible. In fact, it would be very
difficult, if not impossible, to drive having in mind, at the same time, the functionality expected
from the car (the what: speed up, change direction, brake, etc.) and the way in which this
functionality is internally achieved (the how: in which precise manner fuel is mixed with air and
gets to the engine; which mechanical elements are involved in the transmission of the energy
produced by the engine to the wheels, etc.).

Example:

interface
IList<T>
+Add(item : Object)
+Remove(item : Object)
+Clear()

LinkedList<T>

List<T>

BENEFITS OF ABSTRACTION
Computer scientists use abstraction to understand and solve problems and communicate
their solutions with the computer in some particular computer language.
This allows you to reduce a complex operation into a generalization that retains the base
characteristics of the operation. For example, an abstract interface can be a well-known
definition that supports data access operations using simple methods such as Get and
Update.

Encapsulation
Objects expose functionality only through methods, properties, and events, and hide the internal
details such as state and variables from other objects. This makes it easier to update or replace
objects, as long as their interfaces are compatible, without affecting other objects and code.
This is wrapping up of data and functions into a single unit (called class). Data encapsulation is
the most striking feature of a class. The data is not accessible to the outside world, and only those
functions which are wrapped in the class can access it. These functions provide the interface
between the objects data and the program. This insulation of the data from direct access by the
program is called data hiding or information hiding.
Therefore encapsulation means putting the data and the function that operates on that data in a
single unit (information hiding) .Encapsulation prevents clients from seeing its inside view, where
the behavior of the abstraction is implemented. It is the mechanism that binds together code and
the data it manipulates, and keeps both safe from outside interference and misuse.in java
encapsulation is achieved by making use of access modifiers (keeping variables as private and
providing public getters and setters.

Eg:-automatic transmission of an automobile. It encapsulates lots of information about the engine,


such acceleration, the pitch of the surface, and the position of the shift lever. Being a user, we have
only one method of affecting this complex encapsulation: moving the gear-shift lever.
Encapsulation hides the implementation details

Class announces some operations (methods) available for its clients its public interface
All data members (fields) of a class should be hidden

Accessed via properties (read-only and read-write)

No interface members should be hidden


Data fields are private

Constructors and accessors are defined (getters and setters)

Example of encapsulation

Person
-name : string
-age : TimeSpan
+Person(string name, int age)
+Name : string { get; set; }
+Age : TimeSpan { get; set; }
Benefits of Encasulation

Ensures that structural changes remain local:


Changing the class internals does not affect any code outside of the class
Changing methods' implementation
does not reflect the clients using them

Encapsulation allows adding some logic when accessing client's data


E.g. validation on modifying a property value

Hiding implementation details reduces complexity easier maintenance

Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to
take more than one form. An operation may exhibit different behavior in different instances. The
behavior depends upon the types of data used in the operation. For example, consider the operation of
addition. For two numbers, the operation will generate a sum. If the operands are strings, then the
operation would produce a third string by concatenation. The process of making an operator to exhibit
different behaviors in different instances is known as operator overloading.
Fig. below illustrates that a single function name can be used to handle different number and different
types of argument. This is something similar to a particular word having several different meanings
depending upon the context. Using a single function name to perform different type of task is known
as function overloading. Polymorphism plays an important role in allowing objects having different
internal structures to share the same external interface. This means that a general class of operations
may be accessed in the same manner even though specific action associated with each operation may
differ. Polymorphism is extensively used in implementing inheritance.

There are several different kinds of polymorphism.

1) A variable with a given name may be allowed to have different forms and the program can
determine which form of the variable to use at the time of execution. For example, a variable
named USERID may be capable of being either an integer (whole number) or a string of characters
(perhaps because the programmer wants to allow a user to enter a user ID as either an employee
number - an integer - or with a name - a string of characters). By giving the program a way to
distinguish which form is being handled in each case, either kind can be recognized and handled.
2) A named function can also vary depending on the parameters it is given. For example, if given
a variable that is an integer, the function chosen would be to seek a match against a list of employee
numbers; if the variable were a string, it would seek a match against a list of names. In either case,
both functions would be known in the program by the same name. This type of polymorphism is
sometimes known as overloading.
In C++, for example, the operator known as the plus sign (+) - which is effectively a simple named
function - can be assigned to operate on two objects such that it adds them together (perhaps the
most common form of the + operation) or, as in boolean searching, a + can indicate a logical "and"
(meaning that both words separated by the + operator must be present in order for a citation to be
returned). In another context, the + sign could mean an operation to concatenate the two objects
or strings of letters on either side of the + sign.
A given operator can also be given yet another meaning when combined with another operator.
For example, in the C++ language, a "++" following a variable can mean "increment this value by
1". The meaning of a particular operator is defined as part of a class definition. Since the
programmer can create classes, the programmer can also define how operators work for this class
of objects; in effect, the programmer can redefine the computing language.
3) Polymorphism can mean, as in the ML language, a data type of "any," such that when specified
for a list, a list containing any data types can be processed by a function. (For example, if a function
simply determines the length of a list, it doesn't matter what data types are in the list.)
The override Modifier

Using override we can modify a method or property

An override method provides a new implementation of a member inherited from a base


class
You cannot override a non-virtual or static method

The overridden base method must be virtual, abstract, or override

How Polymorphism Works

Polymorphism ensures that the appropriate method of the subclass is called through its
base class' interface
Polymorphism is implemented using a technique called late method binding

Exact method to be called is determined at runtime, just before performing the


call
Applied for all abstract / virtual methods

Note: Late binding is slower than normal (early) binding

Example 2 - Polymorphism
abstract class Figure
{
public abstract double CalcSurface();
}
abstract class Square
{
public override double CalcSurface() { return }
}
Figure f1 = new Square(...);
Figure f2 = new Circle(...);
// This will call Square.CalcSurface()
int surface = f1.CalcSurface();
// This will call Square.CalcSurface()
int surface = f2.CalcSurface();

Example 2 - Polymorphism

Benefits Of Polymorphism
The biggest advantage of polymorphism is creation of reusable code by programmers. Classes
once written, tested and implemented can be easily reused without caring what is written in the
cases.
Polymorphic variables help with memory use, in that a single variable can be used to store
multiple data types rather than declaring a different variable for each data format to be used.
The other advantage is more generic and loosely coupled code.
Imagine a class hierarchy as follows:

The calling code which uses these classes, will be like:


Shape *basep[] = { &line_obj, &tri_obj,
&rect_obj, &cir_obj};
for (i = 0; i < NO_PICTURES; i++)
basep[i] -> Draw ();
Where, line_obj, tri_obj etc are objects of the concrete Shape classes Line, Triangle and so on,
and they are stored in a array of pointers of the type of more generalized base class Shape.
This gives the additional flexibility and loose coupling that if you need to add another concrete
shape class say Rhombus, the calling code does not have to change much, because it refers to all

concrete shapes with a pointer to Base class Shape. You only have to make the Base class pointer
point to the new concrete class.
At the sametime the calling code can call appropriate methods of those classes because the
Draw() method would be virtual in these classes and the method to call will be decided at runtime depending on what object the base class pointer points to.

CONCLUSION
OOP fundamental principles are: inheritance, encapsulation, abstraction, and polymorphism.
Inheritance allows inheriting members form another class, Abstraction and encapsulation hide
internal data and allow working through abstract interface, and Polymorphism allows working
with objects through their parent interface and invoke abstract actions

REFERENCES
http://en.wikipedia.org/wiki/Object-oriented_programming
http://web.eecs.utk.edu/~huangj/CS302S04/notes/oo-intro.html
http://stackoverflow.com/questions/9147521/can-someone-explain-the-benefits-ofpolymorphism
A Complete Guide to Programming in C++ by Ulla Kirch-Prinz Peter Prinz

S-ar putea să vă placă și