Chapter- 1 Introduction to Object-Oriented Programming
Chapter- 1 Introduction to Object-Oriented Programming
OOP- CoSc3112 1
Introduction to Object-
Oriented Programming
OOP - CoSc2051 2
Introductions
• Chapter 1: Introduction to OOP
– Types of programming paradigms
– Overview of OO principles
– Editing, Compiling and Interpreting
OOP - CoSc2051 3
Introductions
All computer programs consist of two elements: code and data.
A Programming language is a notational system for describing
tasks/computations in a machine and human readable form.
Most computer languages are designed to facilitate certain operations
and not others:
numerical computation, or text manipulation, or I/O.
More broadly, a computer language typically embodies a particular
programming paradigm.
Which programming language?
OOP - CoSc2051 4
Introductions
• What is a "programming paradigm"?
– Paradigm: "A philosophical and theoretical framework of a scientific school or
discipline within which theories, laws, and generalizations and the experiments
performed in support of them are formulated;
– broadly: a philosophical or theoretical framework of any kind“
• Paradigms as “ways of organizing thought”
– Programming paradigm = The basic structuring of thought underlying the
programming activity.
• E.g.. when you think of a programming problem, what are you thinking
of?
– the sequence of actions to perform (first download the file, then display it)
– how to divide the problem-space into sub-tasks (to compute the spanning tree, i can divide the
graph arbitrarily in two, and then …)
– what are the agents involved (sensors, a simulator, a renderer, …)
– what data do we need to handle? do we need intermediate representations? what are the
relations between the different forms?
OOP - CoSc2051 5
Programming Paradigms : PL
Since a task can be solved in different ways (paradigms), the language
used to describe the solution differs in abstractions, structures
due to the way in which the problem is solved.
A programming paradigm is a fundamental style of computer
programming.
Programming paradigms differ in:
– The concepts and abstractions used to represent the elements
of a program (such as objects, functions, variables,
constraints, etc.)
– The steps that compose a computation (assignation, evaluation,
data flow, control flow, etc.).
OOP - CoSc2051 6
Programming Paradigms : PL
.
Imperative/ Object
Algorithmic Declarative Oriented
Functional Logic
Programming Programming
Algol Lisp Prolog Smalltalk
Cobol Haskell Simula
PL/1 ML C++ , C#
Ada Miranda Java ,VB
C APL
Modula-3
OOP - CoSc2051 7
Imperative paradigms
It is based on commands that update variables in storage.
The main : Explicitly tells the computer "how" to accomplish it.
The Latin word imperare means “to command”.
E.g GO TO command
It works by changing the program state through assignment statements.
It performs step by step task by changing state.
The paradigm consist of several statements and after execution of all
the result is stored.
Includes procedural & structured programming.
Many people also find the imperative paradigm to be a more natural
way of expressing themselves.
OOP - CoSc2051 8
Imperative paradigms
Advantages :
Efficient;
Close to the machine;
Popular; Familiar.
Disadvantages :
The semantics of a program can be complex to understand or
prove
debugging is harder;
Abstraction is more limited than with some paradigms;
Order is crucial, which doesn't always suit itself to problems.
Parallel programming is not possible
OOP - CoSc2051 9
Imperative paradigms
Examples of Imperative programming paradigm:
C : developed by Dennis Ritchie and Ken Thompson
Fortran : developed by John Backus for IBM
Basic : developed by John G Kemeny and Thomas E Kurtz
// 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;
OOP - CoSc2051 10
Imperative paradigms
Imperative programming is divided into three broad categories:
Procedural, OOP and parallel processing.
Procedural programming paradigm
This paradigm emphasizes on procedure in terms of under lying
machine model.
There is no difference in between procedural and imperative
approach.
It has the ability to reuse the code and it was boon at that time
when it was in use because of its reusability.
PP is a derivation of IMP , adding to it the feature of functions
(also known as "procedures" or "subroutines").
OOP - CoSc2051 11
Imperative paradigms
Imperative programming is divided into three broad categories:
Procedural, OOP and parallel processing.
Procedural programming paradigm
Examples of Procedural programming paradigm:
C : developed by Dennis Ritchie and Ken Thompson
C++ : developed by Bjarne Stroustrup
Java : developed by James Gosling at Sun Microsystems
ColdFusion : developed by J J Allaire
Pascal : developed by Niklaus Wirth
OOP - CoSc2051 12
Imperative paradigms
Imperative programming is divided into three broad categories:
Procedural, OOP and parallel processing.
Procedural programming paradigm
Examples of Procedural programming paradigm:
include <iostream>
using namespace std;
int main() {
int i, fact = 1, num;
cout << "Enter any Number: ";
cin >> number;
return 0;
}
OOP - CoSc2051 13
Declarative Programming
Declarative programming is the opposite of imperative programming
in the sense that the programmer doesn't give instructions about
how the computer should execute a task, but rather on what result
is needed.
Declarative languages aim to bring programming languages closer to
human language and thinking.
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 emphasize on what code is actually doing.
It just declares the result we want rather how it has be produced.
OOP - CoSc2051 14
Functional programming paradigms
In this paradigm we express computations as the evaluation of
mathematical functions.
Functional programming paradigms treat values as single entities.
Unlike variables, values are never modified.
Instead, values are transformed into new values.
Computations of functional languages are performed largely through
applying functions to values,.
It uses functions to perform everything.
It is a form of declarative programming.
In this, the command execution order is not fixed.
OOP - CoSc2051 15
Functional programming paradigms
Advantages:
The high level of abstraction, removes the possibility of committing many
classes of errors;
The lack of dependence on assignment operations, allowing programs to be
evaluated in many different orders.
This evaluation order independence makes function-oriented languages
good candidates for programming massively parallel computers;
The absence of assignment operations makes the function-oriented programs
much more amenable to mathematical proof and analysis than are imperative
programs.
Disadvantages:
Perhaps less efficiency
Problems involving many variables or a lot of sequential activity that are
sometimes easier to handle imperatively or with object-oriented programming.
OOP - CoSc2051 16
Logic programming paradigms
The LP takes a declarative approach to problem-solving.
Various logical assertions about a situation are made, establishing all
known facts.
Then queries are made.
The role of the computer becomes maintaining data and logical
deduction.
Logical Paradigm Programming:
A logical program is divided into three sections:
1. A series of definitions/declarations that define the problem
domain
2. Statements of relevant facts
3. Statement of goals in the form of a query
OOP - CoSc2051 17
Logic programming paradigms
While the functional paradigm emphasizes the idea of a
mathematical function, the logic paradigm focuses on predicate
logic, in which the basic concept is a relation.
Logic languages are useful for expressing problems where it is not
obvious what the functions should be.
For example consider the uncle relationship:
a given person can have many uncles, and another person can be
uncle to many nieces and nephews.
Let us consider now how we can define the brother relation in
terms of simpler relations and properties father, mother, and male.
Using the Prolog logic language one can say:
OOP - CoSc2051 18
Logic programming paradigms
clauses
brother(X,Y) :- /* X is the brother of Y */
/* if there are two people F and M for which*/
father(F,X), /* F is the father of X */
father(F,Y), /* and F is the father of Y */
mother(M,X), /* and M is the mother of X */
mother(M,Y), /* and M is the mother of Y */
male(X). /* and X is male */
Predicates
mother(sara, jack). /* sara is the mother of jack */
is fact.
Query
? mother(sara, jack).
Yes
OOP - CoSc2051 19
Logic programming paradigms
Advantages:
system solves the problem, so the programming steps themselves
are kept to a minimum;
Proving the validity of a given program is simple.
OOP - CoSc2051 20
The Object-Oriented Paradigm
Object Oriented Programming (OOP) is a paradigm in which real-
world objects are each viewed as separate entities having their own
state which is modified only by built in procedures, called methods.
Alan Kay characterized the fundamental of OOP as follows:
– Everything is modeled as object
– Computation is performed by message passing:
• objects communicate with one another via message passing.
– Every object is an instance of a class where a class represents a
grouping of similar objects.
– Objects are organized into classes, from which they inherit
methods and equivalent variables.
OOP - CoSc2051 21
Fundamental Principles of OOP
1. Objects
2. Classes
3. Methods and Messages
4. Abstraction
5. Inheritance
6. Encapsulation
7. Polymorphism
OOP - CoSc2051 22
OOP Concepts
In object-oriented programming (OOP), programs are organized into
objects.
The properties of objects are determined by their class
Objects act on each other by passing messages.
Object
Definition:
An object is a software bundle that has State and Behavior.
Software Objects are often used to model real-world objects.
Example:
dogs have states (name, color, hungry, breed) and
behaviors (bark, fetch, and wag tail).
OOP - CoSc2051 23
Object Examples
Example 1: Dogs
States: name, color, breed, and “is hungry?”
Behaviors: bark, run, and wag tail
Example 2: Cars
States: color, model, speed, direction
Behaviors: accelerate, turn, change gears
OOP - CoSc2051 24
Class
Definition: A class is a blueprint that defines the states and the
behaviors common to all objects of a certain kind.
In the real world, you often have many objects of the same kind.
For example, a guard dog, herding dog, snoop dog . . .
Even though all dogs have four legs, and bark, each dog’s behavior is
independent of other dogs.
For example:
class Dog {
Dog #1 is a black Poodle,
// state and behavior
Dog #2 is a red Irish Setter
}
OOP - CoSc2051 25
Methods
An Object's behavior is defined by its methods
Methods, like fields, are written inside the braces of the class
Methods can access the fields (the state) of their object and can
change them
class Dog {
String name; // field
// behavior
public void bark()
{
...
}
}
OOP - CoSc2051 26
Message
Definition: Software objects interact and communicate with each
other by sending messages to each other.
Example: when you want your dog to gather a herd of goats, you
whistle and send him out.
OOP - CoSc2051 27
Inheritance
Inheritance is a mechanism in which one object acquires all the
states and behaviors of a parent object.
Inheritance allows child classes inherits the characteristics of
existing parent class
Attributes (fields and properties)
Operations (methods)
Child class can extend the parent class
Add new fields and methods
Redefine methods (modify existing behavior)
A class can implement an interface by providing implementation for
all its methods.
Inheritance is same as specialization.
OOP - CoSc2051 28
Inheritance
Inheritance terminology
base class /
derived class inherits parent class
OOP - CoSc2051 30
Inheritance – Example
Base class
. Person
+Name: String
+Address: String
Employee Student
+Company: String +School: String
+Salary: double
OOP - CoSc2051 31
Encapsulation
Encapsulation is a process of wrapping code and data together
into a single unit.
Encapsulation is the process of grouping data in a single section.
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.
OOP - CoSc2051 32
Encapsulation – Example
Example: Complete television is single box where all the
mechanism are hidden inside the box all are capsuled.
Data fields are private.
Constructors and accessors are defined (getters and setters)
Person
-name : String
-age : TimeSpan
+Person (String name, int age)
+Name : String { get; set; }
+Age : TimeSpan { get; set; }
OOP - CoSc2051 33
Encapsulation – Benefits
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.
We can make a class read-only or write-only:
For a read-only a getter method and
For write-only a setter method will be used.
OOP - CoSc2051 34
Polymorphism
Polymorphism is a concept in which we can execute a single operation
in different ways.
Polymorphism is same as generalization.
Polymorphism ability to take more than one form (objects have
more than one type)
A class can be used through its parent interface
A child class may override some of the behaviors of the parent class
Polymorphism allows abstract operations to be defined and used.
Abstract operations are defined in the base class' interface and
implemented in the child classes
Declared as abstract or virtual
OOP - CoSc2051 35
Polymorphism
Why handle an object of given type as object of its base type?
– To invoke abstract operations
– To mix different related types in the same collection
E.g. List<object> can hold anything
– To pass more specific object to a method that expects a
parameter of a more generic type
– To declare a more generic field which will be initialized and
"specialized" later
OOP - CoSc2051 36
Polymorphism
Figure Abstract
. action
+CalcSurface() : double
Concrete
class Square Circle
-x : int -x : int
-y : int -y : int
Overriden -size : int -radius: int Overriden
action action
OOP - CoSc2051 37
Abstraction
Abstraction is a process of hiding the implementation details
and showing only functionality to the user.
Abstraction means hiding internal details and showing the required
things.
– E.g.: pressing the accelerator will increase the speed of a car.
– But the driver doesn’t know how pressing the accelerator
increases the speed – they don't have to know that.
Technically abstract means something incomplete or to be
completed later.
In Java, we can achieve abstraction in two ways:
– abstract class (0 to 100%) and interface (100%).
OOP - CoSc2051 38
Overview of Java Programming
Java is an object-oriented programming language
The Java programming language was created by Sun Microsystems,
Inc.
It was introduced in 1995 and it's popularity has grown quickly since
Its primary feature is that it could function nicely in a networked
environment.
The explosion of WWW created an environment in which the
language could live.
OOP - CoSc2051 39
Overview of Java Programming
Java technology can be seen as both a language and a platform.
Using it you can write applications that can run on practically any
device, including a PC, PDA, a cellular phone or a television.
The Java platform is formed from two components:
– The Java application programming interface (Java API)
Set if libraries that are used to accomplish tasks such as
creating GUIs, performing file I/O and establishing network
comm.
– The Java Virtual Machine (JVM)
Is in charge of executing your code in a specific environment.
OOP - CoSc2051 40
Characteristics of Java
Java Is Simple
Java Is Object-Oriented
Java Is Distributed
Java Is Interpreted
Java Is Robust
Java Is Secure
Java Is Architecture-Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
OOP - CoSc2051 41
Java Program Structure
In the Java programming language:
– A program is made up of one or more classes
– A class contains one or more methods
– A method contains program statements
These terms will be explored in detail throughout the course
A Java application always contains a method called main
OOP - CoSc2051 42
Java Program Structure
// comments about the class
.
public class MyProgram
{
OOP - CoSc2051 43
Development Environments
There are many tools to do java programming, to the very least you
need to have
Sun Java Development Kit (JDK/ Recent version JDK 8)
Text editor such as Microsoft Notepad
Integrated Development Environment IDE for Java
NetBeans (from Sun/Oracle)
Eclipse (from IBM) IntelliJ
Borland JBuilder Android Studio and
BlueJ Many others
JCreator
DrJ
OOP - CoSc2051 44
The Compiler and the Java Virtual Machine
A programmer writes Java programming statements for a program called
source code
A text editor is used to edit and save a Java source code file.
Source code files have a .java file extension.
A compiler is a program that translates source code into an executable
form.
A compiler is run using a source code file as input.
Syntax errors caught during compilation if exist.
Syntax errors are mistakes that violate the rules of the
programming language.
Compiler creates another file that holds the translated instructions
and it is called byte code.
OOP - CoSc2051 45
The Compiler and the Java Virtual Machine
A program written in a high-level language like java is called a source
program.
Since a computer cannot understand a source program. Program
called a compiler is used to translate the source program into a
machine language program called an object program.
The object program is often then linked with other supporting
library code before the object can be executed on the machine.
OOP - CoSc2051 46
The Compiler and the Java Virtual Machine
Most compilers translate source code into executable files containing
machine code.
The Java compiler translates a Java source file into a file that contains
byte code instructions.
Byte code files end with the .class file extension.
Byte code instructions are the machine language of the Java Virtual
Machine (JVM) and cannot be directly executed by the CPU.
The JVM is a program that emulates a micro-processor.
The JVM executes instructions as they are read.
JVM is often called an interpreter.
Therefore, Java is both compiled and interpreted language.
OOP - CoSc2051 47
Compiling Java Source Code
With Java, you write the program once, and compile the source
program into a special type of object code, known as bytecode.
The bytecode can then run on any computer with a Java Virtual
Machine, as shown below.
Java Virtual Machine is a software that interprets Java bytecode.
Java Bytecode
Java Virtual
Machine
Any
Computer
OOP - CoSc2051 48
Program Development Process
OOP - CoSc2051 49
Multiple Compilers
Because different operating systems (Windows, Macs, Unix) require
different machine code, you must compile most programming
languages separately for each platform.
Unix
compiler
program
compiler MAC
compiler
Win
OOP - CoSc2051 50
Your First Java Program
Open your text-editor and type the following piece of Java code
exactly:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
OOP - CoSc2051 51
Compiling and Running Your First Program
Open the command prompt in Windows
To run the program that you just wrote, type at the command prompt:
cd c:\java
Your command prompt should now look like this: c:\java>
To compile the program that you wrote, you need to run the Java
Development Tool Kit Compiler as follows:
At the command prompt type: c:\java> javac HelloWorld.java
You have now created your first compiled Java program named
HelloWorld.class
To run your first program, type the following at the command prompt:
c:\java>java HelloWorld
Although the file name includes the .class extension , this part of the name
must be left off when running the program with the Java interpreter.
OOP - CoSc2051 52
Creating, Compiling, and Running Programs
Result
OOP - CoSc2051 53
Types of Java Program
Types All Java programs can be classified as Applications and
Applets.
Java applications are large programs that run stand-alone,
with the support of a virtual machine.
Applet is a relatively small Java program executed under the by a
browser (inside an appletviewer).
Applets are great for creating dynamic and interactive web
applications of Java Program.
Advantages of Applets
OOP - CoSc2051 54
Types of Java Program
Advantages of Applets :
Execution of applets is easy in a Web browser and does not
require any installation or deployment procedure in real-time
programming (where as servlets require).
Writing and displaying (just opening in a browser) graphics and
animations is easier than applications.
In GUI development, constructor, size of frame, window closing
code etc. are not required (but are required in applications).
OOP - CoSc2051 55
Types of Java Program
OOP - CoSc2051 56
End of Chapter 1
OOP - CoSc2051 57