Dr. Samit BhattacharyaAssistant Professor,Dept. of Computer Science and Engineering,IIT Guwahati, Assam, India
NPTEL Course on
Human Computer Interaction- An Introduction
Dr. Pradeep YammiyavarProfessor,Dept. of Design,IIT Guwahati, Assam, India
Indian Institute of Technology Guwahati
Module 9: Object Oriented Programming
Lecture 1: Object Oriented Programming
- an Introduction
Dr. Pradeep Yammiyavar
The inputs & assistance to this module by Mr.Yogesh Deshpande, PhD scholar at HCI-UE- Lab, IITG, (2010 – 2013) is acknowledged with thanks
Overview• Procedural Programming Paradigm - PPP• Object-Oriented Programming Paradigm - OPP• Objects
•State and Behavior • Software Objects - Fields and Methods • Data Encapsulation• Public Interface • Object-based application• Benefits of object-based application development
• Classes• Definition• Blueprint of similar object• Instantiating objects from class - example
• Object-Oriented Principles•Encapsulation•Inheritance and Interfaces •Polymorphism
• Packages and API
Procedural Programming Paradigm (PPP)• In this paradigm (functional paradigm) the programming unit is a function.• Program is divided into self-contained and maintainable parts called ‘modules’ (e.g. A,B,C,D).• A module contains procedures - self-contained code that carries out a single task (e.g. X,Y,Z).• A function (e.g. P, Q) is a self-contained code returning value to the calling procedure (e.g. Y).• In PPP all computations are done by applying functions.• Procedural paradigm separates data of program from instructions that manipulate the data.
Module A
Module B
Module C
Module D
Application
Procedure Y
Procedure X
Procedure Z
Module C
Function P Function Q
Procedure Y
Application is divided into 4 modules Module C carries out 3 tasks (X,Y,Z) Procedure Y calls function P and Q
data codeData in Data out
Function (processes the data)
Object Oriented Programming Paradigm (OOPP)• Paradigm describes a system as it exists in real life based on interactions among real objects.• Application is modeled as collection of related objects that interact and do your work (task).• The programming unit is a class representing collection of similar real world objects.• Programming starts with abstraction of useful real world objects and classes.• Application is divided into multiple packages (e.g. A,B,C,D).• A package is a collection of classes (e.g. P,Q,R) fulfilling group of tasks or functionality. • A class is an encapsulated(data + code) definition of collection of similar real world objects.• OOPP binds together data and the instructions that manipulate the data into a class.
Application is collection of 4 packages Package B contains 3 classes (P,Q,R)
Class R encapsulates 7 methods( m1.. m7) and 3 attributes ( x, y, z)
Package A
Package C
Package B
Package D
Application Package B
Class P
Class Q
Class R
Class R
Data x , y , z
m1()m2()
m3()
m4()m5()
m6()
m7()
Object A
Message to invoke m4() (Ask object X to do task m4)
Data / Object out
Object (encapsulates data+code)
Data3,8,1
00
Object X of Class R
Objects Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects
Real-world objects share two characteristics: They all have state and behavior
State Name ColorBreedHungry
Behavior BarkingFetchingWagging Tail
DOG
State Current Gear Current SpeedCurrent Pedal Cadence ( rhythm )
Behavior Changing gearChanging pedal cadenceApplying brakes
BICYCLE
Objects
State ?
Behavior ?
State ?
Behavior ?
TABLE LAMP DVD PLAYER
Objects Try and identify the State & behavior of the two objects .
Answer in the next slide
State On/Off
Behavior Turning OnTurning Off
State On /OffCurrent Volume Current Station
Behavior
Turn onTurn offIncrease volumeDecrease volume,SeekScanTune
TABLE LAMP DVD PLAYER
Objects
Software Object
An object stores its state / information in fields (attributes ) and exposes its behavior through methods ( member functions )
Software Objects - fields and methods
Objects methods can only change object's internal state. Hiding this internal state & requiring all interaction to be performed through an object's methods is known as data encapsulation
Objects - Data Encapsulation
Window Object
Height as real = 32.15Width as real = 10.15Color as string = “Red”Location as point = 15,25
Change_height()
Change_width()
Maximize()
Change_location()
Minimize()
Objects – Data Encapsulation
Other objects can change the state of an object by using only those methods that are exposed to the outer world through a public interface. This help in data security.
Object is an encapsulation of data (attributes) as well as methods (functions)
Curr volumeCurr channel Power Etc ……….
Private initialize()
Private decode ()
private modulate()
Public Volume+()Public
SetChannel()
Public TurnOff()
Public TurnOn()
Interface IA
Object Set Top Box
Public Volume-()
Turn On
Turn OffVolume
Objects - Public Interface
Other objects can change the state of an object by using only those methods that are exposed to the outer world through an public interface. This help in data security.
Object is an encapsulation of data (attributes) as well as methods (functions)
Interface IA
X , Y , Z , Avg
Public getX()
Public getY()
public getZ()
Public SetX()Public
SetY()
Public SetZ()
Private Average()
Object A
Setx(real)Sety(real)Setz(real)Getx()Gety()Getz()
Objects - Public Interface
Object-based application
Power Circuit
Audio Amplifier
Tuner
Receiver
IF Amplifier
InterfaceIPowerCircuit
InterfaceIAmplifier
InterfaceIAudio
User Interface
+
Turn On/OFF
-
Volume+ Volume-
Tuning
Electronic Components Connectors / Interfaces
• Modularity: Source code for an object can be maintained independently in a class. Once
created, an object can be easily passed around inside the system. E.g. ClassMaths, Class string , ClassWindow etc
• Information-hiding:By interacting only with an object's methods, the details of its internal
implementation remain hidden from the outside world. E.g. Interface IMaths , Interface IString Interface IWindow
• Code re-use:If an object already exists (perhaps written by another software developer), you
can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
e.g. Standard Classes available packages which can reused using their interfaces.
• Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
Benefits of object-based application development
Class
Animals
Birds
Airplanes
VehiclesAnimalsStationary
Humans
Flowers
Collection of objects that share common attributes and behavior (methods)
Class Animal
Attributes
Behavior
Class Vehicle
Attributes
Behavior
Class - Structure
Factory of cycles of same make and model with same features and same components . Built from same blueprint. This blueprint is called a Class. Class Cycle
Used to create all other cycles
In object-oriented terms, we say that your cycle is an instance of the class of objectsknown as cycles
A class is the blueprint from which individual objects are created.
The attributes and operations defined by a class are for its objects, not for itself.
A class is a logical construct, an object has physical reality.
Class - Blueprint of similar object
class Cycle { int cadence = 0;
int speed = 0; int gear = 1;
void changeCadence(int newValue) { cadence = newValue; }
void changeGear(int newValue) { gear = newValue; }
void speedUp(int increment) { speed = speed + increment; }
void applyBrakes(int decrement) { speed = speed - decrement; }
void printStates() { System.out.println("cadence:"+cadence+"
speed:"+speed+“ gear:"+gear); } }
Cadence=15Speed=2kph
Gear=4
changeCadence
printStateschangeGear
applyBrakesspeedUp
Cadence=10Speed=5kph
Gear=3
changeCadence
changeGear
applyBrakesspeedUp
ObjectsCycle1
& Cycle2
Class Cycle
int Cadence int Speed int Gear
void changeGear(int)void printStates(int)void speedUp(int)void applyBrakes(int)void changeCadence()
Defines InteractionWith World viz interface
Represents State
cycle1 and cycle2 are instances of Class Cycle
Classes are passive and which do not communicate but are used to create (instantiate) objects which interact.
The responsibility of creating and using new Cycle objects belongs to some other class in your application.
Class Definition – Example
Cycle Demo class that creates two separate cycle objects and invokes their methods:
Class CycleDemo{
public static void main(String[] args) { // Create two different Bicycle
objects Bicycle bike1 = new Bicycle();Bicycle bike2 = new Bicycle();
// Invoke methods on those objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates();
bike2.changeCadence(50); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates();
} } This program is stored in file CycleDemo.java
Main Class - Is a class that contains one method, called main. The main method contains a series of instructions to create objects and to tell those objects to do things. Setting an Application's Entry Point
Define Main ClassClass with main() method
Create instances of required objects
Write instructions for object communication to
build applications
Delete objects created
Class Math
Class Stat
Class Draw
Interface IMath
Interface IMath
Interface IMath
Java APIs
Java Packages
Programming Support
Instantiating objects from class
• Encapsulation is the mechanism that binds together the code and the data it manipulates, and keeps both safe from outside interference and misuse
Object-Oriented Principle – Encapsulation
Private Data
Private Functions
Public Data
Public Functions
Private Area
Public Area
No Entry
Entry Allowed
X
Object-Oriented Principle – Inheritance
Mountain bikes, road bikes, and tandem bikes all share the characteristics of bicycles (current speed, current pedal cadence, current gear).
Yet each has some features that makes them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.
In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike.
Creating subclass - at beginning of class use the extends keyword, followed by name of the class to inherit from:
class MountainBike extends Bicycle{
// new fields and methods defining a mountain bike would go here }
Inheritance is the process by which one object acquires the properties of another object. By use of inheritance, an object need only define all of its characteristics that make it unique within its class, it can inherit its general attributes from its parent. This will be clear from the following example
Interfaces • Public methods form the object's interface with the outside world• Interface is a group of related methods with empty bodies ( pure virtual functions )
Class Soiree Hotel
Class Office Canteen
Client_1
Client_2
Dosa
Idli
Tea
Coffee
Ice-Cream
Bournvita
Pepsi
Soup
Pudding
Menu- Publicly Available Items
Interface IKitchen• constant - should not change• defines behavior • does not have implementation• client not bothered of implementation
Implementation_1
Implementation_2
• Public methods form the object's interface with the outside world• Interface is a group of related methods with empty bodies ( pure virtual functions )
Class Dot Matrix
Class InkJet
+5V
Gnd
X
X
TxD
RxD
DTS
CTS
X
Interface IPrinter
CPUImplementation_2
Implementation_1
Uses Iprinterto connect
Interfaces
• A bicycle's behavior, if specified as an interface, might appear as follows
Interface IBicycle{
void changeCadence(intnewValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
void printStates() }
IBicycle
To implement interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration
Class Bicycle implements IBicycle{
int cadence = 0;int speed = 0; int gear = 1;
void changeCadence(int newValue) { cadence = newValue; }
void changeGear(int newValue) { gear = newValue; }
void speedUp(int increment) { speed = speed + increment; }
void applyBrakes(int decrement) { speed = speed - decrement; }
void printStates() {
System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear); }
}
Implementation in Class
e.g. Class Soiree implements IKitchen
Class as implementation of interface
Interfaces define an application
Implements IA
Implements ICImplements ID Implements IE
Implements IBA
C
D
Uses IA
Uses IB
Uses ID
Uses IC
EUnused
Server Object Client Object
• An interface makes a class formal about the behavior it promises to provide.
• Interfaces form a contract between the class and the outside world and this contract is enforced at build time by the compiler.
• If your class claims to implement an interface, all methods defined by that interface must appear in its source
code before the class will successfully
compile.
Polymorphism (from Greek, meaning ‘many forms’) is a feature that allows same interface
(method name) to be used for a multiple class of actions depending on context.
Object-Oriented Principle – Polymorphism
sound()
sound(){
meow }
sound(){
bark }
ANIMAL
CAT DOG
Examples shows same name of method i.e. sound() but different implementations in CAT and DOG
Packages and API • A package is a namespace that organizes a set of related classes and interfaces
like a folder • Software written in the Java programming language can be composed of hundreds or
thousands of reusable classes, it makes sense to keep things organized by placing related classes and interfaces into packages.
• Java Platform provides Class library which has huge number of classes organized inpackages which is also called API.
Java.awt
Cla
ss L
ibra
ry a
s c
olle
ctio
n of
pac
kage
s
Application_1
Application_2
Application_3
Application Programming Interface (API)(Standard nuts and bolts)
Java
AP
Is
Java.util
Java.swing
Java.rmi
Java.sql
Java.security
There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work.
ReferencesBooks• The Object-Oriented Thought Process by Matt Weisfeld, Publisher: Addison-Wesley
Professional • Head First Object-Oriented Analysis & Design by Gary Pollice, David West, Brett D
McLaughlin , Publisher: Shroff O Reilly
• Experiencing Object Oriented Concepts: For Beginners by John E. Mathew
Ueful Links
http://scg.unibe.ch/archive/osg/Nier89aSurveyOfOOConcepts.pdf
http://www.codeproject.com/Articles/15874/Understanding-Object-Oriented-Concepts
http://www.slideshare.net/bgjeecourse/objectoriented-concepts-5576132
http://www.youtube.com/watch?v=3bMsY5a7cBo