You are on page 1of 17

Chapter One: Introduction to Object

Oriented Programming
Chapter- One: Introduction to Object-Oriented Programming

Basic topics of chapter 1:


Overview of computer, program, software Object-Oriented Programming
programming paradigm OOP Concepts
Types of programming paradigm

1.1. Overview of computer ,program, Software


Computer
You use word processors to write documents, Web browsers to explore the Internet, and email
programs to send email. These are all examples of software that runs on computers. Software is
developed using programming languages. There are many programming languages—so why
Java? The answer is that Java enables users to develop and deploy applications on the Internet
for servers, desktop computers, and small hand-held devices. The future of computing is being
profoundly influenced by the Internet, and Java promises to remain a big part of that future. Java
is the Internet programming language.
Programs
Computer programs, known as software, are instructions to the computer, telling it what to do.
Computers do not understand human languages, so you need to use computer languages in
computer programs. Programming is the creation of a program that is executable by a computer
and performs the required tasks.
A computer’s native language, which differs among different types of computers, is its machine
language—a set of built-in primitive instructions. These instructions are in the form of binary
code, so in telling the machine what to do, you have to enter binary code. Programming in
machine language is a tedious process. Moreover, the programs are highly difficult to read and
modify. For example, to add two numbers, you might have to write an instruction in binary like
this:
1101101010011010
Assembly language is a low-level programming language in which a mnemonic is used to
represent each of the machine-language instructions. For example, to add two numbers, you
might write an instruction in assembly code like this:
ADDF3 R1, R2, R3

BY: Alex E Object Oriented programming in JAVA Page 1


Chapter One: Introduction to Object
Oriented Programming

Assembly languages were developed to make programming easy. However, since the computer
cannot understand assembly language, a program called an assembler is used to convert
assembly-language programs into machine code, as shown in Figure 1.1:

FIGURE1. 1: Assembler translates assembly-language instructions to machine code.


Assembly programs are written in terms of machine instructions with easy-to-remember
mnemonic names. Since assembly language is machine dependent, an assembly program can be
executed only on a particular kind of machine. The high-level languages were developed in order
to transcend platform specificity and make programming easier. The high-level languages are
English-like and easy to learn and program. Here, for example, is a high-level language
statement that computes the area of a circle with radius 5:
area = 5 * 5 * 3.1415;
Among the more than one hundred high-level languages, the following are well known:
COBOL (COmmon Business Oriented Language)
FORTRAN (FORmula TRANslation)
BASIC (Beginner’s All-purpose Symbolic Instruction Code)
Pascal (named for Blaise Pascal)
Visual Basic (Basic-like visual language developed by Microsoft)
Delphi (Pascal-like visual language developed by Borland)
C++ (an object-oriented language, based on C)
C# (a Java-like language developed by Microsoft)
Java
Each of these languages was designed for a specific purpose. COBOL was designed for business
applications and is used primarily for business data processing. FORTRAN was designed for
mathematical computations and is used mainly for numeric computations. BASIC was designed
to be learned and used easily. Visual Basic and Delphi are used in developing graphical user

BY: Alex E Object Oriented programming in JAVA Page 2


Chapter One: Introduction to Object
Oriented Programming
interfaces and in rapid application development. C++ is popular for system software projects
such as writing compilers and operating systems. The Microsoft Windows operating system was
coded using C++. C# (pronounced C sharp) is a new language developed by Microsoft for
developing applications based on the Microsoft.NET platform. Java, developed by Sun
Microsystems, is widely used for developing platform-independent Internet applications.
A program written in a high-level language is called a source program or source code. Since
a computer cannot understand a source program, a program called a compiler is used to translate
it into a machine-language program. The machine-language program is then linked with other
supporting library code to form an executable file, which can be run on the machine, as shown in
Figure 1.2. On Windows, executable files have extension .exe.

FIGURE 1.2: A source program is compiled into a machine-language file, which is then
linked with the system library to form an executable file.

Operating Systems
The operating system (OS) is the most important program that runs on a computer, which
manages and controls a computer’s activities. The popular operating systems are Microsoft
Windows, Mac OS, and Linux. Application programs, such as a Web browser or a word
processor, cannot run without an operating system. The interrelationship of hardware,
operating system, application software, and the user is shown in Figure 1.3:

FIGURE 1.3 The operating system is the software that controls and manages the system.

BY: Alex E Object Oriented programming in JAVA Page 3


Chapter One: Introduction to Object
Oriented Programming

1.2. Programming Paradigms


There are lots for programming language that are known but all of them need to follow some
strategy when they are implemented and this methodology/strategy is paradigms. Paradigm can
also be termed as method to solve some problem or do some task.
Programming paradigm is an approach to solve problem using some programming language.
Programming paradigm is also a
. . . Way of conceptualizing what it means to perform computation and how tasks to be carried
out on a computer should be structured and organized.

Types of programming paradigm


Apart from varieties of programming language there are lots of paradigms to fulfill each and
every demand. We can distinguish between two types of programming paradigm: Imperative
programming paradigm and declarative programming paradigm. They are discussed below:

Figure 1.4: Types of programming paradigms


In any program, you will always have both imperative and declarative codes, what you should
aim for is to hide all imperative codes behind the abstractions, so that other parts of the program
can use them declaratively.

BY: Alex E Object Oriented programming in JAVA Page 4


Chapter One: Introduction to Object
Oriented Programming
i. Declarative programming paradigm
A computer language that does not require writing traditional programming logic; Users
concentrate on defining the input and output rather than the program steps required in a
procedural programming language such as C++ or Java.
This is the form or style of programming where we are most concerned with what we want as the
answer, or what would be returned. Here, we as developers are not concerned with how we get
there simply concerned with the answer that is received. Declarative programming examples are
CSS, HTML, XML, etc.

 Declarative - specify what to do, not how to do it


 E.g.: HTML describes what should appear on a web page, not how it should be
drawn on the screen
Declarative programming paradigm- is divided as Logic, Functional, and Database. In
computer science the declarative programming is a style of building programs that expresses
logic of computation without talking about its control flow. It often considers programs as
theories of some logic. It may simplify writing parallel programs. The focus is on what needs to
be done rather how it should be done basically emphasizing on what code is actually doing. It
just declares the result we want rather how it has be produced. This is the only difference
between imperative (how to do) and declarative (what to do) programming paradigms. Getting
into deeper we would see logic, functional and database.

a. Logic programming paradigms – It can be termed as abstract model of computation. It


would solve logical problems like puzzles, series etc. In logic programming we have a
knowledge base which we know before and along with the question and knowledge base
which is given to machine, it produces result. In normal programming languages, such
concept of knowledge base is not available but while using the concept of artificial
intelligence, machine learning we have some models like Perception model which is using
the same mechanism. In logical programming the main emphasize is on knowledge base and
the problem. The execution of the program is very much like proof of mathematical
statement, e.g., Prolog

BY: Alex E Object Oriented programming in JAVA Page 5


Chapter One: Introduction to Object
Oriented Programming
sum of two number in prolog:
predicates
sum of two number(integer, integer)
clauses
sum(0, 0).
sum(n, r):-
n1=n-1,
sum(n1, r1),
r=r1+n

b. Functional programming paradigms –

The functional programming paradigm has its roots in mathematics and it is language
independent. The key principal of this paradigm is the execution of series of mathematical
functions. The central model for the abstraction is the functions which are meant for some
specific computation and not the data structure. Data are loosely coupled to functions. The
functions hide their implementation. Function can be replaced with their values without changing
the meaning of the program. Some of the languages like perl, javascript mostly uses this
paradigm.

c. Database/Data driven programming approach –

This programming methodology is based on data and its movement. Program statements are
defined by data rather than hard-coding a series of steps. A database program is the heart of a
business information system and provides file creation, data entry, update, query and reporting
functions. There are several programming languages that are developed mostly for database
application. For example SQL. It is applied to streams of structured data, for filtering,
transforming, aggregating (such as computing statistics), or calling other programs. So it has its
own wide application.

CREATE DATABASE databaseAddress;


CREATE TABLE Addr (

BY: Alex E Object Oriented programming in JAVA Page 6


Chapter One: Introduction to Object
Oriented Programming
PersonID int,
LastName varchar(200),
FirstName varchar(200),
Address varchar(200),
City varchar(200),
);

Why you should use declarative programming?


Reusability: Since the way the result is achieved does not necessarily matter here, it allows for
the functions you build to be more general and could potentially be used for multiple purposes
and not just one. Not rewriting code can speed up the program you are currently writing and any
others that use the same functionality in the future.
Reducing Errors: Given that in declarative programming you tend to write functions that do
not change state as you would in functional programming, the chances of errors arising are
smaller and it allows for your application to become more stable. The removal of side effects
from your functions allows you to know exactly what comes in and what comes out, allows for a
more predictable program.

Potential drawbacks of declarative programming/Disadvantage

Lack of Control: - In declarative programming, you may use functions that someone else
created, in order to achieve the desired results. But you may need specific things to be completed
behind the scenes to make your result come out properly. You do not have this control in
declarative programming as you would in imperative programming.

Inefficiency: - When the implementation is controlled by something else, you may have
problems making your code efficient. In applications where there may be a time constraint, you
will need to program the individual steps in order to make sure your program is running as
efficient as possible.

ii. Imperative programming paradigm

BY: Alex E Object Oriented programming in JAVA Page 7


Chapter One: Introduction to Object
Oriented Programming
A programming language that requires programming discipline such as C/C++, Java, COBOL,
FORTRAN, Perl and JavaScript. Programmers writing in such languages must develop a proper
order of actions in order to solve the problem, based on knowledge of data processing and
programming.
 Imperative - specify both what and  how-to knowledge
 int x; - what (declarative)
 x=x+1; - how
This is the form and style of programming in which we care about how we get to an answer, step
by step. We want the same result ultimately, but we are telling the complier to do things a certain
way in order to achieve that correct answer we are looking for.

For example: To give directions in an imperative fashion, you say, “Go to 1st Street, turn left
onto Main, drive two blocks, turn right onto Maple, and stop at the third house on the left.”
The declarative version might sound something like this: “Drive to Sue’s house.” One says how
to do something; the other says what needs to be done.

Examples of Imperative programming paradigm:


Average of five number in C++
int marks[5] = { 12, 32, 45, 13, 19 }
int sum = 0;
float average = 0.0;
for (int i = 0; i < 5; i++) {
    sum = sum + marks[i];
} average = sum / 5;
Imperative programming is divided into: Procedural and OOP paradigms. These paradigms are
as follows:

a. Procedural programming paradigm.

A procedural Programming language follows a sequence of instructions and tells the computer
what to do step- by-step. Procedural programming depends on procedures. As procedural
programming language follows a method of solving problems from the top of the code to the

BY: Alex E Object Oriented programming in JAVA Page 8


Chapter One: Introduction to Object
Oriented Programming
bottom of the code, if a change is required to the program, the developer has to change every line
of code that links to the main or the original code.

If the user wants to code a program, they would have to follow a sequence of instructions and
thereby enter the instructions. In addition, we can say that when a problem is need to be fix using
procedural programming, the developer will start with the problem (procedure) and then he
logically fragment the problem down into sub problems (Sub-Procedures). Subsequently, this
process will continue until a sub-procedure is simple enough to be solved by itself. Examples for
procedural programming languages include C, COBOL, FORTRAN and VB.

b. Object oriented programming

Object Oriented Programming or OOP is a programming paradigm that uses the concept of
classes and objects to construct models based on the real world surrounding. An object is a
constituent of a program that recognizes how to execute certain actions and how to interrelate
with other elements of the program. More emphasis is on data rather procedure. It can handle
almost all kind of real life problems which are today in scenario. Objects are the foundation of
object-oriented programming. An object-oriented program uses a set of objects, which will
communicate by sending and receiving messages to request services or information. A class is a
collection of objects with similar properties and behaviors (aka methods).

A simple example of an object would be a person. Logically, you would expect a person to have
a name. This would be considered a property of the person. You would also expect a person to
be able to do something, such as walking. This would be considered a method of the person. A
method in object-oriented programming is like a procedure in procedural programming. Finally,
an object or a collection of objects (class) attempts to complete its goals (goals such as
displaying ‘hello world’ on to the screen) by communicating by swapping messages. In fact,
displaying ‘Hello World’ is a method. Some examples for Object-Oriented Programming
languages include Java, C#.NET, C++, Python and Perl.

Comparing OOP and Procedural Programming


When we consider, what are the differences between Object-Oriented Programming and
Procedural Programming it is obvious that OOP is based on objects and classes while Procedural

BY: Alex E Object Oriented programming in JAVA Page 9


Chapter One: Introduction to Object
Oriented Programming
Programming is based on procedures. Using objects in OOP rather than procedures as in
procedural programming allow the developers to reuse a single code anywhere as needed. Thus,
allowing coding methods that are more complicated with ease and using less code.

When we consider about the security of the data when using either of the programming
paradigms, OOP provides more security as it has a more improved data concealing mechanism
rather than procedural programming languages.

Procedural programming uses global data for sharing data within functions therefore data can be
accessed from function to function without any access limits. However, OOP does not allow
global data but instead the developer has the ability to set the functions to private or public so
developers can control the access rights for data.

In procedural programming, it is quite difficult to add new data or functions to the program but
OOP offers an easy approach to add new data and functions. Additionally, in procedural
programming data cannot be moved liberally from function to function but OOP allow objects to
move and communicate with each other via member functions.

Object Orientation as a New Paradigm: The Big Picture


It is claimed that the problem-solving techniques used in object-oriented programming more
closely models the way humans solve day-to-day problems. So let’s consider how we solve an
everyday problem:
Suppose you wanted to send flowers to a friend named Robin who lives in another city. To solve
this problem you simply walk to your nearest florist run by, lets say, Fred. You tell Fred the
kinds of flowers to send and the address to which they should be delivered. You can be assured
that the flowers will be delivered.
Now, let’s examine the mechanisms used to solve your problem.
 You first found an appropriate agent (Fred, in this case) and you passed to this agent a
message containing a request.
 It is the responsibility of Fred to satisfy the request.
 There is some method (an algorithm or set of operations) used by Fred to do
this.

BY: Alex E Object Oriented programming in JAVA Page 10


Chapter One: Introduction to Object
Oriented Programming
 You do not need to know the particular methods used to satisfy the request—
such information is hidden from view.

Off course, you do not want to know the details, but on investigation you may find that Fred
delivered a slightly different message to another florist in the city where your friend Robin lives.
That florist then passes another message to a subordinate who makes the floral arrangement. The
flowers, along with yet another message, are passed onto a delivery person and so on. The
florists also have interactions with wholesalers who, in turn, had interactions with flower
growers and so on. This leads to our first conceptual picture of object-oriented programming:

An object-oriented program is structured as community of interacting agents called objects.


Each object has a role to play. Each object provides a service or performs an action that is used
by other members of the community.

1.3. OOP Concepts


All object-oriented programming languages provide mechanisms that help you implement the
object-oriented model. They are encapsulation, inheritance, and polymorphism. Let’s take a look
at these concepts now.

Encapsulation

Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps
both safe from outside interference and misuse. One way to think about encapsulation is as a
protective wrapper that prevents the code and data from being arbitrarily accessed by other code
defined outside the wrapper. Access to the code and data inside the wrapper is tightly controlled
through a well-defined interface.
To relate this to the real world, consider the automatic transmission on an automobile. It
encapsulates hundreds of bits of information about your engine, such as how much you are
accelerating, the pitch of the surface you are on, and the position of the shift lever. You, as the
user, have only one method of affecting this complex encapsulation: by moving the gear-shift
lever. You can’t affect the transmission by using the turn signal or windshield wipers, for
example. Thus, the gear-shift lever is a well-defined (indeed, unique) interface to the
transmission. Further, what occurs inside the transmission does not affect objects outside the

BY: Alex E Object Oriented programming in JAVA Page 11


Chapter One: Introduction to Object
Oriented Programming
transmission. For example, shifting gears does not turn on the headlights! Because an automatic
transmission is encapsulated, dozens of car manufacturers can implement one in any way they
please. However, from the driver’s point of view, they all work the same. This same idea can be
applied to programming.

The power of encapsulated code is that everyone knows how to access it and thus can use it
regardless of the implementation details—and without fear of unexpected side effects.
In Java/C++ the basis of encapsulation is the class. A class defines the structure and behavior
(data and code) that will be shared by a set of objects. Each object of a given class contains the
structure and behavior defined by the class, as if it were stamped out by a mold in the shape of
the class. For this reason, objects are sometimes referred to as instances of a class. Thus, a class
is a logical construct; an object has physical reality.

When you create a class, you will specify the code and data that constitute that class.
Collectively, these elements are called members of the class. Specifically, the data defined by the
class are referred to as member variables or instance variables. The code that operates on that
data is referred to as member methods or just methods. In properly written Java programs, the
methods define how the member variables can be used. This means that the behavior and
interface of a class are defined by the methods that operate on its instance data.

Inheritance

Inheritance is the process by which one object acquires the properties of another object. This is
important because it supports the concept of hierarchical classification. For example, a Golden
Retriever is part of the classification dog, which in turn is part of the mammal class, which is
under the larger class animal. Without the use of hierarchies, each object would need to define
all of its characteristics explicitly.

However, by use of inheritance, an object need only define those qualities that make it unique
within its class. It can inherit its general attributes from its parent. Thus, it is the inheritance
mechanism that makes it possible for one object to be a specific instance of a more general case.
Let’s take a closer look at this process.

BY: Alex E Object Oriented programming in JAVA Page 12


Chapter One: Introduction to Object
Oriented Programming
Most people naturally view the world as made up of objects that are related to each other in a
hierarchical way, such as animals, mammals, and dogs. If you wanted to describe animals in an
abstract way, you would say they have some attributes, such as size, intelligence, and type of
skeletal system. Animals also have certain behavioral aspects; they eat, breathe, and sleep. This
description of attributes and behavior is the class definition for animals.

If you wanted to describe a more specific class of animals, such as mammals, they would have
more specific attributes, such as type of teeth, and mammary glands. This is known as a subclass
of animals, where animals are referred to as mammals’ superclass. Since mammals are simply
more precisely specified animals, they inherit all of the attributes from animals. A deeply
inherited subclass inherits all of the attributes from each of its ancestors in the class hierarchy.

Fig: inheritance

BY: Alex E Object Oriented programming in JAVA Page 13


Chapter One: Introduction to Object
Oriented Programming
Inheritance interacts with encapsulation as well. If a given class encapsulates some attributes,
then any subclass will have the same attributes plus any that it adds as part of its specialization.
This is a key concept which lets object-oriented programs grow in complexity linearly rather
than geometrically. A new subclass inherits all of the attributes of all of its ancestors. It does not
have unpredictable interactions with the majority of the rest of the code in the system.

Polymorphism

Polymorphism (Greek, meaning “many forms”) is a feature that allows one interface to be used
for a general class of actions. The specific action is determined by the exact nature of the
situation. Consider a stack (which is a last-in, first-out list). You might have a program that
requires three types of stacks. One stack is used for integer values, one for floating-point values,
and one for characters. The algorithm that implements each stack is the same, even though the
data being stored differs. In a non–object-oriented language, you would be required to create
three different sets of stack routines, with each set using different names. However, because of
polymorphism, in Java you can specify a general set of stack routines that all share the same
names.

More generally, the concept of polymorphism is often expressed by the phrase “one interface,
multiple methods.” This means that it is possible to design a generic interface to a group of
related activities. This helps reduce complexity by allowing the same interface to be used to
specify a general class of action. It is the compiler’s job to select the specific action (that is,
method) as it applies to each situation. You, the programmer, do not need to make this selection
manually. You need only remember and utilize the general interface.
There are several fundamentally different kinds of polymorphism:
 If a function denotes different and potentially heterogeneous implementations depending
on a limited range of individually specified types and combinations, it is called ad
hoc polymorphism. Ad hoc polymorphism is supported in many languages using function
overloading.
 If the code is written without mention of any specific data type and thus can be used
transparently with any number of new types, it is called parametric polymorphism. In the
object-oriented programming community, this is often known as generics or generic

BY: Alex E Object Oriented programming in JAVA Page 14


Chapter One: Introduction to Object
Oriented Programming
programming. In the functional programming community, this is often simply
called polymorphism.
 Subtyping is a concept wherein a name may denote instances of many different classes as
long as they are related by some common superclass. In object-oriented programming,
this is often referred to simply as polymorphism.
Example:
abstract class Animal {
abstract String talk();
}
class Cat extends Animal {
String talk() {
return "Meow!";
}
}
class Dog extends Animal {
String talk() {
return "Woof!";
}
}
class TestClass {
void letsHear(Animal a) {
println(a.talk());
}

void main() {
letsHear(new Cat());
letsHear(new Dog());
}
}
Polymorphism, Encapsulation, and Inheritance Work Together
When properly applied, polymorphism, encapsulation, and inheritance combine to produce a
programming environment that supports the development of far more robust and scalable
programs than does the process-oriented model. A well-designed hierarchy of classes is the basis
for reusing the code in which you have invested time and effort developing and testing.
Encapsulation allows you to migrate your implementations over time without breaking the code
that depends on the public interface of your classes. Polymorphism allows you to create clean,
sensible, readable, and resilient code.

BY: Alex E Object Oriented programming in JAVA Page 15


Chapter One: Introduction to Object
Oriented Programming

The Benefits of OOP


The concept of inheritance and the data-oriented approach allow a lot of reuse of existing
classes and help to eliminate redundant code.
Programs can be built using working modules that already know how to communicate with
each other. This means that programs do not always have to be written from scratch – thus
saving development time and increasing productivity.
Encapsulation (hiding of data) helps with the building of more secure programs – as data
cannot be unintentionally changed by other parts of the program.
There is a close link between objects in the real-world system and objects in the program.
Therefore the structure of the system is more likely to be meaningful to users.
The work for a project can be divided by class/object – making it easier to split work up
between a team of developers.
OO systems can be easily upgraded from small to larger systems.
The message passing technique for communication between objects makes it easy to describe
the interface of an OO system for other systems that need to communicate with it.
Software complexity can be easily managed.

To summarize:
 In procedural languages, everything is a procedure.
 In functional languages, everything is a function.
 In logic programming languages, everything is a logical expression (predicate).
 In object-oriented languages, everything is an object.

BY: Alex E Object Oriented programming in JAVA Page 16


Chapter One: Introduction to Object
Oriented Programming

BY: Alex E Object Oriented programming in JAVA Page 17

You might also like