Chapter One: Introduction To Object-Oriented Programming
Chapter One: Introduction To Object-Oriented Programming
Chapter One: Introduction To Object-Oriented Programming
Procedure oriented programming basically consists of writing a list of instructions for the computer to
follow, and organizing these instructions into groups known as functions. We normally use flowcharts
to organize these actions and represent the flow of control from one action to another.
In a multi-function program, many important data items are placed as global so that they may be
accessed by all the functions. Each function may have its own local data. Global data are more
vulnerable to an inadvertent change by a function. In a large program it is very difficult to identify what
data is used by which function. In case we need to revise an external data structure, we also need to
revise all functions that access the data. This provides an opportunity for bugs to creep in. Another
serious drawback with the procedural approach is that we do not model real world problems very well.
This is because functions are action-oriented and do not really corresponding to the element of the
problem.
Page 2
OOP Handout
Page 3
OOP Handout
Event-driven programming
Event-driven programming is a programming paradigm in which the flow of program execution is
determined by events - for example a user action such as a mouse click, key press, or a message from
Page 4
OOP Handout
the operating system or another program. An event-driven application is designed to detect events as
they occur, and then deal with them using an appropriate event-handling procedure. The idea is an
extension of interrupt-driven programming of the kind found in early command-line environments such
as DOS, and in embedded systems (where the application is implemented as firmware). Event-driven
programs can be written in any programming language, although some languages(Visual Basic for
example) are specifically designed to facilitate event-driven programming, and provide an integrated
development environment (IDE) that partially automates the production of code, and provides a
comprehensive selection of built-in objects and controls, each of which can respond to a range of
events. Virtually all object-oriented and visual languages support event-driven programming. Visual
Basic, Visual C++ and Java are examples of such languages.
A visual programming IDE such as VB.Net provides much of the code for detecting events
automatically when a new application is created. The programmer can therefore concentrate on issues
such as interface design, which involves adding controls such as command buttons, text boxes, and
labels to standard forms (a form represents an application's workspace or window). Once the user
interface is substantially complete, the programmer can add event-handling code to each control as
required. Many visual programming environments will even provide code templates for event-handlers,
so the programmer only needs to provide the code that defines the action the program should take when
the event occurs. Each event-handler is usually bound to a specific object or control on a form. Any
additional subroutines, methods, or function procedures required are usually placed in a separate code
module, and can be called from other parts of the program as and when needed.
Page 5
OOP Handout
• Classes
• Data abstraction and encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
We shall discuss these concepts in some detail in this section.
Objects
Objects are the basic run time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program has to handle. They may also
represent user-defined data such as vectors, time and lists. Programming problem is analyzed in terms
of objects and the nature of communication between them. Program objects should be chosen such that
they match closely with the real-world objects. Objects take up space in the memory and have an
associated address like a record in Pascal, or a structure in C.
When a program is executed, the objects interact by sending messages to one another. For example, if
“customer” and “account” are two objects in a program, then the customer object may send a message
to the acount object requesting for the bank balance. Each object contain data, and code to manipulate
data. Objects can interact without having to know details of each other„s data or code. It is a sufficient
to know the type of message accepted, and the type of response returned by the objects. Although
different author represent them differently the figure below shows two notations that are popularly used
in object-oriented analysis and design.
Classes
We just mentioned that objects contain data, and code to manipulate that data. The entire set of data and
code of an object can be made a user-defined data type with the help of class. In fact, objects are
variables of the type class. Once a class has been defined, we can create any number of objects
Page 6
OOP Handout
belonging to that class. Each object is associated with the data of type class with which they are
created. A class is thus a collection of objects with similar type. For example, Mango, Apple and orange
are members of class fruit. Classes are user-defined that types and behave like the built-in types of a
programming language. The syntax used to create an object is not different than the syntax used to
create an integer object in C. If fruit has been defined as a class, then the statement Fruit Mango; will
create an object mango belonging to the class fruit.
Data Abstraction and Encapsulation
The wrapping up of data and function into a single unit (called class) is known as encapsulation. 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 object„s data and the program. This insulation of the data from direct access by the
program is called data hiding or information hiding.
Abstraction refers to the act of representing essential features 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. They encapsulate all the essential
properties of the object that are to be created.
The attributes are sometime called data members because they hold information. The functions that
operate on these data are sometimes called methods or member function.
Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT).
Inheritance
Inheritance is the process by which objects of one class acquired the properties of objects of another
classes. It supports the concept of hierarchical classification. For example, the bird, „robin‟ is a part of
class „flying bird‟ which is again a part of the class „bird‟. The principal behind this sort of division is
that each derived class shares common characteristics with the class from which it is derived as
illustrated in fig below.
In OOP, the concept of inheritance provides the idea of reusability. This means that we can add
additional features to an existing class without modifying it. This is possible by deriving a new class
from the existing one. The new class will have the combined feature of both the classes. The real appeal
and power of the inheritance mechanism is that it allows the programmer to reuse a class i.e. almost,
but not exactly, what he wants, and to tailor the class in such a way that it does not introduced any
undesirable side-effects into the rest of classes. Note that each sub-class defines only those features
Page 7
OOP Handout
that are unique to it. Without the use of classification, each class would have to explicitly include all of
its features.
Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to
take more than on 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.
The figure 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.
Page 8
OOP Handout
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.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
Dynamic binding means that the code associated with a given procedure call is not known until the
time of the call at run time. It is associated with polymorphism and inheritance. A function call
associated with a polymorphic reference depends on the dynamic type of that reference.
Consider the procedure “draw” in fig. 1.7. by inheritance, every object will have this procedure. Its
algorithm is, however, unique to each object and so the draw procedure will be redefined in each class
that defines the object. At run-time, the code matching the object under current reference will be called.
Message Passing
An object-oriented program consists of a set of objects that communicate with each other. The process
of programming in an object-oriented language, involves the following basic steps:
1. Creating classes that define object and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same way as
people pass messages to one another. The concept of message passing makes it easier to talk about
building systems that directly model or simulate their real-world counterparts.
Page 9
OOP Handout
A Message for an object is a request for execution of a procedure, and therefore will invoke a function
(procedure) in the receiving object that generates the desired results. Message passing involves
specifying the name of object, the name of the function (message) and the information to be sent.
Example:
Object has a life cycle. They can be created and destroyed. Communication with an object is feasible as
long as it is alive.
Benefits of OOP
OOP offers several benefits to both the program designer and the user. Object-Orientation contributes
to the solution of many problems associated with the development and quality of software products.
The new technology promises greater programmer productivity, better quality of software and lesser
maintenance cost. The principal advantages are:
• Through inheritance, we can eliminate redundant code extend the use of existing
• Classes.
• We can build programs from the standard working modules that communicate with one another,
rather than having to start writing the code from scratch. This leads to saving of development time and
higher productivity.
• The principle of data hiding helps the programmer to build secure program that cannot be invaded by
code in other parts of a programs.
• It is possible to have multiple instances of an object to co-exist without any interference.
• It is possible to map object in the problem domain to those in the program.
• It is easy to partition the work in a project based on objects.
• The data-centered design approach enables us to capture more detail of a model can implemental
form.
• Object-oriented system can be easily upgraded from small to large system.
Page 10
OOP Handout
• Message passing techniques for communication between objects makes to interface descriptions with
external systems much simpler.
• Software complexity can be easily managed.
While it is possible to incorporate all these features in an object-oriented system, their importance
depends on the type of the project and the preference of the programmer. There are a number of issues
that need to be tackled to reap some of the benefits stated above. For instance, object libraries must be
available for reuse. The technology is still developing and current product may be superseded quickly.
Strict controls and protocols need to be developed if reuse is not to be compromised.
Developing software that is easy to use makes it hard to build. It is hoped that the object-oriented
programming tools would help to manage this problem.
Java language is a general-purpose programming language. It can be used to develop software for
mobile devices, browser-run applets, games, as well as desktop, enterprise (server-side), and scientific
applications.
Java platform consists of Java virtual machine (JVM) responsible for hardware abstraction, and a set
of libraries that gives Java a rich foundation.
Java tools include the Java compiler as well as various other helper applications that are used for day-
to-day development (e.g. debugger).
Why Java?
Object oriented Scalable
Interpreted High-performance multi-threaded
Portable Dynamic
Simple yet feature-full Distributed
Secure and robust
Page 11
Object Oriented
Everything in Java is coded using Object Oriented principles. This facilitates code modularization,
reusability, testability, and performance.
Interpreted/Portable
Java source is compiled into platform-independent bytecode, which is then interpreted (compiled into
native-code) at runtime. Java‟s slogan is "Write Once, Run Everywhere"
Simple
Java has a familiar syntax, automatic memory management, exception handling, single inheritance,
standardized documentation, and a very rich set of libraries (no need to reinvent the wheel).
Secure/Robust
Due to its support for strong type checking, exception handling, and memory management, Java is
immune to buffer- overruns, leaked memory, illegal data access. Additionally, Java comes with a
Security Manager that provides a sand-box execution model.
Scalable
Thanks to its overall design, Java is scalable both in terms of performance/throughput, and as a
development environment. A single user can play a Java game on a mobile phone, or millions of users
can shop though a Java-based e-commerce enterprise application.
High-performance/Multi-threaded
With its Hotspot Just-in-Time compiler, Java can achieve (or exceed) performance of native
applications. Java supports multi-threaded development out-of-the-box.
Dynamic
Java can load application components at run-time even if it knows nothing about them. Each class has a
run-time representation.
Distributed
Java comes with support for networking, as well as for invoking methods on remote (distributed)
objects through RMI.
Types of Java Programs
There are two types of Java programs:
1. Applications - Java programs that run directly on your machine.
Applications must have a main().
Java applications are compiled using the javac command and run using the java command.
OOP Handout
2. Applets - Java programs that can run over the Internet. The standard client/server model is used when
the Applet is executed. The server stores the Java Applet, which is sent to the client machine running
the browser, where the Applet is then run.
Applets do not require a main(), but in general will have a paint().
An Applet also requires an HTML file before it can be executed.
Java Applets are also compiled using the javac command, but are run either with a browser
or with the appletviewer command.
We will see exactly how to compile and run each when we write our first program as an
application and as an Applet (coming up next!).
We will write both types of Java programs during this class.
At first it may not be clear why you are writing an application rather than an Applet, or vice-
versa. For many of our beginning examples the choice may be arbitrary.
Our immediate goal is for you to learn how to write both, then later in the course we will go
over more of the detailed differences and you will begin to understand what kinds of programs
should be applications and what kinds should be Applets.
Page 13
OOP Handout
We will walk through the steps involved in executing the first sample program. What we outline here
are the overall steps in the edit-compile-run cycle common to any Java development tool you use. You
need to get detailed instructions on how to use your chosen development tool to actually run programs.
The steps we present in this section should serve as a guideline for more detailed instructions specific
to your program development tool.
Step 1
Type in the program, using an editor, and save the program to a file. Use the name of the main class
and the suffix .java for the filename. This file, in which the program is in a human-readable form, is
called a source file.
/*
Sample Program: Displaying a Window
File: Sample1.java
*/
import javax.swing.*;
class Sample1 {
public static void main( String[] args ) {
JFrame myWindow;
myWindow = new JFrame();
myWindow.setSize(300, 200);
myWindow.setTitle("My First Java Program");
myWindow.setVisible(true);
}
}
Step 2
Compile the source file. Many compilers require you to create a project file and then place the source
file in the project file in order to compile the source file. When the compilation is successful, the
compiled version of the source file is created. This compiled version is called bytecode, and the file that
contains bytecode is called a bytecode file. The name of the compiler-generated bytecode file will have
the suffix .class while its prefix is the same as the one for the source file.
Page 14
OOP Handout
When any error occurs in a program, an error message will be displayed. If the sample program
contains no errors in syntax, then instead of an error message, you will get nothing or a message stating
something like “Compiled successfully.” To see what kind of error messages are displayed, try
compiling the following program. We purposely introduced three errors. Can you find them? Make sure
to compile the correct Ch2Sample1 again before you proceed to the next step.
Errors detected by the compiler are called compilation errors. Compilation errors are actually the
easiest type of errors to correct. Most compilation errors are due to the violation of syntax rules.
Step 3
Execute the bytecode file. A Java interpreter will go through the bytecode file and execute the
instructions in it. If your program is error-free, a window will appear on the screen.
Page 15
OOP Handout
If an error occurs in running the program, the interpreter will catch it and stop its execution. Errors
detected by the interpreter are called execution errors. If you did not see the expected results, go back
to the previous steps and verify that your program is entered correctly. If you still do not see the
expected results, then most likely your development environment is not set up correctly. Please refer to
other sources of information for further help.
Let„s get familiar with various terminologies used by java programmers.
JDK (Java Development Kit): JDK contains JRE along with various development tools like Java
libraries, Java source compilers, Java debuggers, bundling and deployment tools
JRE (Java Runtime Environment): It is part of JDK but can be used independently to run any byte
code (compiled java program). It can be called as JVM implementation.
JVM (Java Virtual Machine): „JVM‟ is software that can be ported onto various hardware platforms.
JVM will become instance of JRE at run time of java program. Byte codes are the machine language
for the JVM. Like a real computing machine, JVM has an instruction set which manipulates various
memory areas at run time. Thus for different hardware platforms one has corresponding
implementation of JVM available as vendor supplied JREs.
Java API (Application Programming Interface): Set of classes written using Java programming
language which runs on JVM. These classes will help programmers by providing standard methods like
reading from console, writing to console, saving objects in data structure etc.
Page 16