Sunteți pe pagina 1din 10

An Introduction to Object

Oriented Programming

This introductory chapter covers the basics of object oriented program-


ming. It also serves to introduce the terminology used throughout this
book.
What is object oriented programming? What are the basic concepts
used in object oriented programming? What are the basic classifications
and definitions used for various concepts in object oriented program-
ming? These questions on object oriented programming are answered in
this introductory chapter.

WHAT IS OBJECT ORIENTED PROGRAMMING?

Object oriented programming has been the most popular programming


paradigm for more than last two decades. It has been the subject of
active research for more than three decades, and is well-accepted and
widely used in the software industry today.
What is object oriented programming? [Mossenbock 1993]1 provides
the following definition: ‘Object oriented programming means program-
ming with abstract data types (classes) using inheritance and dynamic
binding.’

1
[Mossenbock 1993] Hanspeter Mossenbock, ‘Object-Oriented Programming in
Oberon-2’, Springer-Verlag, 1993.
60 Tips for Object Oriented Programming

PROCEDURAL PROGRAMMING VERSUS OBJECT ORIENTED


PROGRAMMING

The traditional programming methodology encourages us to think about


solving problems by decomposing the programs into various procedures.
Procedures provide specific functionality and operate on (global) data.
Computers execute instructions sequentially and operate on data; the
procedural approach provides a layer of abstraction over the machine
by providing higher level procedures. So, procedural approach appears
to be the most natural way of solving problems. However, programming
on large scale with procedural approach may lead to lots of problems.
Huge applications written using procedural style tend to be fragile, and
it is difficult to maintain or extend the code.
Object orientated programming methodology encourages us to give
central importance to data (instead of procedures). Object orientation
provides support for modelling solutions at higher level in terms of classes,
relationship between classes, inheritance and dynamic binding. Instead
of writing code that solves specific problems, generalized classes are
written under object oriented approach, and then specific code is pro-
vided to solve the problem. This provides the basis for writing reusable
and extensible software.
To summarize, object oriented programming provides a higher level
of abstraction than procedural programming. Traditional procedural pro-
gramming supports writing software that solves specific problems; ob-
ject oriented programming provides support for writing software that is
also extensible, reusable and maintainable.

CLASS

A class declaration is a logical abstraction which defines a new type that


determines what an object of that type will look like. Object oriented
programming enables creation of self-contained types with classes. This
helps in reusability, maintenance, abstraction and other desirable prop-
erties for the software. For example, if you make changes to the class, it
does not necessarily imply that you have to change the code using that
class.
From programming point of view, a class refers to a programmer
defined data type together with a set of operations that can be per-
An Introduction to Object Oriented Programming !

formed on it. Combining the data with the operations on it leads to


encapsulation. Abstraction refers to hiding the internal details and ex-
posing only the relevant details of the class to the external users. Through
encapsulation, abstraction is achieved.

OBJECTS

An object is instantiated from a class type. It is possible to create any


number of objects from a class type.
Every object has three aspects associated with it: space, identity and
behaviour. A class is a logical entity and doesn’t occupy any space dur-
ing the program execution. An object declaration creates a physical en-
tity of a class type, so, an object is always associated with space. Every
object has a unique identity. Since every object occupies some memory,
objects have an address; also objects can have names associated with it.
In this way, every object can be uniquely identified in a program. Every
object has a set of behaviour (methods) associated with it.

METHODS AND FIELDS

A class contains both data and functions operating on it. Member func-
tions are known as methods and data members are known as fields.
When a method is invoked on an object, it is said that the object is
passed with a message.
The members (function or data) that are common to all the objects of
a class can be provided in the class itself. Such class members are also
known as static members (static functions or static data). For example, a
class might need to keep track of the number of objects created from
that class. A static data member can be used as a counter that will be
incremented or decremented whenever a new object is created or de-
stroyed. A function that is used to increment, decrement or access the
value of that counter will be a static function.

ACCESS SPECIFIERS

Access specifiers determine the accessibility of a class member. There


are two important access specifiers: public and private. Private members
" 60 Tips for Object Oriented Programming

are not meant to be exposed to users, and contains just the implementa-
tion detail of class that users are not concerned about. Public members
are designed and supposed to be used by the users of the class. It is
through the public members that the class is accessed and used; these
members are collectively referred to as the public interface of the class.

USERS OF A CLASS

A class is designed to provide a specific functionality. There are two


main kinds of users of a class: programmers who use the class for using
its functionality, and those who use the class for extending or reusing its
functionality (by inheriting from that class, which is covered later in this
chapter). Collectively, these users are referred to as clients of a class.
For using a class by creating objects of that type or invoking methods
on that object doesn’t need the users to be aware of the internal details
of the class. However, the programmers who reuse the class by extend-
ing it, need to know the internal details of the class to do it properly.

FOUNDATIONS OF OBJECT ORIENTED PROGRAMMING

Object orientation is built on the strong foundation of encapsulation,


abstraction, inheritance and polymorphism.

Encapsulation

Structured programming is oriented towards functionality; programs are


designed with writing functions in mind (with functions operating on
data). Functions are free to operate and modify the (usually global and
unprotected) data.
Object oriented programming gives primary importance to data, and
functions are designed to make use of that (localized and protected)
data. The data and functions operating on that data are combined to-
gether and provided as a single unit (which is nothing but a class).
The term encapsulation refers to combining data and functions oper-
ating on it as a single unit.
An Introduction to Object Oriented Programming #

Abstraction

Abstraction means hiding lower-level details from the users and expos-
ing only the essential and relevant details to the users.
For example, for driving a car, it is enough for the driver to know
essential and relevant details such as knowledge and use of steering,
gear, dash board, breaks, accelerator, etc. It is not necessary to know the
internal implementation details such as how spark plugs work, how fuel
is injected into the combustion chamber, or how batteries are charged
indirectly by the engine. Essentially, as a driver, we are concerned only
about using the car instead of worrying about how the car works and
provides the functionality. In other words, a car abstracts the internal
details and only relevant details are exposed to us as a driver of the car.
In object oriented programming, a class (specified by the keyword
class in C++/Java/C#) specifies an Abstract Data Type (ADT). A class is
the basic unit of abstraction; it has abstract meaning, providing a higher-
level view of the operations to the users and hides the lower-level im-
plementation details. In other words, a class lets us focus exclusively on
behaviour and lets us ignore its internal representation.

Inheritance

Inheritance is a reusability mechanism in object oriented programming,


in which the common properties of various objects are exploited to form
relationships with each other. The abstract and common properties are
provided in the super class and those properties are available to the
more specialized subclasses. This type of relationship is common in the
real world so it acts as a way to model the real world objects in program-
ming. For example, a whale inherits the properties of a mammal (single
inheritance); a two-in-one set inherits properties from both tape and
radio (multiple inheritance).
Inheritance always deals with more that one class. When we say that
a class of one type inherits from another class, the inheriting class is
called as derived class or subclass and the inherited one as base class or
super class. By inheriting, the derived class contains all the properties of
the base class and then it adds up some more properties, which are
relevant to it alone.
$ 60 Tips for Object Oriented Programming

As we have already mentioned, the inheritance mechanism allows the


reusability of code by allowing the classes to derive new classes from
the existing ones.
Generalization Even though the word generalization is practically
used interchangeably with the term inheritance, it refers to the concept
of inheritance in essentially a bottom-up approach. Take the example of
a four-wheeler. It is the general class encompassing all vehicles like bus,
car etc. Here we define the super class by taking the general properties
from the subclasses in a bottom-up fashion.
Specialization It involves defining the subclasses from the existing
super-classes in a top-down fashion. We can classify all automobiles as
vehicles, and provide subclasses such as two-wheelers and four-wheel-
ers; four-wheelers can further be classified as heavy-motor vehicles and
light-motor vehicles; light-motor vehicles can be sub-divided in to car,
van, jeep and so on. Note how we start from a generalized class and
keep identifying specialized classes in a top-down fashion in this ap-
proach.
Thus inheritance helps in creating relationship between classes based
on their common properties. A set of classes having super class and
subclass relationship at multiple levels is known as an inheritance hier-
archy.

Polymorphism

In the real world, every message we pass, has a context. Depending on


the context the entire meaning of the message could change and so the
response for the message. Similarly in programming, depending on the
object, a message can be interpreted in many ways. This is known as
polymorphism in object oriented programming.
Polymorphism can broadly be classified into two categories: compile-
time polymorphism and runtime polymorphism. Function overloading
and operator overloading are the most common forms of compile-time
polymorphism in OOP. Runtime polymorphism is achieved using virtual
functions and inheritance.
In function overloading, more than one method with the same name
but different types of parameters and/or different number of parameters
can be used. Depending on the actual number and/or static type of the
An Introduction to Object Oriented Programming %

parameters used, the compiler will resolve the call to the correct method.
In operator overloading, the predefined operators defined by the lan-
guage can be supported by the classes also. In this way, classes can
behave like primitive types (like int, float etc) defined by the language.
Depending on the arguments used for the operator, correct method will
be resolved by the compiler.
Runtime polymorphism provides the basis of reusability in object ori-
ented programming. In inheritance, a base class pointer or reference can
hold a derived class object. We can invoke methods from the base class
pointer or reference. If such a method is a virtual method, then the
actual method invoked depends on the dynamic type of the object pointed
by the base class pointer or reference. The type of the base class pointer
or reference is known as the static type of the object, and the actual
runtime type of the actual object pointed by the pointer or reference is
known as the dynamic type of the object.
When the compiler sees invocation of a method from a base class
pointer or a reference, and if the method is a virtual method, it defers
determining the exact method to be called to runtime. At runtime, based
on the actual dynamic type of the object, the method is invoked. This
mechanism is known as dynamic method resolution or dynamic method
invocation.

MONOMORPHIC AND POLYMORPHIC CLASSES

There are some classes that are used only for abstraction/encapsulation
and provide a specific functionality; they do not also make use of inher-
itance/virtual functions. Classes that do not have any virtual functions
(runtime polymorphism) are known as monomorphic classes.
The classes that have virtual functions and designed for making use of
runtime polymorphism are known as polymorphic classes.

ABSTRACT, CONCRETE AND INTERFACE CLASSES

Classes are modelled based on the real world objects and their relation-
ships. Sometimes, there are objects that are not really seen in the real-
world, and classes model an abstract relationship between these objects.
& 60 Tips for Object Oriented Programming

For example, Matiz, Ambassador, Indica and Santro are a few car
objects. From these objects, we can model a class named as Car. Simi-
larly, from various bike objects, we can design a Bike class. Both Car
and Bike classes have many common properties, and we can abstract
those common properties as a Vehicle class. This modelling proves
useful in practice. However, Vehicle is an abstract concept and we
cannot see direct instances of a Vehicle class (but there are specific
instances of a Car class). So, Vehicle class is an abstract base class. An
abstract class is a class which cannot be instantiated. The Car and Bike
classes are concrete classes. A concrete class is a class that can be instan-
tiated.
From programming point of view, if definitions of all the methods are
provided in a class, then the class is a concrete class. If there is at least
one virtual method of a class that does not have an implementation (i.e.
definition or body of the method), then it is an abstract class. If all virtual
methods are just declared and no implementation is provided for the
class, then it is an interface class.
An important note: An interface class is sometimes shortly referred to
as an interface (which is also a language feature in Java and C#). This
term should not be confused with the term class interface, which refers
to the public members of a class.

TYPES OF INHERITANCE

Inheritance can be classified based on the way it is used. One way to


classify inheritance is single inheritance and multiple inheritance; an-
other classification is interface inheritance and implementation inherit-
ance.
If any class in the inheritance hierarchy has only one direct (or imme-
diate) base class, then, the inheritance model is known as single inherit-
ance. If a class in the hierarchy has more than one direct (or immediate)
base class, then it is known as multiple inheritance.
An interface class just provides a protocol (signature of a method that
should be defined by the derived classes implementing it) that should
be followed by all the derived classes implementing that class. The in-
heritance model followed, is known as interface inheritance.
An abstract base class provides both a protocol (signature of a method
An Introduction to Object Oriented Programming '

that should be defined by the derived classes implementing it) as well as


implementation (basic implementation of the method that the derived
classes need not implement). The derived classes can provide more
methods or entirely new definitions of the methods provided in the base
class. So, classes that inherit from abstract base classes are said to extend
the base class. Similarly, classes can be inherited from concrete classes
also (but it is not recommended; it is covered later in this book). The
inheritance model in which an abstract or concrete class can be ex-
tended is known as implementation inheritance (in this model, the de-
rived classes will inherit one or more methods with definition or body;
so the derived classes inherit some implementation of methods also; so
this model is known as implementation inheritance).

BENEFITS OF OBJECT ORIENTED PROGRAMMING

Mastering complexity, extensibility and reusability are three main ben-


efits of object oriented programming.
Since object oriented programming is based on the solid foundation
provided by abstraction, it is possible to create a complex software that
hides lots of implementation details. This reason makes object orienta-
tion a suitable approach for programming on a large scale.
With inheritance (and runtime polymorphism), it is easier to intro-
duce new changes and extend the software with new types without
affecting the rest of the code, this implies that object oriented program-
ming enables writing extensible software.
Object orientation also enables providing abstract or concrete classes
as libraries, and related classes as frameworks; instead of (re)writing
classes every time, we can reuse the classes. So, object orientation helps
in developing reusable software.

COSTS OF OBJECT ORIENTED PROGRAMMING

Object oriented programming is not a panacea for all the problems faced
by the software industry today. With more than three decades of object
oriented programming, the hype and over-enthusiasm in promoting object
orientation has subsided and the costs of object oriented programming
are now well-known and clear.
 60 Tips for Object Oriented Programming

Object orientation requires a new way of thinking (different from proce-


dural approach), as it is difficult to comprehend object oriented pro-
grams. Since object orientation provides a higher level of abstraction
from machine level details, there is some loss of efficiency (compared to
procedural programs).
The benefits of object oriented programming aren’t automatically avail-
able to programs still written in procedural way by just making use of
object oriented programming constructs. Object oriented programming
requires a new way of thinking which takes time to master. For pro-
grammers from procedural background, it takes more time to learn the
object oriented approach than to learn the language features.
Object oriented programs are typically more difficult to understand
than their procedural equivalent. For example, to understand how to
use a derived class, we need to go through the public members of that
class and also the public members of all of its base classes. The effort
needed to understand and make use of class libraries, frameworks or
inheritance hierarchies is non-trivial.
Object orientation provides a higher level of abstraction from lowlevel
details alongwith providing features to model higher level relationship
between classes. This flexibility comes with some loss of efficiency when
compared to straight-forward procedural constructs. For example, to
support runtime polymorphism, an extra level of indirection is needed
to invoke a virtual method. In other words, a virtual method call is
almost always slower than a direct method call. Such additional over-
head for abstracting low level details is known as abstraction penalty in
object oriented programming.

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