Uploaded by gihiran385

OOP slides

advertisement
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
Introduction
BITS Pilani
Hyderabad Campus
Computer System
What a computer system includes
 Processor(CPU)
 Memory
 Input- Key board, Mouse etc.
 Output- Monitor, Printer etc.
 Memory (sec) and
 SW
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Computers for Solving Problems





Problem statement
Algorithm
Program
Machine instructions
Execution
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Algorithm
Is a step-by-step procedure (to solve problems)
generated to terminate such that each step is
precisely stated and carried out by the
computer.
Is a finite set of instructions which if followed
accomplishes a particular task.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Requirements
Criteria to be satisfied by any Algorithm
1. Input
2. Output
3. Definiteness – Each instruction must be clear and
unambiguous.
4. Finiteness- The algorithm must terminate after a finite
no. steps.
5. Effectiveness- Every instruction must be sufficiently
basic and must be feasible.
Program – need not satisfy (4)
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Describing an Algorithm
1.Use of natural language such as English
(should be unambiguous)
2.Graphical form- Flowchatrts
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Algorithm for obtaining Coke from a vending machine
Step 1: Start(at vending machine)
Step 2: If coke available go to 3 else go to 10
Step 3: Search pockets for change
Step 4: If change available go to 5 else borrow from others
and go to 5
Step 5: Enter coins
Step 6: If Money is accepted go to 7 else press coin
release and go to 5
Step 7: Press button
Step 8: If drink appears go to 9 else go to 10
Step 9: Drink coke
Step 10: Give up
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Low-level Language
Low-level Language is tied to the computer hardware
(machine dependent).
Each computer (HW) will have one such low-level language
we call such language as Assembly Language ( in
addition to its Machine Language).
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
High-level Language
High-level Languages are at a distance from the
computer(machine independent)
Each computer (HW) will have one such low-level language
we call such language as Assembly Language.
High-level programming languages allow the specification
of a problem solution in terms closer to those used by
human beings.
These languages were designed to make programming far
easier, less error-prone and to remove the programmer
from having to know the details of the internal structure
of a particular computer.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C=A+B
which is obviously much more readable, quicker to write
and less error-prone.
As with assembly languages the computer does not
understand these high-level languages directly and
hence they have to be processed by passing them
through a program called a compiler which translates
them into internal machine language before they can be
executed.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Advantages of High-level
Programming Languages
High-level languages allow us to use symbolic
names for values.
High-level languages provide expressiveness.
 High-level languages enhance readability.
High-level language provide abstraction of the
underlying HW.
High-level languages safeguard against bugs.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Some important Programming
Languages
BASIC, PROLOG, LISP
C,
C++,
Cobol,
FORTRAN,
Java,
Pascal,
Perl,
PHP,
Python,
Ruby, and Visual Basic.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Usage
COBOL
Business applications
FORTRAN
PASCAL
C & C++
PROLOG, LISP
JAVA
Engineering & Scientific Applications
General use and as a teaching tool
General Purpose - currently most popular
Expert Systems; Artificial Intelligence
General Purpose - gaining popularity rapidly
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
The Background
We write programs in some language to give instructions to
the computer to perform a specific task (functionality).
Now we consider High-level programming languages only.
All of us have good acquaintance with C-Language.
C- language is a high level language.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
/* My First Program */
void main( )
{
printf(“My Name Is Ravi”);
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
/* HelloWorld – An example program */
#include <stdio.h>
main( )
{
printf(“Hello, world!\n”);
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Sample C Program
/* INVESTMENT PROBLEM */
/* Written by Dr. R. Gururaj */
#include <stdio.h>
#define PERIOD 10
/*Symbolic constant */
#define PRINCIPAL 5000.00
/*Symbolic constant */
void main( )
{ int year;
float amount, value, inrate;
number=100; amount=PRINCIPAL;
inrate=0.11; year=0;
while(year <= PERIOD)
{
printf(“%d %f\n”, year, amount);
value=amount + inrate*amount;
year=year+1;
amount=value;
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
/* Illustration for use of sub-routine*/
/* Written by Dr. R. Gururaj */
#include <stdio.h>
int mul(int x, int y);
/*Function declaration*/
void main( )
{
int a, b, c;
a=4;
b=7;
c= mul(a,b);
printf(“Multiplication of %d and %d is: %d”, a,b,c);
}
int mul(int x, int y)
{
int p;
p=x*y;
return p;
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Features of C-Language
A. Robust - It has a rich set of built-in functions & operators
helping in writing complex programs
B. Suitable for writing both System & Application SW
C. Efficient & fast
D. Portable- Any C program written on one computer can be
run on another computer with minimal or no modifications.
E. Well suited for structured programming, requiring the user
to think of a problem in terms of function modules or
blocks. A proper collection of this modules would make a
complete program.
F. Extendable- new functions can be added to C libraries
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Features of C-Language
A. Library functions
B. Different data types
C. Operators
D. Declaration of variables, constants
E. Storage classes (auto, register, static, extern)
F. IF-THEN-ELSE, FOR loop, DO WHILE, SWITCH-CASE
G.Functions to perform specific tasks
H. STRUCTURE and UNION
I. Memory allocation (malloc and calloc)
J. Pointers
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Observation
All computer programs have two important elements: Code
and Data.
void main( )
{
int length, breadth, age, rank, area;
length=10; breadth=5; age=15; rank=8;
area= compute_area(length, breadth);
printf(“Area of the shape is: %d”, area);
}
int compute_area(int l, int b)
{
int a;
p=l*b;
return a;
}
This is way of programming is known as Process-Oriented
approach.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Observation
This can be characterized as code acting data.
If by mistake if we pass on some invalid data values to the
function (which is semantically wrong), still the code acts on
the data without discrimination.
void main( )
int length, breadth, age, rank, area;
length=10; breadth=5; age=15; rank=8;
area= compute_area(age, rank);
printf(“Area of the shape is: %d”, area);
}
int compute_area(int l, int b)
{
int a;
p=l*b;
return a;
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Observation
As long as the size (number of lines) of the code is within
some limits it is OK.
But when it increases in size i.e., more that 5000Lines, it
becomes difficult to keep track of what data is passed on to
what code(function).
Because the complexity increases drastically. Programmers
can make mistakes.
Debugging and Maintenance teams face a lot of hardship.
All declarations happen in the beginning of the code.
For what data we are invoking the function?
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Observation
In the Process-Oriented approach, the focus is on what is
happening? But not who is being affected.
For what entity/object, am I executing the code, not clear.
Humans understand the world in terms of entities or objects.
This problem can be solved by use of Structures to some
extent but not completely.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Process oriented
programming
 The problem is viewed as a sequence of things to be
done.
 A number of functions are written to accomplish this.
 The primary focus is on functions.
 Can be thought of as code acting on data.
 We just concentrate on “what is to be done” rather
than what data is affected.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Important observations about
Function oriented paradigm.
 Difficult to handle if the code exceeds certain limits.
 Large problems are divided into smaller functions.
 Functions transform data.
 Employs top-down approach in design.
 Any part of the code can access any data.
 Models do not connect to real world. It doesn’t
model real world.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
SW Complexity
The complexity of the SW systems we are asked
to develop is increasing, and on the other hand
we have limitations up on our ability to cope with
the complexity.
How do we resolve this????
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Consequence of Complexity
1. The more complex the system, the more open it is
for breakdown.
2. Our failure to manage complexity of the software
results in projects that are late, over budget,
deficiency in their state of requirements.
This condition is often called as software crisis.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Role of Decomposition
1. Dijkstras suggested a technique known as “Divide and Rule”.
2. Decompose a complex system into smaller parts, each of
which we may refine independently.
3. Now we will focus on only few things at a time.
Types of decomposition:
1. Algorithmic Decomposition
2. Object Oriented Decomposition
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Algorithmic Decomposition
1. The system is hierarchically organized as
modules.
2. Each module denotes a major step in some
overall process.
3. Process/functionality forms the basis for
modularization.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Object Oriented Decomposition
1. In this approach we view the worlds as set of
autonomous objects which collaborate to provide
some high level functionality.
2. Each object is simply a tangible entity in the world,
that exhibits some behavior.
3. We ask objects to do what they can do by sending
them messages.
4. This decomposition is based on objects not based
on the algorithm/process.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Algorithmic Vs. Object Oriented
Decomposition
Which is the right way of Decomposing a complex System?
Actually it is a tricky question.
 Algorithmic Decomposition highlights the ordering of events.
 OO Decomposition emphasizes the objects and their actions.
 It is more about how objects collaborate to provide a
functionality.
 We can’t construct a system in both ways simultaneously.
 We must decompose in either of the approach.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Algorithmic Vs. Object Oriented
Decomposition
OO Decomposition is best suited for more complex systems.
In OO approach, we can reuse the common mechanisms resulting in
increased reusability.
These OO systems are more resilient to change and thus better able
to evolve over time.
OO approach greatly reduces the risk of complex systems, since
these are evolved from already proven smaller systems in which we
already have confidence.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
The overall philosophy here is to define the software as
collection of objects (software components) of various types that
interact with each other through well-defined interfaces.
We can design an object to handle multiple functions and hence
can participate in several processes.
A software component can also store data.
Instead of implementing the entire process end-to-end and
defining the needed data structures along the way, we first
analyze the entire set of processes and from this identify
necessary software components.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Each component represents a data abstraction and is designed
to store information along with procedures to manipulate the
same.
Then the execution of the original process is broken in to several
steps and each of which is logically assigned to one of the
software components(objects).
The components can also communicate with each other as
needed to complete the process.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Library Management System
LibManagenet
BookTxMgmt
UserMgmt
AddUser
DelUser
Borrow
UserTxMgmt
Retun
BookInvMgmt
StaffTxMgmt
Issue
Rcev
BookMgmt
AddBook
DelBook
RackMgmt
AddRack
DelRack
Process/Algorithmic Decomposition
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Book
User
BookID
Title
Placedin
LoginID
PW
Name
Login()
ChangePW()
Login()
ChangePW()
NormalUser
StaffUser
StaffID
Designation
Limit
Borrow()
Return()
Issue()
Receive()
AddBook()
DelBook()
AddRack()
DelRack()
Object Oriented Decomposition
Prof.R.Gururaj
Rack
Admin
timeperiod
RackID
PW
Name
Login()
ChangePW()
AddUser()
DelUser()
GenerateReort()
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Object-oriented Software
Development
OOA, OOD, and OOP are related and are used in
developing object-oriented software.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
What is OOA
Object-oriented Analysis refers to a method of
analysis that examines the requirements from
the perspective of classes and objects found in
the vocabulary of problem domain.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
What is OOD
Object-oriented Design refers to any design
methodology that leads to object oriented
decomposition.
OOD encompasses the process of object
oriented decomposition and notation for
depicting logical (class, interfaces, collaboration
etc) , physical ( executables, tables, files etc) as
well as static and dynamic models of the system.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
What is OOP
Object-oriented programming is a method of
implementation in which programs are organized as
cooperative collections of objects , each of which
represents an instance of some class.
Characteristics of Object-oriented Programming:
1. Has Objects, not algorithms, as its basic building
blocks
2. Each object is an instance of some class
3. Classes are related to each other via
inheritance/dependency relationship
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Ch.1 of R1.
The Complete Reference- Java, 7th Edition, Herbert
Schildt, Tata McGraw Hill Publishing.
Ch.2 of R2. Object Oriented Analysis and Design with
Applications, Grady Booch, Addison Wesley, 2nd Edition.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Summary
 Software complexity.
 Role of decomposition.
 Algorithmic and object-oriented decomposition.
 Advantages of OO approach.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
Object Oriented
Principles & Elements
and
Object Model
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Ch.2 of R1.
The Complete Reference- Java, 7th Edition, Herbert
Schildt, Tata McGraw Hill Publishing.
Ch.2 of R2. Object Oriented Analysis and Design with
Applications, Grady Booch, Addison Wesley, 2nd Edition.
And also refer to Class notes.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Object Oriented approach
Object-oriented programming is a method of
implementation in which programs are organized
as cooperative collections of objects , each of
which represents an instance of some class.
Characteristics of Object-oriented Programming:
1. Has Objects, not algorithms, as its basic building
blocks
2. Each object is an instance of some class
3. Classes are related to each other via
inheritance/dependency relationship
BITS Pilani, Hyderabad Campus
The Object Model
The three principles of Object Oriented Programming:
❑ Encapsulation
❑ Inheritance
❑ Polymorphism
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Encapsulation
Encapsulation is the mechanism that binds together
code and the data it manipulates.
Keeps both safe from outside interference and misuse.
It can be thought of as a protective wrapper that
prevents code and data from being arbitrarily
accessed by other code defined outside the wrapper.
Access to code and data is tightly controlled through a
well defined interface.
You can use it without knowing the details of
implementation.
Basis for encapsulation is class.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Inheritance
Inheritance is the process by which one object acquires
the properties of another objects. (super/sub)
This is important because support the concept of
hierarchical classification.
The knowledge is made manageable by hierarchical
classification.
This mechanism makes it possible for one object to be
a specific instance of a more general case.
This also helps in managing complexity. Because we use
the same code already defined and proved in Super
class.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Polymorphism
Polymorphism is a feature that allows one interface to be
used for general class of action.
The specific action is determined by the exact nature of
the situation.
Expressed by the phrase- “one interface multiple
methods”.
This helps in reducing the complexity.
Encapsulation, Inheritance and polymorphism work
together to produce a programming environment that
supports development of more scalable and robust
programs than does the Process-oriented model.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
What is OOP
Object-oriented programming is a method of
implementation in which programs are organized as
cooperative collections of objects , each of which
represents an instance of some class.
Characteristics of Object-oriented Programming:
1. Has Objects, not algorithms, as its basic building
blocks
2. Each object is an instance of some class
3. Classes are related to each other via inheritance
relationship
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Object-oriented languages1. Support objects that are data abstractions with
an interface of named operations and hidden
local state.
2. Objects have an associated type [class].
3. Type may inherit attributes from supertypes
[super class]
Ex: Smalltalk, Ada, C++, Java, Eiffel, Object
Pascal etc.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Programming Paradigms
Paradigm
Basis
Suitability
Example
Procedureoriented
Algorithms/
functions
Computation-intense operations
C, Fortran, Pascal,
Algol
Logicoriented
Goals;
predicate logic
Knowledgebase systems, expert
systems, Natural language
processing, Relational DB
Prolog
Objectoriented
Objects, classes Broadest set of applications;
Architectural frameworks
C++, Java, Small
talk, Ada, Ruby etc
Functional
Programming
Only functions
LISP, ML, Haskell
Prof.R.Gururaj
AI
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Other important Elements of
OO Model
1.
2.
3.
4.
5.
6.
Abstraction
Modularity
Typing
Binding
Concurrency
Persistence
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Abstraction
An essential element of object-oriented approach is abstraction.
Humans manage complexity through abstraction.
Using abstraction we can ignore the inner details which are not
so essential, and still we could use an object as a whole.
Modularity
It is the act of partitioning a program into individual
components. This is to reduce the complexity.
Modules serve as physical containers in which we declare
classes and objects of our logical view.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Typing:
Typing is the enforcement of the class of an object, such that
objects of different types may not be interchanged, or at the
most they may be interchanged only in very restricted ways.
A programming language may be strongly typed, and
some are untyped.
Ex: Java , C++ , Ada are strongly typed.
Violation of type conformance can be detected at compile time.
Smalltalk is untyped.
Any object can invoke some method on any object, even that method is
not defined for that object. Violation is not known until execution.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Advantages of strongly typed languages
1. Without this type checking programs can crash in
mysterious ways.
2. Early detection of bugs makes edit-compile-debug cycle
effective.
3. Type declaration helps to document programs.
4. Most compilers generate efficient code if types are
declared.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Binding: refers to the time when names are bound to
object types. This concept is different from strong/untyped.
Static and Dynamic Binding:
Static/early binding : Means that the type of object pointed
by reference is fixed at the time of compilation.
Dynamic binding: Object types are not known until runtime.
This concept is different from strong/untyped.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
More on Inheritance
Inheritance is the most important “is a” hierarchy.
Thus we have single inheritance and multiple inheritance.
Inheritance thus implies generalization and specialization
hierarchy.
A subclass specializes the more general structure or
behavior of the superclass.
If A is not kind of B the A should not inherit B
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
As we evolve our inheritance hierarchy the structure and
behavior that are common to different classes will tend to
common superclasses.
Superclass represents generalized abstractions.
Subclasses represent specialization of superclasses.
Multiple Inheritance is conceptually straightforward, but
induces some practical complexities for programming
languages.
We will have to address two things:
❑ Name clashes.
❑ Repeated inheritance.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Name clashes: Ex:C++ resolves the name clash by attaching the
classname qualifier.
Repeated inheritance:
This occurs when two or more peer superclasses share a
common superclass.
In such situation, the inheritance lattice will be a diamond,
and so the question arises, does the leaf class have one
copy or multiple copies of the structure of the shared
superclass.
Most of the cases, multiple inheritance is misused.
Hence it is prohibited by some languages.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Concurrency
For certain kinds of problems, an automated system may have to
handle many different events simultaneously.
Threads.
Single CPU, multiple CPUs.
Persistence
An object in software takes up some amount of space and
exists for a particular amount of time.
Persistence is the property of an object through which its
existence transcends time ( i.e. the object continues to
exist after its creator ceases to exist), and/or space ( i.e.
the object moves form one address space to another),
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Object Model
❖ Object model does not abandon the sound
principles of process-oriented model.
❖ Rather it introduces several novel elements that
build upon these earlier models.
❖ The use of Object model helps us to construct wellstructured complex systems.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Benefits of Object Model
1. Object model helps us to exploit the
expressive power of object based languages.
2. Reuse of SW and Design both, leading to SW
frameworks.
3. Systems are more resilient to change.
4. Develop more complex systems with
confidence and correctness.
5. Humans find the idea of object orientation
quite natural.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Objects
The ability to recognize the physical objects is a skill
humans possess.
We understand that an object is a tangible entity that
exhibits some well-defined behavior.
An object can be any of the following:
1. A tangible and/or visible thing.
2. Something towards which our thought or action is
directed.
3. Something that may be understood intellectually.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Real-world objects are not the only kind of objects that are
of interest to us in SW development.
Other important kinds of objects are inventions of the
Design process whose collaboration with other such
objects to provide some high-level behavior or
functionality.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
An object represents an individual, identifiable
item, unit, or entity either in the real world or
abstract, with a well-defined role in the
problem domain.
Speed, color, temp etc. can not become objects.
These are actually properties of other objects.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
An object has state, behavior, and identity.
The structure and behavior of similar objects are
defined in their common class.
The terms instance and object are
interchangeable.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
State of an object
The state of an object encompasses all the properties
(usually static) of an object plus the current (usually
dynamic) values of each of these properties.
All properties have values- simple or another object.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Behavior of an object
Objects don’t stay in isolation.
They keep interacting with each other.
They act upon others and similarly are acted upon by
other objects.
Behavior is how an object acts and reacts, in terms of
its state changes and message passing.
We use the terms operation and message
interchangeably.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Identity of an object
Identity is that property of an object which
distinguishes it from all other objects.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Class
❑ A class represents a set of objects that share a
common structure and a common behavior.
❑ A single object is an instance of a class.
❑ An individual object is a concrete entity that
performs some role in the overall system.
❑ The class captures the structure and behavior
common to all related objects.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Class
The interface of a class provides its outside view and
therefore helps in hiding the structure and secrets of
behavior.
By contrast the implementation of a class is its inside view,
which encompasses the secrets of its behavior.
Types of interfaces:
Public ; Private; Protected
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Relationships among Class
Classes may be related in many interesting ways:
❑ Aggregation
❑ Inheritance
❑ Dependency- ( change in one class may affect
other class )
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Summary
❑Three basic Principles of Object Model
❑Other important elements of OO: abstraction,
Modularity
❑ Typing, binding, Concurrency and Persistence
❑ Benefits of Object model
❑ Object - state, identity, and behavior
❑ Class
❑ Relationships among the classes
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
Java Classes
and Methods
OOP-5
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
More on classes, objects,
member variables,
methods and
constructors
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Ch.6 of R1.
The Complete Reference- Java, 7th Edition, Herbert
Schildt, Tata McGraw Hill Publishing.
And also refer to Class notes.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Classes
❖The class forms the basis for object oriented
programming in Java.
❖Class is a template for an object, and object
is an instance of a class.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
General form of a class:
class classname
{
type instance-variable1;
type instance-variable2;
….
type instance-variableN;
type methodname1(parameter-list)
{ body }
……
type methodnameN(parameter-list)
{ body }
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Members of a class
instance variables
methods
A simple class:
class Box
{
int width;
int length;
int depth;
}
To instantiate an object of Box
Box myBox=new Box();
To access variables of an object
myBox.length=12;
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Hungarian notation
(Charles Simonyi from Microsoft)
Naming convention used in Java OOP
Class names
start with caps
Ex:
- start with caps and and new words will
Box,
BoxDemo
Variables – start with small case and new words will start
with caps
Ex: length, boxVolume
methods – start with small case and new words will start
with caps
Ex: volume(), boxVolume(), findSum()
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
A program that uses Box class
class Box
{
int width; int length; int depth;
}
class BoxDemo
{
public static void main(String args[])
{
Box myBox=new Box();
int volume;
myBox.length=2; myBox.width=3; myBox.height=3;
volume= myBox.length * myBox.width * myBox.height;
System.out.println(“Box volume is : “+volume);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
A program that instantiates more than one Box class objects
class BoxDemo
{
public static void main(String args[])
{
Box myBox1=new Box();
Box myBox2=new Box();
int volume;
myBox1.length=2; myBox1.width=3; myBox1.height=3;
volume= myBox1.length * myBox1.width * myBox1.height;
System.out.println(“Box1 volume is : “+volume);
myBox2.length=5; myBox2.width=6; myBox2.height=7;
volume= myBox2.length * myBox2.width * myBox2.height;
System.out.println(“Box2 volume is : “+volume);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Declaring class objects
null
Box myBox;
myBox
length
myBox=new Box();
myBox
width
height
Box
object
Box newBox;
newBox
newBox= myBox;
Prof.R.Gururaj
Object Oriented Programming
newBox
BITS Pilani, Hyderabad Campus
Adding methods
type methodname1(parameter-list)
{
body
}
Type is return value type and could be void
We return values from a method using the syntax
return value;
We can return
- any java predefined type value or an object.
- the type specified in return type of method declaration
and actual return value type must match.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Adding a method to Box class that returns some value:
class Box
{
int width;
int length;
int depth;
int volume()
{
return (length * width * height);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Adding a method to Box class that take parameters:
class Box
{
int width;
int length;
int depth;
int volume()
{
return (length * width * height);
}
void setDimensions(int l, int w, int h)
{
length=l;
width=w;
height=h;
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Constructors
❑
Initialize java objects when they are created
they have no return type.
❑ Constructor is automatically called after object is created
and new operator completes.
❑ A default constructor is created by java, instance variables
will be initialized to zero or null.
❑ If we explicitly define a constructor the default constructor
is no more available.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
//Class Box with default constructors
class Box
{
int width;
int length;
int depth;
int volume()
{
return (length * width * height);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
A program that uses Box class constructor
class BoxDemo
{
Public static void main(String args[])
{
Box myBox1=new Box();
int vol;
vol= myBox1.volume();
System.out.println(“Box volume is : “ + vol);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Adding a parameterized constructor to Box class :
class Box
{
int width; int length;
int depth;
Box(int l, int w, int h)
{System.out.println(“Inside box parameterized constructor : “ );
length=l;
width=w;
height=h;
}
int volume()
{
}
return (length * width * height);
Prof.R.Gururaj
Object Oriented Programming
}
BITS Pilani, Hyderabad Campus
A program that uses parameterized constructor
class BoxDemo
{
Public static void main(String args[])
{
Box myBox1=new Box(2,3,4);
int vol;
vol= myBox1.volume();
System.out.println(“Box volume is : “ + vol);
}
}
Inside box parameterized constructor:
Box volume is :24
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Use of this keyword
The keyword this used in a method to refer to the object invoked it.
class Box
{
int width; int length; int height;
Box(int w, int l, int h)
{System.out.println(“Inside box parameterized constructor : “ );
this.length=l;
this.width=w;
this.height=h;
}
}
But the above usage is redundant
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Instance variable hiding
When local variable and instance variable names are same, then local variable
hides the instance variable.
class Box
{
int width; int length; int height;
Box(int length, int width, int height)
{System.out.println(“Inside box parameterized constructor : “ );
length=length;
width=width;
height=height;
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Instance variable hiding
When local variable and instance variable names are same, then local variable
hides the instance variable. The keyword ‘this’ will resolve the problem
class Box
{
int width; int length; int height;
Box(int length, int width, int height)
{System.out.println(“Inside box parameterized constructor : “ );
this.length=length;
this.width=width;
this.height=height;
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Garbage Collection in Java
-
In Java we don’t destroy objects that are created.
- Java has a mechanism called ‘garbage collection’.
- It is daemon thread.
- It reclaims space occupied by unused objects.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Daemon thread in java
is a service provider thread that provides services to the
user thread. Its life depend on the mercy of user threads
i.e. when all the user threads dies, JVM terminates this
thread automatically.
❑ It provides services to user threads for background
supporting tasks. It has no role in life than to serve user
threads.
❑ Its life depends on user threads.
❑ It is a low priority thread.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
finalization mechanism in Java
it facilitates performing certain actions just before an
object
is destroyed by garbage collector.
protected void finalize()
{
// finalization code
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Stack Example
A stack stores data using first-in, last-out ordering. Stacks
are controlled through two operations pop and push.
Stack[9]
Stack[8]
Stack[7]
Stack[6]
Stack[5]
top
Prof.R.Gururaj
10
Stack[4]
70
23
Stack[3]
Stack[2]
7
Stack[1]
12
Stack[0]
Object Oriented Programming
int stack[ ]=new int[10];
tos=-1;
Implementation as
discussed in the Lect session.
BITS Pilani, Hyderabad Campus
Method and constructor with same name?
class LineDemo
{
public static void main(String args[])
{
Line s=new Line ();
System.out.println(" Line Length is:"+s.l);
s. Line(23);
}
}
class Line
{
int l;
Line()
{
System.out.println(" In constructor");
}
void Line(int a)
{System.out.println(" Inside Line method : "+a);}
}
In constructor
Line Length is:0
In Line method : 23
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Summary
❑
❑
❑
❑
❑
❑
❑
❑
Class structure
Methods
Constructors
Parameterized constructor
Use of this keyword
Garbage collection
Method finalize()
Stack Example
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
More on classes
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
T1: Ch.1 & 2; T2: Ch.1
&
Ch.6 & 7 of R1.
The Complete Reference- Java, 7th Edition, Herbert
Schildt, Tata McGraw Hill Publishing.
And also refer to Class notes.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Methods
General form of a method:
type methodname1(parameter-list)
{ body }
Overloading methods in Java
- In Java it is possible to define two or more methods in a
class with same name.
- In such case the methods are said to be overloaded.
- And this process is referred to as method overloading.
- This is how Java implements polymorphism“one interface multiple methods”
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Book
{
void test(int a)
{
System.out.println(“a is : “ + a);
}
void test(int a, int b)
{
System.out.println(“a and b are : “ + a+” AND “+b);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Passing Objects as
parameters
class Line
{
int length;
Line (int l)
{length=l;}
boolean compare(Line x)
{
if(this.length==x.length) return true;
else return false;
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Module62
{
public static void main(String args[])
{
Line l1=new Line(10);
Line l2=new Line(10);
boolean b=l1.compare(l2);
if (b)
System.out.println(" Both l1 and l2 are of same length");
else
System.out.println(" l1 and l2 are of different length");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Parameter passing
(Call-b-value/call-by-reference)
class Line
{
int length;
Line(int l) { length=l;}
void doubleVal( int a) { a=a*2;}
void doubleLength(Line l) { l.length=l.length*2;}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Module63
{ public static void main(String args[])
{
Line l1=new Line(2);
System.out.println("Call by value :");
System.out.println("value of Line length before doubled is: "+
l1.length);
l1.doubleVal(l1.length);
System.out.println("value of Line length after doubled is: "+
l1.length);
System.out.println("Now Call by reference :");
System.out.println("length of the line before doubled is: "+ l1.length);
l1.doubleLength(l1);
System.out.println("length of the line after doubled is: "+ l1.length);
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
}
Recursion
Java supports recursion.
–Recursion is the process of defining something in terms of
itself.
–A method can call itself. Such methods are called
recursive methods.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Factorial
{
int fact(int n)
{
int result;
if(n==1) return 1;
result=fact(n-1) * n;
return result;
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Recursion
{
public static void main(String args[])
{
Factorial f= new Factorial();
System.out.println(“Factorial of 4 is: “+ f.fact(4));
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
fact(n)
n
fact(n-1) * n
result
=====================================
fact(4)
4
fact(3)* 4
6*4=24
fact(3)
3
fact(2) * 3
2*3=6
fact(2)
2
fact(1) * 2
1*2=2
fact(1)
1
1
1
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Storage for Java Programs
When a program is loaded into memory, it is organized into
three areas of memory, called segments: the stack
segment and the heap segment.
The stack is where memory is allocated for local variables
within methods.
The heap segment provides more stable storage of data for
a program; memory allocated in the heap remains in
existence for the duration of a program. Therefore static
variables and objects are allocated on the heap.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
❖ When method is called space for parameters and
variables is allocated on the stack.
❖ The structure of the stack includes a stack frame for
each active method/procedure.
❖ There may be several frames in the stack at once for a
given method/procedure if it is recursive.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
❖ When a method calls itself, new local variables and
parameters are allocated storage on the stack, and the
method code is executed with these new variables from
the start.
❖ As each recursive call returns, the old local variables and
parameters are removed from the stack, and the
execution resumes at the point of call inside the method.
❖ Execution of recursive calls are slow because of
overhead due to function calls.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
❖ Many recursive calls to a method can cause in stack
overflow.
❖ In such case Java run-time will throw an error. But this is
a rare event.
❖ The main advantage of recursion is that they can be
used to write clearer code for algorithms that are iterative
in nature.
❖ While writing iterative methods we must include an IF
statement somewhere to force the method to return
without recursive call being executed.
❖ Otherwise it will never return.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Access Protection in Java
Encapsulation gives rise to access control on class
members.
How a member can be accessed is determined by access
specifier.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Static members
The static can be attached before instance variable or a method
name while declaring the same.
static variables
- they are global to class
- all instances will share the same copy
- not per instance basis
- can be called with class name without instances
static methods
- can call only static methods
- can access only other static data
- can not refer to this or super
- can be called with class name without instances
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{
static int length;
void setLength(int a)
{ length=a; }
void display()
{
System.out.println(" length is ::"+length);
}
}
Is this code OK?
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class staticDemo
{
public static void main(String org[])
{
Line d1=new Line();
d1.setLength(2);
Line d2=new Line();
d2.setLength(3);
Line d3=new Line();
d3.setLength(4);
d1.display();
d2.display();
d3.display();
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Check for correctness
class staticBlockDemo
{
public static void main(String org[])
{
Line l1=new Line(20);
l1.display();
}
}
class Line
{
int length;
void Line(int a)
{
length=a;
}
void display()
{
System.out.println(" length of line is ::"+length);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>javac staticBlockDemo.java
staticBlockDemo.java:5: error: constructor Line in class Line
cannot be applied
to given types;
Line l1=new Line(20);
^
required: no arguments
found: int
reason: actual and formal argument lists differ in length
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Static block
class Line
{
static {System.out.println(" Inside static block of line class:");}
int length;
Line(int a)
{ length=a; }
void display()
{
System.out.println(" length of line is ::"+length);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class staticBlockDemo
{
public static void main(String org[])
{
Line l1=new Line(20);
l1.display();
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java staticBlockDemo
Inside static block of line class:
length of line is ::20
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{
static{ System.out.println(" Inside static block of line class:"); }
static int code=111;
int length;
Line(int a)
{ length=a; }
void display()
{
System.out.println(" length of line is ::"+length);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class staticDemo2
{
public static void main(String org[])
{
Line l1=new Line(20);
l1.display();
System.out.println(" Line Code is :"+l1.code);
System.out.println(" Line Code is :"+Line.code);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java staticDemo2
Inside static block of line class:
length of line is ::20
Line Code is :111
Line Code is :111
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Check the correctness
class Line
{
static int code=111;
int length;
Line(int a)
{
length=a;
}
static void display()
{ System.out.println(" length of line is ::"+length);
}
Prof.R.Gururaj
Object Oriented Programming
}
BITS Pilani, Hyderabad Campus
class staticDemo3
{
public static void main(String org[])
{
Line l1=new Line(20);
l1.display();
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>javac staticDemo3.java
staticDemo3.java:26: error: non-static variable length
cannot be referenced from a static context
System.out.println(" length of line is ::"+length);
^
1 error
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{
static int code=111;
int length;
Line(int a) {length=a; }
static void display()
{
System.out.println(" Code of line is ::"+code);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class staticDemo3
{
public static void main(String org[])
{
Line l1=new Line(20);
l1.display();
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{
int length;
Line(int a)
{
length=a;
}
static void display()
{
System.out.println(" Started Display \n");
print();
}
static void print() { System.out.println(" Inside print method");}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class staticDemo5
{
public static void main(String org[])
{
Line l1=new Line(20);
l1.display();
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java staticDemo6
Started Display
Inside print method
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class StaticDemo7
{
public static void main(String org[])
{System.out.println("Value of Length is: "+Line.length);}
}
class Line
{
static int length=10;
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class StaticDemo8
{
public static void main(String org[])
{System.out.println("Value of Length is: "+Line.length);
Line l= new Line();
l.length=20;
System.out.println("Value of Length after update is: "+l.length);
}
}
class Line
{
static int length=10;
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Nested Class
A Nested class is a class defined in another class.
If class B is defined inside class A, it is known to A but not
outside A.
That is B does not exist independent of A.
All members (including private) of A are accessible by B.
But, A can not access members of B.
It is also possible to declare a nested class local to a block.
Any code outside Outer class cannot create an inner class
object.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Outer
{
int outer_x;
Outer(){outer_x=10;}
void test(){ Inner inner=new Inner(); inner.display();}
class Inner
{
void display() {System.out.println(“ display outer_x =“ +outer_x); }
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
InnerDemo
{
public static void main(String args[])
{
Outer out=new Outer();
out.test();
}
}
Classes created
Outer.class
Outer$Inner.class
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Outer
{
C:\Users\Admin\JavaPrograms>jav
int outer_x;
ac InnerClassDemo1.java
Outer() {outer_x=10;}
InnerClassDemo1.java:19: error:
class Inner
cannot find symbol
{ int m;
Inner in =new Inner(55);
Inner(int a) {m=a;}
^
}
symbol: class Inner
}
location: class InnerClassDemo1
class InnerClassDemo1
{
public static void main(String args[])
{
Inner in =new Inner(55);
System.out.println(" value of Inner clas m is: "+ in.m);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Box
{
int length;
Box(int a) { length=a;}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Demo
{
public static void main(String args[])
{
Box b1=new Box(10); Box b2=b1;
System.out.println(" box b1 lenth is :"+b1.length);
System.out.println(" box b2 lenth is :"+b2.length);
Box b3=new Box(10);
System.out.println(" box b3 lenth is :"+b3.length);
if(b1==b2)
System.out.println(" box b1 and b2 are same:");
else System.out.println(" box b1 and b2 are not same:");
if(b1==b3)
System.out.println(" box b1 and b3 are same:");
else System.out.println(" box b1 and b3 are not same:");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Overriding equals()
class Box
{
int length;
Box(int a) { length=a;}
public boolean equals(Object obj)
{
Box b=(Box)obj;
if(this.length==b.length) return true;
else return false;
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Demo
{
public static void main(String args[])
{
Box b1=new Box(10);
Box b3=new Box(10);
if(b1==b3) System.out.println(" box b1 and b3 are same:");
else System.out.println(" box b1 and b3 are not same:");
if(b1.equals(b3))System.out.println(" box b1 and b3 are same:");
else System.out.println(" box b1 and b3 are not same:");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Summary
❖ Adding Methods to class
❖ Method Overloading
❖ Parameter Passing
❖ Recursion with examples
❖ Instance variables
❖ The static keyword
❖ Nested Classes
❖ equals() method
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
Inheritance
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Ch.8 of R1.
The Complete Reference- Java, 7th Edition, Herbert
Schildt, Tata McGraw Hill Publishing.
And also refer to Class notes.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Content
1. Inheritance basics
2. Member access and inheritance
3. Superclass referencing subclass object and use of super keyword
4. Multilevel hierarchy
5. Constructor calling
6. Method overriding
7. Dynamic method dispatch
8. Abstract classes
9. Using final with inheritance
10.The Object class
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Inheritance
This allows us to create hierarchical classifications.
One class can inherit traits/properties of another class.
class that is inherited is called superclass.
Hence, subclass is specialized version of superclass.
We use the keyword extends for inheriting a class from other
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
int a;
superclass
int b;
void test(){}
int a;
int a;
int b;
int c;
void test(){}
subclass1
int c;
void add(){}
subclass2
int d;
int b;
int d;
void test(){}
void add(){}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class A
{
int a;
void showSuper()
{System.out.println(" Value of a is ::"+a);}
}
class B extends A
{
int b;
void showSub()
{System.out.println(" Value of a and b are ::"+a+”
and “+b);}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class SuperSubDemo
{ public static void main(String org[])
{
A superObj=new A();
B subObj=new B();
superObj.a=10;
System.out.println(" Contents of super object A are: “);
superObj.showSuper();
subObj.a=100; subObj.b=200;
System.out.println(" Contents of sub object B are: “);
subObj.showSub();
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Contents of super object A are:
Value of a is ::10
Contents of sub object B are:
Value of a and b are ::100 and 200
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Member access
-
If super class member is not accessible to a
subclass if it is specified as private
class A
{
private int a;
void showSuper()
{System.out.println(" Value of a is ::"+a);}
}
class B extends A
{
int b;
void showSub()
{System.out.println(" Value of a and b are ::"+a+”
and “+b);}
}
This will not compile because class B trying to access a private member ‘a’ of A
BITS Pilani, Hyderabad Campus
Superclass variable can reference a subclass
- A reference variable of superclass can be used to point to any
subclass object of that superclass.
A
(superclass)
int a;
int b;
void test(){}
int a;
int a;
int b;
int c;
void test(){}
void add(){}
Valid
A aObj;
aObj=new B();
aObj=new C();
Prof.R.Gururaj
B
subclass1
int c;
void add(){}
invalid
B bObj;
bObj=new A();
Object Oriented Programming
int b;
C
subclass2
int d;
int d;
void test(){}
invalid
B bObj;
bObj=new C();
BITS Pilani, Hyderabad Campus
-A reference variable of superclass can be used to point to any
subclass object of that superclass.
-In such case we can access only those parts of subclass objects
which defined in super class.
Valid
invalid
A aObj;
aObj=new B();
aObj.a=29;
aObj.test();
A aObj;
aObj=new B();
aObj.c=90;
aObj.add();
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Using super keyword
The keyword super is used in two ways
1. super() - Call super class constructor from
subclass constructor, and must be the first
statement in sub class constructor
2. Access super class members when subclass
members hide superclass members.
It is possible to declare a variable in subclass
with same name as declared in superclass.
In such case subclass members hide superclass
members.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Box
{
int length; int width; int height;
Box(int l,int w,int h)){length=l; w=width; height=h;}
}
class BoxWeight extends Box
{
int weight;
BoxWeight(int l,int w,int h, int wt)
{length=l; w=width; height=h; weight=wt;}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class SuperDemo
{ public static void main(String org[])
{
BoxWeight bw=new BoxWeight(2,3,4,5);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{ int length;
Line(int l){length=l;}
}
class NewLine extends Line
{
int length;
NewLine(int a)
{
length=a; }
}
class SuperDemo1
{ public static void main(String org[])
{
NewLine nl=new NewLine(20);
System.out.println("Length is :"+nl.length);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{
int length;
Line(int l){length=l;}
}
class NewLine extends Line
{
int length;
NewLine(int a, int b)
{
super(50);length=a; }
//super() should be the first one to be called.
}
class SuperDemo1
{ public static void main(String org[])
{
NewLine nl=new NewLine(20,50);
System.out.println("Length is :"+nl.length);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{
int length;
}
class NewLine extends Line
{
int length;
NewLine(int a)
{
length=a; }
}
class SuperDemo2
{ public static void main(String org[])
{
NewLine nl=new NewLine(25);
System.out.println("Length is :"+nl.length);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{ int length;
void print(){System.out.println("In Super Print");}
}
class NewLine extends Line
{
int length;
NewLine(int a)
{
length=a; }
void print(){System.out.println("In Subclass Print");}
}
class SuperDemo3
{ public static void main(String org[])
{
NewLine nl=new NewLine(25);
nl.print();
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{ int length;
void print(){System.out.println("In Super Print");}
}
class NewLine extends Line
{
int length;
NewLine(int a)
{
length=a; }
void print(){super.print(); System.out.println("In Subclass Print");}
}
class SuperDemo3
{ public static void main(String org[])
{
NewLine nl=new NewLine(25);
nl.print();
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{
int length;
}
class NewLine extends Line
{
int ht;
NewLine(int a, int b)
{length=a; ht=b;}
}
class SuperDemo4
{ public static void main(String org[])
{
NewLine nl=new NewLine(25,60);
System.out.println("Super length is:"+nl.length);
System.out.println("Sub ht is:"+nl.ht);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{ private int length;
}
class NewLine extends Line
{
int ht;
NewLine(int a, int b)
{
length=a; ht=b;
}
}
class SuperDemo5
{ public static void main(String org[])
{
NewLine nl=new NewLine(25,60);
System.out.println("Super length is:"+nl.length);
System.out.println("Sub ht is:"+nl.ht);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>javac SuperDemo5.java
SuperDemo5.java:13: error: length has private access in
Line
length=a; ht=b;
^
SuperDemo5.java:22: error: length has private access in
Line
System.out.println("Super length is:"+nl.length);
^
2 errors
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{ private int length;
Line(int x){length=x; print();}
void print(){System.out.println("Super length is:"+length);}
}
class NewLine extends Line
{
int ht;
NewLine(int a, int b)
{
super(a); ht=b;
}
}
class SuperDemo6
{ public static void main(String org[])
{
NewLine nl=new NewLine(25,60);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Creating multilevel hierarchy
class A
{
int a;
}
super() in class B calls A()
super() in class C calls B()
class B extends A
{
int b;
}
If super() is not used in subclass then default
or parameterless constructor of superclass is
used.
class C extends B
{
int c;
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class A
{
A(){System.out.println(" Inside A’s constructor :”);
}
class B extends A
{
B(){System.out.println(" Inside B’s constructor :”);
}
class C extends B
{
C(){System.out.println(" Inside C’s constructor :”);
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ConstructorsDemo
{ public static void main(String org[])
{
C cobj=new C();
}
}
Inside A’s constructor :
Inside B’s constructor :
Inside C’s constructor :
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Method Overriding
subclass can have a method defined, which has same
name and type signature (arguments & return type) as the
one available in its super class. Then the subclass is said
to override the method in its superclass.
When a overridden method is called from the subclass it
always refers to the version defined in the sub class.
Why overriding:
superclass can specify methods that will be common to
all its derivatives
this implements ‘one interface multiple methods’
aspect of polymorphism.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class A
{
void test(int a)
{System.out.println(" test method of super class :”+ a);}
}
class B extends A
{
void test(int a)
{System.out.println(" test method of subclass class :”+ a);}
}
If we wish to call the superclass version of test() we need to use
super.test(2); statement in subclass code.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Dynamic Method Dispatch
- Is a mechanism by which a call to an overridden method is resolved at
runtime, rather than compile time.
- This is how Java implements run-time polymorphism.
class OverrideDemo
{ public static void main(String org[])
{
A a=new A();
a.test(3);
this will invoke A’s test()
a=new B();
a.test(7);
this will invoke B’s test()
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Abstract class
- Superclass declares the structure of the class,
without complete implementation to all the
methods(abstract class).
- Here superclass is unable to define the
implementation.
- It is the responsibility of the sub class to
provide implementation required.
-
As there is no completeness an abstract class
object can not be instantiated.
-
But we can declare a reference variable of an
abstract class and make it to point to some
concrete subclass object.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
abstract class A
{
abstract void test(int a);
}
class B extends A
{
void test(int a)
{System.out.println(" test method of subclass class :”+ a);}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class AbstractDemo
{ public static void main(String org[])
{
A a = new A();
A a =new B();
//it is wrong
//ok
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
The final keyword for methods
A super class method specified with final modifier can not
be overridden by any of its subclasses.
final void add(int a, int b){ // body }
The final keyword for class
A class specified with final modifier can not be inherited.
final class Box
{
//body
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
The Object class
- is the super class for all java classes
Object clone()
void finalize()
boolean equals(Object o)
void notify()
//final
void notifyAll()
//final
void wait()
// final
String toString()
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class Line
{
void print(){System.out.println("In super line:\n");}
}
class StLine extends Line
{
void print1(){ System.out.println("In Straight Line:\n");}
}
class TypeCastDemo1
{
public static void main(String org[])
{
Line l=new Line();
l=new StLine();
meth(l);
}
static void meth(Line l)
{
StLine l1=l;
l1.print1();
Line ln=l;
ln.print();
}
}
BITS Pilani, Hyderabad Campus
class Line
{
void print(){System.out.println("In super line:\n");}
}
class StLine extends Line
{
void print1(){ System.out.println("In Straight Line:\n");}
}
class TypeCastDemo1
{
public static void main(String org[])
{
Line l=new Line();
l=new StLine();
meth(l);
}
static void meth(Line l)
{
StLine l1=(StLine)l;
l1.print1();
Line ln=l;
ln.print();
}
}
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>javac
TypeCastDemo2.java
C:\Users\Admin\JavaPrograms>java TypeCastDemo2
In Straight Line:
In super line:
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>javac TypeCastDemo1.java
TypeCastDemo1.java:25: error: incompatible types: Line cannot be
converted to StLine
StLine l1=l;
^
1 error
BITS Pilani, Hyderabad Campus
Summary
1. Inheritance basics
2. Member access and inheritance
3. Superclass referencing subclass object and use of super keyword
4. Multilevel hierarchy
5. Constructor calling
6. Method overriding
7. Dynamic method dispatch
8. Abstract classes
9. Using final with inheritance
10.The Object class
11.Object type Casting
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
String Handling in Java
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
Strings In Java
•
String is sequence of characters.
•
In Java, strings are treated as objects.
•
The String class is used to create a string object.
•
String is immutable in nature. It means we can’t modify the string once it is
created.
Whenever we change any string, a new instance is created.
•
Mutable strings can be created by using StringBuffer and StringBuilder
classes.
•
We can create String object either by using string literal or using new
keyword.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Creating Strings
There are two ways to create a String in Java
a. Using string literal
b. Using new keyword
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Using String Literals
Assigning a String literal to a String reference.
Example:
String str1 = "Hello";
String str2 = "Hello";
Here we have not created any string object using the new
keyword.
The compiler does that task for us, it creates a string object
having the string literal (that we have provided, in
this case it is “Hello”) and assigns it to the provided string
reference.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Using new keyword
But if the object already exist in the memory (string
constant pool) it does not create a new
Object rather it assigns the same old object to the new
reference, that means even though we have two string
references above(str1 and str2) compiler only created
one string object (having the value “Hello”) and the
reference to the pool instance is returned to both the
references. For example there are 10 string references
that have same value, it means that in memory there is
only one object having the value and all the 10 string
references would be pointing to the same object.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
String str1 = new String("Welcome");
String str2 = new String("Welcome");
This would create two different objects with same string
value.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
String class Constructors
1)String() - This initializes a newly created String object so
that it represents an empty character sequence.
2)String(char[] value) - This allocates a new String so that it
represents the sequence of characters currently
contained in the character array argument.
3)String(char[] value, int offset, int count) - This allocates a
new String that contains characters from a subarray of
the character array argument.
4)String(String original) - This initializes a newly created
String object so that it represents the same sequence of
characters as the argument; in other words, the newly
created string is a copy of the argument string.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
5)String(StringBuffer buffer) - This allocates a new string
that contains the sequence of characters currently
contained in the string buffer argument.
6)String(StringBuilder builder) - This allocates a new string
that contains the sequence of characters currently
contained in the string builder argument.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
String Class Methods:
1) char charAt(int index) - Returns the character at the specified index.
2) int compareTo(String anotherString) - This method compares two
strings lexicographically.
3)String concat(String str) - This method appends one String to the end
of another. The method returns a String with the value of the String
passed into the method, appended to the end of the String, used to
invoke this method.
4) int length() - Returns the length of this string.
5) String toLowerCase() - Converts all of the characters in this String to
lower.
6). String toUpperCase() - Converts all of the characters in this String to
upper.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
StringBuffer class
StringBuffer supports a modifiable string. As you know,
String represents fixed-length,immutable character
sequences. In contrast, StringBuffer represents growable
and writable character sequences. StringBuffer may
have characters and substrings inserted in
the middle or appended to the end. StringBuffer will
automatically grow to make room for such additions and
often has more characters preallocated than are actually
needed, to allow room for growth.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
StringBuffer Constructors
1)StringBuffer() - It is the default constructor and reserves
room for 16 characters without reallocation.
2) StringBuffer(int size) - It accepts an integer argument that
explicitly sets the size of the buffer.
3) StringBuffer(String str) - The third version accepts a String
argument that sets the initial contents of the StringBuffer
object and reserves room for 16 more characters without
reallocation. StringBuffer allocates room for 16 additional
characters when no specific buffer length is requested.
4)StringBuffer(CharSequence chars) - It creates an object
that contains the character sequence contained in chars
and reserves room for 16 more characters.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Methods
1) int capacity() - It is used to return the current capacity.
2)synchronized StringBuffer insert(int offset, String s) - It is
used to insert the specified string with this string at the
specified position. The insert() method is overloaded
like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
3)synchronized StringBuffer replace(int startIndex, int
endIndex, String str) - It is used to replace the string from
specified startIndex and endIndex.
4) synchronized StringBuffer reverse() - It is used to reverse
the string.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
StringBuilder class
Introduced by JDK 5, StringBuilder is a relatively recent
addition to Java’s string handling capabilities.
StringBuilder is similar to StringBuffer except for one
important difference: it is not synchronized, which means
that it is not thread-safe. The advantage of StringBuilder
is faster performance. However, in cases in which a
mutable string will be accessed by multiple threads, and
no external synchronization is employed, you must use
StringBuffer rather than StringBuilder.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
When to use which one :
❑ If a string is going to remain constant throughout the
program, then use a String class object because a String
object is immutable.
❑ If a string can change (example: lots of logic and
operations in the construction of the string) and will only
be accessed from a single thread, using a StringBuilder
is good enough.
❑ If a string can change, and will be accessed from
multiple threads, use a StringBuffer because StringBuffer
is synchronous so you have thread-safety.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
StringTokenizer class
The java.util.StringTokenizer class allows you to break a
string into tokens. It is simple way to break string. It
doesn't provide the facility to differentiate numbers,
quoted strings, identifiers etc.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Constructors
1)StringTokenizer(String str) - Creates StringTokenizer with
specified string.
2)StringTokenizer(String str, String delim) - Creates
StringTokenizer with specified string and delimiter.
3) StringTokenizer(String str, String delim, boolean
returnValue) - Creates StringTokenizer with specified
string, delimiter and returnValue. If return value is true,
delimiter characters are considered to be tokens. If it is
false, delimiter characters serve to separate tokens.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Methods
1)boolean hasMoreTokens() - Checks if there are more
tokens available.
2) String nextToken() - Returns the next token from the
StringTokenizer object.
3) String nextToken(String delim) - Returns the next token
based on the delimiter.
4) boolean hasMoreElements() - Same as
hasMoreTokens() method.
5) Object nextElement() - Same as nextToken() but its
return type is Object.
6) int countTokens() - Returns the total number of tokens.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Regular Expressions
•
•
•
•
•
•
•
A regular expression is a sequence of characters that forms a
search pattern.
When you search for a data in a text, you can use this search
pattern to describe what you are searching for.
A regular expression is a single character, or more a complicated
pattern.
These can be used for ‘text search’ as well as ‘text replace’
operations.
In java, java.util.regex package supports regular expression
processing. It lets you define a pattern for searching or manipulating
strings.
These are mainly used for password and email validation in real life
applications.
Java regex API provides 1 interface and 3 classes in java.util.regex
package.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Java regex package
The java.util.regex package provides following classes
and interfaces for regular expressions:1. MatchResult interface
2. Matcher class
3. Pattern class
4. PatternSyntaxException class
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
•
Regular Expressions
REGEX CHARACTER CLASSES :
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Regular Expressions
•
REGEX QUANTIFIERS :
The quantifiers specify the number of occurrences of a character.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Regular Expressions
•
REGEX METACHARACTERS :
The regex metacharacters work as short codes.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Summary
1)Java Strings
2) Constructing Strings
3) Some important methods of Strings
4) StringBuffer class in Java
5) Constructors and methods
6) StringTokenizer Class
7) Constructors and Methods
8) Java Regex
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
toString() method
Printing Objects using toString()
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Java interfaces
A Java interface defines a set of methods but does not
implement them.
A class that implements the interface agrees to implement all
of the methods defined in the interface, thereby agreeing to
certain behavior.
Interfaces are provided in Java for the following reason.
Java supports only single inheritance.
To allow multiple inheritance, an interface can be
implemented to achieve the same purpose.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
An interface is a named collection of method definitions
(without implementations).
An interface can also include variables which are static and
final and must be initialized.
Implementing class can not change them.
Meaning they are constants.
All methods and variables are implicitly public.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Defining an interface
Defining an interface is similar to creating a new class.
An interface definition has two components: the interface
declaration and the interface body.
public interface MyInterface
{
interfaceBody
}
if an implementing class provides partial implementation it
should be declared abstract.
One interface can inherit another interface by using
extends.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
One class can implement any number of interfaces thus
simulating multiple inheritance
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Using clone()
The clone() method Object class generates a duplicate copy of the object
on which it is called.
❑ Only classes that implement the Cloneable interface can be
cloned.
❑ The Cloneable interface has no members defined.
❑ When a clone is made, the constructor is not called. A clone is
simply an exact copy of the original.
❑ Cloning is potentially dangerous action, because it can cause
unintended side effects.
Object clone() throws CloneNotSupportedException
// creates a new object that is the same as the invoking object.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Because Cloning can cause unintended side effects, clone() is declared as
a protected method in Object class.
This means that it must either be called from within a method defined by the
class that implements Cloneable interface , or it must be overridden
explicitly by that class so that it becomes public.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Cloning Example
length=10
Multiple refs. Of an object
width=20
myBox
Box myBox= new Box();
Line l
Box newBox;
newBox
newBox= myBox;
newBox.length=100;
Line obj.
myBox.l.length=50;
newBox.l.length=50;
cloning an object
Box myBox= new Box();
myBox
length=40
length=10
width=20
Line l
Box newBox;
length=40
newBox= myBox.clone();
length=10
newBox.length=100;
width=20
myBox.l.length=50;
newBox.l.length=50;
Prof.R.Gururaj
newBox
Object Oriented Programming
Line l
BITS Pilani, Hyderabad Campus
Summary
1)Java Strings
2) Constructing Strings
3) Some important methods of Strings
4) StringBuffer class in Java
5) Constructors and methods
6) StringTokenizer Class
7) Constructors and Methods
8) Java Regex
9) using toString()
10) Java interfaces
11) Cloning in Java
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Java AWT
Ch.23 and 24 of R1.
The Complete Reference- Java, 7th Edition, Herbert
Schildt, Tata McGraw Hill Publishing.
And also refer to Class notes.
Java API Documentation
https://docs.oracle.com/javase/7/docs/api/
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Contents
❖ AWT
❖ Component
❖ Event Handling
❖ Frame and Controls
❖ Layout Managers
❖ JFC and Swing
❖ Sample java programs on AWT/Swing
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
AWT
AWT stands for Abstract Windowing Toolkit.
GUI design in Java is provided by a set of windowing classes available
in the java.awt package.
Using AWT we can create Applet and standalone windows that run in
GUI environments.
In java the various GUI building blocks are called components(visual
components).
These components, in turn , are placed inside a java object called
container.
After creating the components one has to arrange them on the screen
and this is done by the
various layout managers provided by the
java.awt.
The user interface, once created, can be programmed to respond to
various events.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
JAVA AWT
Java AWT (Abstract Window Toolkit) is an API to develop
GUI or window-based applications in java.
Java AWT components are platform-dependent i.e.
components are displayed according to the view of the
operating system. AWT is heavyweight i.e. its
components use the resources of OS.
The java.awt package provides classes for AWT API such
as TextField, Label, TextArea, RadioButton, CheckBox,
Choice, List etc.
BITS Pilani, Hyderabad Campus
The hierarchy of java AWT classes are given below:
BITS Pilani, Hyderabad Campus
AWT
So, broadly in this chapter we will cover the following
topics.
·
Components
·
Layout Managers
·
Event Handling
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Components
A component is an object having a graphical representation
that can be displayed on the screen and that can interact
with the user. Examples of components are the buttons,
checkboxes, and scrollbars of a typical graphical user
interface. Useful methods of component class:
• public void add(component c) - Inserts a component on this
component.
• public void setSize(int width,int height) - sets the size (width
and height) of the component.
• public void setLayout(LayoutManager m) - defines the layout
manager for the component.
• public void setVisible(boolean status) - changes the visibility
of the component, by default false.
BITS Pilani, Hyderabad Campus
CONTAINER:
Containers are an integral part of AWT GUI components. A container
provides a space where a component can be located. A Container in
AWT is a component itself and it adds the capability to add components
to itself. Following are noticeable points to be considered.
• Subclasses of Container are called as Container. For example Panel,
Frame and Window.
• Container can add only components to itself.
• A default layout is present in each container which can be overridden
using setLayout method.
Following is the list of commonly used containers while designed GUI
using AWT:
• Frame
• Panel
• Window
BITS Pilani, Hyderabad Campus
FRAME:
The Frame is the container that contains the title bar and
can have menu bars. It can have other components like
button, textfield etc.
To create a simple awt example, you need a frame. There
are two ways to create a frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class (association)
BITS Pilani, Hyderabad Campus
Important Constructors
• Frame() - Constructs a new instance of Frame that is
initially invisible.
• Frame(String title) - Constructs a new, initially invisible
Frame object with the specified title.
BITS Pilani, Hyderabad Campus
AWT Components
1)
How to Use Buttons
2)
How to Use Canvases
3)
How to Use Checkboxes
4)
How to Use Choices
5)
How to Use Dialogs
6)
How to Use Frames
7)
How to Use Labels
8)
How to Use Lists
9)
How to Use Menus
10)
How to Use Panels
11)
How to Use Scrollbars
12)
How to Use Scroll Panes
13)
How to Use TextAreas and TextFields
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Event handling
Source generates an event.
Then an appropriate event object is created and sent to one or more
listeners.
The listeners simply wait till an event is notified.
Once received, listeners process the event and then return.
Here the event processing, and the event generation interface are
cleanly separated.
The interface element is able to delegate the processing action to a
different entity.
This is called delegation event model.
Listeners must register themselves with event sources.
An event source can send events to those which are registered.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
ActionListener
p v actionPerformed (AE e);
Notify ActionEvent
MyListener
p v actionPerformed (AE e)
{
code
}
myButton
Button myButton;
myButton.addActionListener(new MyListener());
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Java AWT classes
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Java AWT classes
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Java AWT events
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Java AWT event Listeners and
Adapters
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Events and Sources
ActionEvent
clicked
when button click, menu item selected, list item double
ItemEvent
selected
when checkbox or list items are clicked, menu item
KeyEvent
when input is received from key board
MouseEvent(5)when mouse dragged, moved, clicked, pressed or
released, enter a component.
WindowEvent(7)
opened etc.
when window activated, closed, min, max,
ComponentEvent
by component
ContainerEvent
by container
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
LAYOUT MANAGERS
A container has a layout manager to arrange its components.
The layout managers provide a level of abstraction to map
your user interface on all windowing systems, so that the
layout can be platform-independent.
AWT provides the following layout managers (in package
java.awt):
• FlowLayout
• Gridlayout
• BorderLayout
• GridBagLayout
• BoxLayout
• CardLayout
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Container’s setLayout() method
A container has a setLayout() method to set its layout
manager:
To set up the layout of a Container (such as Frame,
JFrame, Panel, or JPanel), you have to:
∙ Construct an instance of the chosen layout object, via new
and constructor, e.g., new FlowLayout())
∙ Invoke the setLayout() method of the Container, with the
layout object created as the argument;
∙ Place the GUI components into the Container using the
add() method in the correct order; or into the correct
zones.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Frame f= new Frame();
f.setLayout(new FlowLayout());
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
About some important
Layout Managers
FlowLayout:
In the java.awt.FlowLayout, components are arranged from
left-to-right inside the container in the order that they are
added The actual appearance depends on the width of
the display window.
Constructors:
public FlowLayout();
public FlowLayout(int alignment);
public FlowLayout(int alignment, int hgap, int vgap);
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
// alignment: FlowLayout.LEFT (or LEADING),
FlowLayout.RIGHT (or TRAILING), or
FlowLayout.CENTER
// hgap, vgap: horizontal/vertical gap between the
components
// By default: hgap = 5, vgap = 5, alignment =
FlowLayout.CENTER
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
GridLayout:
In java.awt.GridLayout, components are arranged in a grid
(matrix) of rows and columns inside the Container.
Components are added in a left-to-right, top-to-bottom
manner in the order they are added (via method
aContainer.add(aComponent)).
Constructors:
public GridLayout(int rows, int columns);
public GridLayout(int rows, int columns, int hgap, int vgap);
// By default: rows = 1, cols = 0, hgap = 0, vgap = 0
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
BorderLayout:
In java.awt.BorderLayout, the container is divided into 5
zones: EAST, WEST, SOUTH, NORTH, and CENTER.
Components are added using method
aContainer.add(acomponent, zone), where zone is either
BorderLayout.NORTH (or PAGE_START),
BorderLayout.SOUTH (or PAGE_END),
BorderLayout.WEST (or LINE_START),
BorderLayout.EAST (or LINE_END), or
BorderLayout.CENTER.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
CardLayout:
A CardLayout object is a layout manager for a container.
It treats each component in the container as a card. Only
one card is visible at a time, and the container acts as a
stack of cards. ... Object) method can be used to
associate a string identifier with a given card for fast
random access.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Canvas; Graphics; Font
Canvas: The Canvas class controls and represents a blank
rectangular area where the application can draw. It
inherits the Component class.
Graphics: The Graphics class is the abstract base class
for all graphics contexts that allow an application to draw
onto components .
Font: It represents the font that are used to render the
text.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
JFC and Swing
Swing is the part of JFC (Java Foundation Classes) built on
the top of AWT and written entirely in Java. The
javax.swing API provides all the component classes like
JButton, JTextField, JCheckbox, JMenu, etc.
The components of Swing are platform-independent, i.e.,
swing doesn't depend on the operating system to show
the components. Also, the Swing's components are
lightweight.
Swing: lightweight, faster, more components, platform
independent look and feel, takes less memory,
javax.swing package.
BITS Pilani, Hyderabad Campus
Summary
1.
2.
3.
4.
5.
6.
7.
8.
9.
Introduction to AWT
Components, Containers, controls
Event handling model
Listeners, Events, Adapters
Working with Frame, Panel, Button, Label, Choive, Dialog
etc.
Writing event handlers
Layout managers (Flow LO, Border LO, Grid LO, Card LO)
Introduction to Java Swing (JFC)
Sample java programs on AWT/Swing
BITS Pilani, Hyderabad Campus
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
Exception
Handling
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Ch.10 of R1.
The Complete Reference- Java, 7th Edition, Herbert
Schildt, Tata McGraw Hill Publishing.
And also refer to Class notes.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Content
1. Exception Handling Fundamentals
2. Exception Types in Java
3. Use of try-catch
4. Nested try statements
5. Keywords- throw, throws, finally
6. Creating own exception subclasses
7. Examples
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Exception
Exception
Is an abnormal condition that arises in a code
sequence at run time.
It is an error condition.
Exception handling in Java
This brings run-time error handling mechanism into
object-oriented world.
Java exception is an object that describes the error
condition that has occurred in a piece of code.
Code throws appropriate exception object and its
caught and processed properly.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Ex:
class Exc{
public static void main(String args[ ]) {
int d,a;
d=0;
a=42 / d;
System.out.println(“Divide 42 by zero.”);
}
}
java.lang.ArithmeticException: / by zero
at Exc.main(Exc.java: 4)
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Java uses “try- catch – throw – throws – finally”
keywords.
Program Statements that you want to monitor for
exception are contained within a ‘try’ block.
Your code can catching exception using ‘catch’ and handle
it in some rational manner.
To manually throw an exception, use the key word
‘throw’.
Any exception thrown out of a method must be specified
as such by a ‘throws’ clause.
Any code that absolutely must be executed before a
method returns is put in a ‘finally’ block.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
The general form of Exception handling in Java
{
try{
// code expected to throw an exception
}
catch(Exception type1){
// exception handler for type1
}
catch (Exception type2){
// exception handler for type2
}
finally{ // code to be executed before try block ends
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
The Exception types in Java
Object
Throwable
Error
Exception
RuntimeException
IllegalAccessException
InstantiationException
ArithmeticException
NosuchMethodException
ClassCastException
Etc.
Java.lang package
IlegalArgumentException
IndexOutOfBoundsException
NullPointerException
Prof.R.Gururaj
NumberFormatException
ArrayIndexOutOfBoundsExceptino
Object Oriented Programming
BITS Pilani, Hyderabad Campus
All exception types are subclasses of built-in class Throwable
which is subclass of Object .
Class ‘Trowable’ has two subclasses that partition exceptions
into two distinct branches.
One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch.
A subclass of Exception, is called RuntimeException.
Exceptions of this type are automatically defined for the
programs that you write and include things such as division by
zero and invalid array indexing.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Exceptions of type Error are used by the Java run-time
system to indicate errors having to do with the run-time
environment, itself. Stack overflow is an example of such an
error.
Exception objects should be throwable i.e, the class called
Throwable should be in the hierarchy of Exception class.
User created exception are generally subclasses of class
Exception.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Using try and catch
try{
Statement 1;
Statement 2;
}
catch(Exception e)
{
exception handler code ;
}
The catch should be immediately after try.
There should be no statements in between two, else it is an error.
Exception object is said to be thrown out of ‘try’ block which is caught in
the ‘catch’ block.
The control does not return to try because we are not calling ‘catch’ as a
method.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Sample
class ExDemo1
{
public static void main(String args[ ])
{
int d,a;
try{
d=0;
a=42 / d;
System.out.println("Divide 42 by zero.");
}
catch (ArithmeticException e)
{ System.out.println("Division by zero is not allowed");
}
System.out.println("After catch statement.");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo1
Division by zero is not allowed
After catch statement.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo2
{
public static void main(String args[ ])
{
int a[]={20,40,60,80};
System.out.println("last element in array is :"+a[4]);
System.out.println("last Statement");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo2
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 4
at ExDemo2.main(ExDemo2.java:8)
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo3
{
public static void main(String args[ ])
{
int a[]={20,40,60,80};
try{
System.out.println("last element in array is :"+a[4]);
System.out.println("\nlast statement in try ");
}
catch(Exception e)
{
System.out.println("\n I handle the Exception on my own");
}
finally
{
System.out.println("Leaving try block bye..");
}
System.out.println("\nlast statement in program :");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo3
I handle the Exception on my own:
Leaving try block bye..
last statement in program :
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Ex
class ExDemo4
{ public static void main(String args[ ])
{ int a[]={20,40,60,80};
try{
System.out.println("last element in array is :"+a[4]);
System.out.println("\nlast statement in try ");
}
catch(ArithmeticException ae)
{ System.out.println("\n I handle this array index out Exception \n:");
}
finally
{System.out.println("In finally block code..");
}
System.out.println("\nlast statement in main program :");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo4
In finally block code..
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 4
at ExDemo4.main(ExDemo4.java:8)
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
A try without catch or finally is an error at compile-time.
class ExDemo1A
{
public static void main(String args[ ])
{
int d,a;
try{
d=0;
a=42 / d;
System.out.println("Divide 42 by zero.");
}
System.out.println("After catch statement.");
}
}
C:\Users\Admin\JavaPrograms>javac ExDemo1A.java
ExDemo1A.java:7: error: 'try' without 'catch', 'finally' or resource declaration
s
try{
^
1 error
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
A try without catch and only with finally is OK.
class ExDemo1A
{
public static void main(String args[ ])
{
int d,a;
try{
d=0; a=42 / d;
System.out.println("Divide 42 by zero.");
}
finally
{System.out.println("In finally ");}
System.out.println("After catch statement.");
}
}
C:\Users\Admin\JavaPrograms>java ExDemo1A
In finally
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExDemo1A.main(ExDemo1A.java:9)
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
A finally without try will not be compiled.
A catch without try will not be compiled.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Multiple catches for a ‘try’
block
If there is a single catch for a try block, the exception
handling will be generalized.
Different types of exceptions should be handled in different
ways i.e., more than one catch block for a single try.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Ex
class EX{
method(){
//code
try{
//code expected to throw exception.
}
catch(
){
//handler.
}
catch( ) {
//handler.
}
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo5
{
public static void main(String args[ ])
{ int a[]={20,40,60,80};
try{System.out.println("last element in array is :"+a[4]);
System.out.println("\nlast statement in try ");
}
catch(ArithmeticException ae)
{
System.out.println("\n I handle this Arithmetic Exception \n");
}
catch(ArrayIndexOutOfBoundsException aie)
{
System.out.println("\n I handle this array index out Exception \n");
}
finally
{
System.out.println("In finally block code.");
}
System.out.println("\nlast statement in main program :");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo5
I handle this array index out Exception
In finally block code.
last statement in main program :
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo6
{
public static void main(String args[ ])
{
boolean b=true; boolean a=false;
if (b){ System.out.println("\n It is TRUE");}
else{System.out.println("\n It is FALSE");}
if (b==true & a==false)
{System.out.println("\n It is OK");}
}
}
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo6
It is TRUE
It is OK
BITS Pilani, Hyderabad Campus
class ExDemo7
{
public static void main(String args[ ])
{
boolean b=true; boolean a=false;
if (b){ System.out.println("\n It is TRUE");}
else{System.out.println("\n It is FALSE");}
if (b==true & a==false)
{System.out.println("\n It is OK");}
if (b==true & b==false)
{System.out.println("\n It is NOT Correct");}
}
}
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo7
It is TRUE
It is OK
BITS Pilani, Hyderabad Campus
class ExDemo8
{
public static void main(String args[ ])
{
boolean b=true;
if (b){ System.out.println("\n It is TRUE");return;}
else{System.out.println("\n It is FALSE");return;}
System.out.println("\n Last statemant");
}
}
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>javac ExDemo8.java
ExDemo8.java:10: error: unreachable statement
System.out.println("\n Last statemant");
^
1 error
BITS Pilani, Hyderabad Campus
In multiple catch the catch block which can catch all types
exceptions must be put in the end because if non of the
catch blocks catches the exception then only it should catch
it.
It is important to remember that Exception subclasses must
come before their super class.
This is because a catch statement that uses a super class will
catch exceptions of that type and all its subclasses. Thus a
subclass would never be reached, if it comes after the
super class.
In java un reachable code is an error.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo{
public static void main(String org[])
{
//code
try{
//code expected to throw arithmetic exception.
}
catch(ArithmeticException e )
{
//handler.
}
catch(ArrayIndexOutOfBoundsException aie)
{
//handler.
}
catch(Exception e )
{
//handler.
}
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo9
{
public static void main(String args[ ])
{
int a[]={20,40,60,80};
try{
System.out.println("last element in array is :"+a[4]);
System.out.println("\nlast statement in try ");
}
catch(Exception e)
{ System.out.println("\n I handle this Exception \n:");}
catch(ArithmeticException ae)
{ System.out.println("\n I handle this Arithmetic Exception \n:");}
catch(ArrayIndexOutOfBoundsException ae)
{ System.out.println("\n I handle this array index out Exception \n:"); }
finally
{System.out.println("In finally block code..");}
System.out.println("\nlast statement in main program :");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>javac ExDemo9.java
ExDemo9.java:15: error: exception ArithmeticException has already
been caught
catch(ArithmeticException ae)
^
ExDemo9.java:19: error: exception ArrayIndexOutOfBoundsException
has already been caught
catch(ArrayIndexOutOfBoundsException ae)
^
2 errors
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo9
{
public static void main(String args[ ])
{
int a[]={20,40,60,80};
try{
System.out.println("last element in array is :"+a[4]);
System.out.println("\nlast statement in try ");
}
catch(ArithmeticException ae)
{ System.out.println("\n I handle this Arithmetic Exception \n:");}
catch(ArrayIndexOutOfBoundsException ae)
{ System.out.println("\n I handle this array index out Exception \n:"); }
catch(Exception e)
{ System.out.println("\n I handle this Exception \n:");}
finally
{System.out.println("In finally block code..");}
System.out.println("\nlast statement in main program :");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo10
I handle this array index out Exception
In finally block code..
last statement in main program :
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo11
{
public static void main(String args[ ])
{
int a[]={20,40,60,80};
try{
System.out.println("last element in array is :"+a[4]);
System.out.println("\nlast statement in try ");
}
try{ System.out.println("last element in array is :"+a[4]);}
catch(ArrayIndexOutOfBoundsException ae)
{ System.out.println("\n I handle this array index out Exception \n:"); }
catch(Exception e)
{ System.out.println("\n I handle this Generic Exception \n:");}
finally
{
System.out.println("In finally block code..");
}
System.out.println("\nlast statement in main program :");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>javac ExDemo11.java
ExDemo11.java:6: error: 'try' without 'catch', 'finally' or resource
declarations
try{
^
1 error
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo12
{ public static void main(String args[ ])
{
int a[]={20,40,60,80};
try{
System.out.println("last element in array is :"+a[4]);
System.out.println("\nlast statement in try ");
}
catch(ArrayIndexOutOfBoundsException ae)
{ System.out.println("\n I handle this array index out Exception \n:");
}
finally
{System.out.println("In finally block code..");
}
try{ System.out.println("last element in array is :"+a[4]/0);
}
System.out.println("\nlast statement in main program :");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>javac ExDemo12.java
ExDemo12.java:18: error: 'try' without 'catch', 'finally' or resource
declarations
try{ System.out.println("last element in array is :"+a[4]/0);}
1 Error
^
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo13
{ public static void main(String args[ ])
{
int a[]={20,40,60,80};
try{
System.out.println("last element in array is :"+a[4]);
System.out.println("\nlast statement in try ");
}
catch(ArrayIndexOutOfBoundsException ae)
{ System.out.println("\n I handle this array index out Exception \n:");
finally
{System.out.println("In finally block code..");}
try{ System.out.println("last element in array is :"+a[2]/0);}
catch(ArithmeticException ae)
{ System.out.println("\n I handle this Arithmetic Exception \n:");}
System.out.println("\nlast statement in main program :");
}
}
Prof.R.Gururaj
Object Oriented Programming
}
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo13
I handle this array index out Exception
:
In finally block code..
I handle this Arithmetic Exception
:
last statement in main program :
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Nesting try
The trys can be nested.
In case of nested try any exception object is thrown in inner
try block and there is no matching catch for that particular
exception , then it searches for a catch block after the outer
try block.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Ex
class NestedTryDemo
{
public static void main(String org[])
{
try{
int b=100;
System.out.println("outer try");
try{
int d=b/0;
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(e); }
System.out.println("end of inner try");
}
catch(Exception e)
{
System.out.println(e); }
System.out.println(“Last statement in main metod:”);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo14
outer try
java.lang.ArithmeticException: / by zero
Last statement in main metod:
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo15
{
public static void main(String org[])
{
try{
int b=100;
System.out.println("outer try");
try{
int d=b/0;
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(e +"\n"); }
finally{System.out.println("In the finally block of inner try");}
System.out.println("end of inner try");
}
catch(Exception e)
{ System.out.println(e+"\n");}
finally{System.out.println("In the finally block of outer try");}
System.out.println("Last statement in main metod:");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo15
outer try
In the finally block of inner try
java.lang.ArithmeticException: / by zero
In the finally block of outer try
Last statement in main metod:
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo16
{
public static void main(String org[])
{
int a[]={20,40,60,80};
try{
int b=100;
System.out.println("start outer try");
try{
a[5]=400; System.out.println("in nested try\n");
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(e +"\n"); }
finally{System.out.println("In the finally block of inner try");}
System.out.println("end of inner try");
}
catch(Exception e)
{ System.out.println(e+"\n");}
finally{System.out.println("In the finally block of outer try");}
System.out.println("Last statement in main metod:");
}
}
Prof.R.Gururaj
Object Oriented Programming
}
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo16
start outer try
java.lang.ArrayIndexOutOfBoundsException: 5
In the finally block of inner try
end of inner try
In the finally block of outer try
Last statement in main metod:
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo17
{
public static void main(String org[])
{
int a[]={20,40,60,80};
try
{ a[5]=400;
System.out.println("in try\n");
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(e +"\n");
a[7]=800;
}
finally{System.out.println("In the finally block of ");}
System.out.println("Last statement in main metod:");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo17
java.lang.ArrayIndexOutOfBoundsException: 5
In the finally block
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 7
at ExDemo17.main(ExDemo17.java:11)
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo17
{
public static void main(String org[])
{
int a[]={20,40,60,80};
try
{ a[5]=400; System.out.println("in nested try\n");
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(e +"\n");
a[7]=800; System.out.println("last in catch \n");
}
finally{System.out.println("In the finally block");}
System.out.println("Last statement in main metod:");
}
}
Prof.R.Gururaj
Object Oriented Programming
}
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo17
java.lang.ArrayIndexOutOfBoundsException: 5
In the finally block
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 7
at ExDemo17.main(ExDemo17.java:11)
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Using throw
try{
------;
throw exceptionobject;
}
catch( exception )
{
//handler.
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo18
{
public static void main(String orgs[])
{
int a;
a= Integer.parseInt(args[0]);
a=a*2;
System.out.println("value is :"+a);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo18
{
public static void main(String args[])
{
int a;
a= Integer.parseInt(args[0]);
a=a*2;
System.out.println("value is :"+a);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo18 20
value is :40
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo18 ab
Exception in thread "main" java.lang.NumberFormatException: For input
string: "ab"
at
java.lang.NumberFormatException.forInputString(NumberFormatExcepti
on. java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at ExDemo18.main(ExDemo18.java:6)
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo19
{
public static void main(String args[])
{
int a;
a= Integer.parseInt(args[0]);
try{
if (a >100) throw new Exception();
}
catch(Exception e){
System.out.println("Exeption is:"+e);}
System.out.println("\n Last in main");
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo19 120
Exeption is:java.lang.Exception
Last in main
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo19
{
public static void main(String args[])
{
int a;
a= Integer.parseInt(args[0]);
try{
if (a >100) throw new Exception();
}
catch(Exception e){ a=100;}
a=a*2;
System.out.println("\n Doubled Value of a is:"+a);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo19 130
Doubled Value of a is:200
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo19 50
Doubled Value of a is:100
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Use of throws
If a method is capable of causing an exception that
it does not handle, it must specify this behavior
so that callers of the method can guard
themselves against that exception.
We do this by including a throws clause in the
method’s decleration.
A throws clause lists the types of exceptions that a
method might throw.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
void method( ) throws ABCException
{//ABC exception can be thrown which is not handled
here.
------ ;
}
try {
method( );
}
catch( ABCException e ){
// handle the Exception e.
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo20
{
public static void main(String args[])
{
Line lin= new Line(100);
lin.doubleLength();
}
}
class Line
{
int length;
Line(int l)
{length=l;}
void doubleLength()
{
if(length>100) throw new Exception();
System.out.println("\n Doubled Value of a is:"+length*2);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>javac ExDemo20.java
ExDemo20.java:18: error: unreported exception Exception;
must be caught or declared to be thrown
if(length>100) throw new Exception();
^
1 error
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo20
{
public static void main(String args[])
{
Line lin= new Line(100);
try{ lin.doubleLength(); }
catch(Exception e){System.out.println("\n Sorry Value is greater than 100");}
}
}
class Line
{
int length;
Line(int l)
{length=l;}
void doubleLength() throws Exception
{
if(length>100) throw new Exception();
System.out.println("\n Doubled Value of a is:"+length*2);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo20
Doubled Value of a is:200
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo20
Sorry Value is greater than 100
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Unchecked exceptions:
Inside the standard package java.lang, Java defines
several exception classes.
Unchecked exceptions: They need not be
included in any method’s throws list.
The compiler does not check to see if a method
handles or throws these exception.
Ex:
ArithmeticException
ArrayIndexOutOfBoundException
ArrayStoreException
ClassCastException
NullPointerException
NumberFormatException
Etc.,
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Checked exceptions:
These must be included in a method’s throws list if
that method can generate one of these
exceptions and does not handle it, itself.
Ex:
ClassNotFoundException
IllegalAccessException
InstantiationException
InterruptedException Etc.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
User Created Exceptions
User can create his own exception classes provided the
classcalled Throwable is present in the hierarchy.
Generally we create exceptions by subclassing the class
called Exception.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class InvalidAgeException extends Exception
{
int s;
InvalidAgeException()
{
s=333;
}
public String toString()
{
return s+“: Invalid Age Exception: Age Meaningless:";
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
class ExDemo21
// Program to test InvalidAgeException
{
public static void main(String a[])
{
try
{
insertAge(11);
}
catch(InvalidAgeException iae)
{
System.out.println("caught"+iae);
}
}
static void insertAge(int a) throws InvalidAgeException
{
if(a<1 || a>100)
throw new InvalidAgeException();
else
System.out.println("Inserted Data for Age:"+a);
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C:\Users\Admin\JavaPrograms>java ExDemo21
Caught 333: Invalid Age Exception: Age Meaningless:
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Summary
Exception handling Java
Try catch finally
Throw
Throws
Exception hierarchy
Nested try blocks
User Defined Exceptions
Examples
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
CS F213
Object Oriented Programming
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
By Arun Vadekkedhil
Agenda
Java Multi-threading
❖
❖
❖
❖
❖
Introduction to multi threading
Advantages of Multi threading
Java Thread Model
Thread Class & Runnable Interface
run() method,
Creating a Thread
❖ Extend Thread Class
❖ Use Runnable Interface
Methods of Thread Class
❖
❖
❖
❖
Sleep()
join()
wait()
notify()
Synchronization in threads
❖
❖
Synchronized keyword (Monitor)
Synchronized blocks
2
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Introduction to Multi
Threading
Multi threaded / Multi threading means to split a task into parts
which then be executed concurrently in its own execution
path.
Each part of the task (in our case a program) is called a thread
Each thread defines its own path of execution.
New Terminology = “CONCURRENCY”
Multi threading is a specialized form of multi tasking
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Introduction to Multi
Threading - Paradigms
Is Multi Threading Parallel Process?
• To the untrained eye, it seems like threads and parallel
process are one and the same – In reality it’s not
• Parallel Process
•
•
We define two processes to be in parallel when they have the capability to run
uninterrupted on a dedicated resource (CPU) till its completes
Example : Now at the same time, in BITS multiple lectures are going on in
parallel
• Concurrent Process
•
•
We define Concurrency where, progress is observed on more than one task,
however, all the tasks cannot be executed at the same time.
Example: In this session, if another student / TA has to share the screen, the will
have to wait till I stop my screen sharing
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Introduction to Multi Threading –
Process & Threads
Process : We are familiar with Process, we can equate it to
a program that is executing (eg, web browser, JVM, DB
engine etc)
In Process based MT, we can run two or more program
simultaneously, subject to hardware constraints.
Thread: Threads are concurrent execution path within a
process or program.(eg, while browsing, you can play
music videos or while using word you can print while
formatting text). Only condition is that these actions run
on separate thread
In thread based MT, we can run two or more threads
simultaneously, subject to hardware constraints.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Introduction to Multi Threading –
Process & Threads
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
The Java Thread Model
The Java Thread Model
Thread: program unit that is executed independently
• Multiple threads run simultaneously
Virtual machine executes each thread for short time slice
• Thread scheduler activates, deactivates threads
Illusion of threads running in parallel
• Multiprocessor computers: threads actually run in parallel
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Benefits of Java
Multithreading
Loop/polling as in single-threaded systems is
eliminated.
• One thread can be paused without stopping other parts of the
program.
Allows animation loops to sleep between frames
without causing the system to pause.
• When a thread is blocked in a program only that thread is paused
and not the entire program. All other threads continue to run.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Introduction to Multi Threading –
Thread States (Life Cycle)
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Introduction to Multi Threading –
Thread Creation
There are two common ways to write a thread in Java:
Write a class that implements the Runnable interface, then
associate an instance of your class with a java.lang.Thread
object.
Write a class that extends the Thread class.
Either you write a class that implements Runnable, or you
extend a class that already implements
In either case, you define the one method in Runnable: public
void run()
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Introduction to Multi Threading –
Thread States (Life Cycle)
The body of the run() method is the path of execution for your
thread.
When the thread starts running, the run() method is invoked,
and the thread becomes dead when the run() method runs to
completion
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The Runnable Interface Type
Running Threads
Define class that implements Runnable
Runnable has one method void run()
Place thread action into run method
Construct object of runnable class
Construct thread from that object
Start thread
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Running Threads
public class MyRunnable implements Runnable
{
public void run()
{
thread action
}
} ...
Runnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Thread Example
• Run two threads in parallel
• Each thread prints the content of ‘greetings’ 10 times
for (int i = 1; i <= 10; i++)
{
System.out.println(i + ": " + greeting);
Thread.sleep(100);
}
• After each printout, sleep for 100 millisec
• All threads should occasionally yield control
• sleep throws InterruptedException
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Running Threads
Use Thread Class &
Extend it
Instantiate & Start
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Thread Example
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Thread Priorities
Java assigns to each thread a priority that determines
how that thread should be treated with respect to the
others
As an absolute value, a priority is meaningless; a higherpriority thread doesn’t run any faster than a lowerpriority thread if it is the only thread running.
Instead, a thread’s priority is used to decide when to switch
from one running thread to the next. This is called a
context switch.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Thread Priorities
A thread can voluntarily relinquish control. This is done by
explicitly yielding, sleeping, or blocking on pending I/O.
In this scenario, all other threads are examined, and
the highest-priority thread that is ready to run is given the
CPU.
• A thread can be preempted by a higher-priority thread. In
this case, a lower-priority thread that does not yield the
processor is simply preempted—no matter what it is
doing—by a higher-priority thread. Basically, as soon as
a higher-priority thread wants to run, it does. This is
called preemptive multitasking.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Monitors
As concurrency introduces asynchronous behaviour, it is
imperative that java provides a mechanism to marshall
threads.
Objective is to ensure that the threads do not conflict with
each other nor enter into a deadlock.
Java implements a concept called monitor to prevent such
situations
Monitor only allows one thread to execute, so in case of
using shared resources, other threads will have to wait
till the thread finishes. (Example trial room in an apparel
store)
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Messaging
Since threads run asynchronously, it is imperative there is a
good communication between them.
Languages like C / C++ depend on OS to provide the
infrastructure to manage inter thread communication.
However java provides specialized methods to ensure that
the communication happens (wait, notify etc)
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Let’s not Forget – The Main
When a Java program starts up, one thread begins running
immediately. This is usually called the main thread of your
program, because it is the one that is executed when your
program begins.
The main thread is important for two reasons:
• It is the thread from which other “child” threads will be
spawned.
• Often, it must be the last thread to finish execution
because it performs various shutdown actions.
23/07/2017
SSZC313 Object Oriented
Programming and Design
22
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Scheduling Threads
Scheduling Threads
Scheduler activates new thread if
– a thread has completed its time slice
– a thread has blocked itself
– a thread with higher priority has become runnable
Scheduler determines new thread to run
–
–
–
–
looks only at runnable threads
picks one with max priority (1 = Low; 5 = Normal ; 10 = High)
Main thread has a priority of 5
Thread groups usually have the same priority
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Thread States
Threads exist in various states:
•
New
✓
•
Runnable
✓
•
•
•
When it gets CPU time
Resumed/unblocked
✓
Reason for blocking has
gone away
Blocked/Suspended
✓
✓
✓
•
Start
Running
Ready to run
✓
•
Created
✓
Sleeping
Waiting for I/O
Waiting to acquire lock
(later)
Waiting for condition (later)
✓
✓
Terminated
Can not be resumed
Dead
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Thread Priorities:
Context Switch
Each thread has a priority which decides which tread is
to get a higher preference.
Rules between thread of different priority:
• A thread can voluntarily relinquish control.
•
A thread explicitly sleeps/blocks on pending I/O etc. Control is taken by the
highest priority thread amongst those waiting for their turn to run.
• A thread can be preempted by a higher priority thread.
•
A higher priority thread takes control (prempts) from a lower priority thread no
matter what it is doing.
Rules between thread of equal priority:
• Windows: time-sliced in round-robin fashion.
• Other O/S: Thread must voluntarily yield control to their
peers.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The Thread Class and the
Runnable Interface
Method
Meaning
getName
Obtain a thread’s name.
getPriority
Obtain a thread’s priority
isAlive
Determine if a thread is running
join
Wait for a thread to be terminated
run
Entry point for the thread
sleep
Suspend a thread for a period of time
start
Start a thread by calling its run method
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Terminating Threads
Terminating Threads
• Thread terminates when run exits
• Sometimes necessary to terminate running thread
• Don't use this deprecated stop method
• Interrupt thread by calling interrupt
• Calling t.interrupt() doesn't actually interrupt t;
• just sets a flag
• Interrupted thread must sense interruption and exit its
run method
• Interrupted thread has chance to clean up
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Sensing Interruptions
• Thread could occasionally call
Thread.currentThread().isInterrupted()
• sleep, wait throw InterruptedException when thread
interrupted
. . . and then the interruption status is cleared!
• More robust: Sleep occasionally, catch exception and
react to interruption
• Recommendation: Terminate run when sensing
interruption
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Sensing Interruptions
public class MyRunnable implements Runnable
{
public void run()
{
try
{
while (...)
{
do work
Thread.sleep(...);
}
}
catch (InterruptedException e) {}
clean up
}
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Thread Synchronisation
Synchronization
Java has a unique language level support to ensure that
shared resources are used by one thread at a time. C
and C++ use OS primitives to achieve this.
• Using Synchronized Methods
•
While a thread is inside a synchronized method all other synchronized methods
in the same instance have to wait.
• Using Synchronized Statement
•
If the class is not available for modification and the methods in this class do not
contain synchronized methods, place all calls to methods you wish to
synchronize in a synchronized block.
synchronized (object){
// statements to be synchronized: target.call(msg);
//
where object is target.
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Messaging
Java’s messaging system allows a thread to enter a
synchronized method on an object and then wait there
untill some other thread explicity notifies it to come out.
• wait()
•
Tells the calling thread to go to sleep and sleep until it is told to wake up by
another thread. By passing a parameter to wait the extent of wait can be
controlled.
• notify()
•
Wakes up a thread that called wait() on the same object
• notifyAll()
•
Wake up all the threads that called wait() on the same object. Only one of the
threads will however be granted access.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Illustration
Producer Thread
int i = 1;
while (i <= greetingCount)
{
if (!queue.isFull())
{
queue.add(i + ": "
+ greeting);
i++;
}
Thread.sleep(
(int)(Math.random() * DELAY));
}
Consumer Thread
int i = 1;
while (i <= greetingCount)
{
if (!queue.isEmpty())
{
Object greeting =
queue.remove();
System.out.println(greeting);
i++;
}
Thread.sleep(
(int)(Math.random() * DELAY));
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Race Condition
Thread Synchronization
Race Condition Scenario
• Use bounded queue
• Two producers, one
consumer
• Each producer
thread inserts
greetings
• Each consumer
thread removes
greetings
1
2
3
4
5
• First thread calls add and executes
• elements[tail] = anObject;
• First thread at end of time slice
• Second thread calls add and executes
• elements[tail] = anObject; tail++;
• Second thread at end of time slice
• First thread executes
• tail++;
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Race Condition
Expected Program
Output
1: Hello, World!
1: Goodbye, World!
2: Hello, World!
3: Hello, World!
...
99: Goodbye, World!
100: Goodbye, World!
But this may not
happen and the queue
may get corrupted
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Locks
Locks
Thread can acquire lock
• When another thread tries to acquire same lock, it blocks
When first thread releases lock, other thread is unblocked and tries again
Two kinds of locks
Objects of class implementing
java.util.concurrent.Lock interface type,
usually ReentrantLock
Locks that are
built into every
Java object
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Reentrant Locks
Scenario with Locks
aLock =
new ReentrantLock();
...
aLock.lock();
Try
{
protected code
}
finally
{
aLock.unlock();
}
1
• First thread calls add and acquires lock,
then executes elements[tail] =
anObject;
2
• Second thread calls add and tries to
acquire lock, but it is blocked
3
4
• First thread executes tail++;
• First thread completes add, releases
lock
• Second thread unblocked
• Second thread acquires lock, starts
executing protected code
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Deadlocks
Deadlocks
Deadlocks
•
Not enough to synchronize add,
remove
•
if (!queue.isFull()) queue.add(...);
can still be interrupted
•
Must move test inside add method
public void add(E newValue)
{
queueLock.lock();
try
{
while (queue is full)
wait for more space
...
}
finally { qeueLock.unlock(); }
}
•
Problem: nobody else can call remove
Avoiding Deadlocks
• Use conditon object to manage
"space available" condition
private Lock queueLock = new
ReentrantLock();
private Condition
spaceAvailableCondition
= queueLock.newCondition();
•
Call await when condition is not
fulfilled:
public void add(E newValue)
{
...
while (size == elements.length)
spaceAvailableCondition.await();
...
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Avoiding Deadlocks
•
•
Waiting thread is blocked
Condition object manages set of threads that wait for the condition to change
•
•
To unblock, another thread must call signalAll on the same condition object
Call when state changes
public E remove()
{
...
E r = elements[head];
...
spaceAvailableCondition.signalAll(); // Unblock waiting threads
return r;
}
•
All waiting threads removed from wait set, unblocked
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Object Locks
•
•
•
•
Each object has a lock
Calling a synchronized method
acquires lock of implicit parameter
Leaving the synchronized method
releases lock
Easier than explicit Lock objects
public class BoundedQueue<E>
{
public synchronized void
add(E newValue) { . . . }
public synchronized E remove()
{
...
}
...
}
•
•
•
Each implicit lock has one associated
(anonymous) condition object
Object.wait blocks current thread and
adds it to wait set
Object.notifyAll unblocks waiting threads
public synchronized void add(E
newValue)
throws InterruptedException
{
while (size == elements.length)
wait();
elements[tail] = anObject;
. ..
notifyAll(); // notifies threads
waiting to remove elements
}
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Thread Communication
Using Wait & Notify methods
As discussed earlier, multithreading replaces event loop
programming by dividing your tasks into discrete, logical
units. Threads also provide a secondary benefit: they do
away with polling.
Polling is usually implemented by a loop that is used to
check some condition repeatedly.
Since repeated checking is an overhead, it would be better
if we can have a mechanism where some kind of
signalling is sent between threads who are waiting for
shared objects.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Using Wait & Notify methods
The Object class in Java has three final methods that allow threads to
communicate about the locked status of a resource.
wait()
It tells the calling thread to give up the lock and go to sleep until some other
thread enters the same monitor and calls notify().
The wait() method releases the lock prior to waiting and reacquires the lock
prior to returning from the wait() method.
The wait() method is actually tightly integrated with the synchronization lock.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Using Wait & Notify methods
The wait() method is applicable only
on synchronized objects
(monitors)
If called on un-synchronized objects,
it will compile but will throw
IllegalMonitorStateException
The wait() method throws the
exception InterruptedException
When the wait is called, it releases
the lock and then proceeds to
hibernate unlike sleep
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Using Wait & Notify methods
notify()
It wakes up one single thread that called wait() on the same object. It
should be noted that calling notify() does not actually give up a lock on
a resource.
It tells a waiting thread that that thread can wake up. However, the lock
is not actually given up until the notifier’s synchronized block has
completed.
So, if a notifier calls notify() on a resource but the notifier still needs to
perform 10 seconds of actions on the resource within its synchronized
block, the thread that had been waiting will need to wait at least another
additional 10 seconds for the notifier to release the lock on the object,
even though notify() had been called.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Using Wait & Notify methods
General syntax for calling notify() method is like this:
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Producer Consumer Problem
In general, a thread that uses the wait() method confirms that a
condition does not exist (typically by checking a variable) and
then calls the wait() method.
When another thread establishes the condition (typically by
setting the same variable), it calls the notify() method.
The wait-and-notify mechanism does not specify what the specific
condition/ variable value is. It is on developer’s hand to specify
the condition to be checked before calling wait() or notify().
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Producer Consumer Problem
In this exercise, we will
solve producer consumer
problem using wait() and
notify() methods.
To keep program simple and
to keep focus on usage of
wait() and notify() methods,
we will involve only one
producer and one consumer
thread.
23/07/2017
SSZC313 Object Oriented
Programming and Design
53
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Producer Consumer Problem
Producer thread produce a new resource in every 1 second and
put it in ‘taskQueue’.
Consumer thread takes 1 seconds to process consumed
resource from ‘taskQueue’.
Max capacity of taskQueue is 5 i.e. maximum 5 resources can
exist inside ‘taskQueue’ at any given time.
Both threads run infinitely.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Producer Consumer Problem
Here “produce(counter++)” code has been written inside infinite loop so that
producer keeps producing elements at regular interval.
We have written the produce() method code following the general guideline to
write wait() method as mentioned in first section.
Once the wait() is over, producer add an element in taskQueue and called
notifyAll() method. Because the last-time wait() method was called by
consumer thread (that’s why producer is out of waiting state), consumer gets
the notification.
Consumer thread after getting notification, if ready to consume the element as
per written logic.
Note that both threads use sleep() methods as well for simulating time delays
in creating and consuming elements.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Producer Consumer Problem
Here “consume()” code has been written inside infinite loop so that consumer
keeps consuming elements whenever it finds something in taskQueue.
Once the wait() is over, consumer removes an element in taskQueue and
called notifyAll() method. Because the last-time wait() method was called by
producer thread (that’s why producer is in waiting state), producer gets the
notification.
Producer thread after getting notification, if ready to produce the element as
per written logic.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Points to Remember
What happens when notify() is called and no thread is waiting?
In general practice, this will not be the case in most scenarios if these methods
are used correctly. Though if the notify() method is called when no other thread
is waiting, notify() simply returns and the notification is lost.
Since the wait-and-notify mechanism does not know the condition about which
it is sending notification, it assumes that a notification goes unheard if no
thread is waiting. A thread that later executes the wait() method has to wait for
another notification to occur.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Points to Remember
Can there be a race condition during the period that the wait() method
releases OR reacquires the lock?
The wait() method is tightly integrated with the lock mechanism. The object
lock is not actually freed until the waiting thread is already in a state in which it
can receive notifications. It means only when thread state is changed such that
it is able to receive notifications, lock is held. The system prevents any race
conditions from occurring in this mechanism.
Similarly, system ensures that lock should be held by object completely before
moving the thread out of waiting state.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Points to Remember
If a thread receives a notification, is it guaranteed that the condition is set
correctly?
Simply, no. Prior to calling the wait() method, a thread should always test the condition
while holding the synchronization lock. Upon returning from the wait() method, the
thread should always retest the condition to determine if it should wait again. This is
because another thread can also test the condition and determine that a wait is not
necessary — processing the valid data that was set by the notification thread.
This is a common case when multiple threads are involved in the notifications. More
particularly, the threads that are processing the data can be thought of as consumers;
they consume the data produced by other threads. There is no guarantee that when a
consumer receives a notification that it has not been processed by another consumer.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Points to Remember
What happens when more than one thread is waiting for notification?
Which threads actually get the notification when the notify() method is
called?
It depends on many factors.Java specification doesn’t define which thread gets
notified. In runtime, which thread actually receives the notification varies based
on several factors, including the implementation of the Java virtual machine
and scheduling and timing issues during the execution of the program.
There is no way to determine, even on a single processor platform, which of
multiple threads receives the notification.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Points to Remember
What happens when more than one thread is waiting for notification?
Which threads actually get the notification when the notify() method is
called?
Just like the notify() method, the notifyAll() method does not allow us to decide
which thread gets the notification: they all get notified. When all the threads
receive the notification, it is possible to work out a mechanism for the threads
to choose among themselves which thread should continue and which
thread(s) should call the wait() method again.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Q & A……..
62
23/07/2017
SSZC313 Object Oriented
Programming and Design
•
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Credits
BITS Pilani
•Based on the book Java, the Complete Reference – Herbert Schilt
Pilani|Dubai|Goa|Hyderabad
23/07/2017
SSZC313 Object Oriented
Programming and Design
63
CS F213
Object Oriented Programming
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
By Arun Vadekkedhil
Agenda
•
•
•
•
•
•
Concept of Streams in Java
Byte Streams
Character Streams
Object Input Stream
Object Output Stream
File Handling in Java
• Reading File
• Random Access Files
• File Class
– Object Serialization & De-Serialization
2
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
The Java I/O Streams
Introduction to Stream
From the perspective of Java, "stream" essentially refers to an
abstraction that is used to produce and consume flow of
sequential information.
The flow of information can be a result of input or output operations
performed on any physical device linked to Java I/O subsystem.
The actual linked devices may vary, such as a local storage device or
network, but the underlying principle remains the same.
Typically, Java stream supports a variety of devices, like a keyboard,
network socket, disk file, and so forth. Hence, it provides a
convenient way to handle I/O operation in the same way for
different types of devices it is actually linked to.
The steam classes are bundled in the java.io package.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Why Stream
an abstraction that either produces or
consumes information.
➢ linked to a physical device by the
Java I/O system.
➢ All streams behave in the same
manner, even if the actual physical
devices to which they are linked differ.
➢ Clean way to deal with i/o without
having every part of your code
understand the difference between a
keyboard and a network
5
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Types of Stream
There are two types of streams
1. Input Stream : Java uses I/P stream to read from source
2. Output Stream : Java used O/P stream to write to destination
6
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Introduction to Stream
Java defines two types of streams: byte and character.
Byte streams provide a convenient means for handling input and
output of bytes. Byte streams are used, for example, when reading
or writing binary data.
Character streams provide a convenient means for handling input and
output of characters. They use Unicode and, therefore, can be
internationalized.
The original version of Java (Java 1.0) did not include character
streams and, thus, all
I/O was byte-oriented. Character streams were added by Java 1.1, and
certain byte-oriented classes and methods were deprecated.
One other point: at the lowest level, all I/O is still byte-oriented.
The character-based streams simply provide a convenient and
efficient means for handling characters.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Byte Stream Classes
There are two types of
streams
1. Input Stream : Java uses
I/P stream to read from
source
2. Output Stream : Java
used O/P stream to write
to destination
Each of these abstract classes has several concrete subclasses that handle the differences
among various devices, such as disk files, network connections, and even memory
buffers.
Remember, to use the stream classes, you must import java.io.
8
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Byte Stream Sub Classes
The abstract classes
InputStream and
OutputStream define several
key methods that the other
stream classes implement.
Two of the most important
are read( ) and write( ),
which, respectively, read and
write bytes of data.
Each has a form that is
abstract and must
be overridden by derived
stream classes.
9
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Character Stream Classes
•
•
•
•
•
•
At the top of the character stream class
hierarchy, there are two abstract classes:
– Reader for character-oriented input
and
– Writer for character-oriented output
operations. The hierarchical layout is
as follows:
The Java platform stores character values
using Unicode conventions.
Character stream I/O automatically
translates this internal format to and from
the local character set.
In Western locales, the local character set is
usually an 8-bit superset of ASCII.
For most applications, I/O with character
streams is no more complicated than I/O
with byte streams.
Input and output done with stream classes
automatically translates to and from the
local character set.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Character Stream Sub Classes
The abstract classes Reader and
Writer define several key
methods that the other stream
classes implement.
Two of the most important
methods are read( ) and write( ),
which read and write characters
of data, respectively.
Each has a form that is abstract
and must be overridden by
derived stream classes.
11
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Predefined Streams
Predefined Streams
As you know, all Java programs automatically import the
java.lang package. This package defines a class called
System, which encapsulates several aspects of the run-time
environment.
For example, using some of its methods, you can obtain the
current time and the settings of various properties associated
with the system.
System also contains three predefined stream variables: in,
out, and err. These fields are declared as public, static, and
final within System. This means that they can be used by any
other part of your program and without reference to a specific
System object.
13
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Predefined Streams
System.out refers to the standard output stream. By default,
this is the console.
System.in refers to standard input, which is the keyboard by
default.
System.err refers to the standard error stream, which also is
the console by default. However, these streams may be
redirected to any compatible I/O device.
14
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Predefined Streams
System.in is an object of type InputStream;
System.out and System.err are objects of type PrintStream.
These are byte streams, even though they are typically used
to read and write characters from and to the console.
As you will see, you can wrap these within character-based
streams, if desired.
15
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Reading Console Input
System.in
In Java 1.0, the only way to perform console input was to use
a byte stream. Today, using a byte stream to read console
input is still acceptable.
However, for commercial applications, the preferred method
of reading console input is to use a character-oriented
stream. This makes your program easier to internationalize
and maintain.
In Java, console input is accomplished by reading from
System.in. To obtain a character based stream that is
attached to the console, wrap System.in in a BufferedReader
object.
17
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
System.in
BufferedReader supports a buffered input stream. A
commonly used constructor is shown here:
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance
of BufferedReader that is being created.
Reader is an abstract class. One of its concrete subclasses
is InputStreamReader, which converts bytes to characters.
To obtain an InputStreamReader object that is linked to
System.in, use the following constructor:
InputStreamReader(InputStream inputStream)
18
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
System.in
Because System.in refers to an object of type InputStream, it
can be used for inputStream.
Putting it all together, the following line of code creates a
BufferedReader that is connected to the keyboard:
BufferedReader
br
=
new
InputStreamReader(System.in));
BufferedReader(new
After this statement executes, br is a character-based stream
that is linked to the console through System.in.
19
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Reading from Buffer
Once data is available in the buffered reader, we can use the
read method.
To read a character from a BufferedReader, use read( ). The
version of read( ) that we will be using is
int read( ) throws IOException
Each time that read( ) is called, it reads a character from the
input stream and returns it as an integer value.
It returns –1 when the end of the stream is encountered. As
you can see, it can throw an IOException
20
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
I/O Classes
Understanding I/O Classes
Almost all of the classes in the java.io package fit into one of the
following two categories:
Streams. The stream classes are for performing I/O on bytes of data.
Readers and Writers. The reader and writer classes are for performing
I/O on characters.
The stream classes are child classes of java.io.OutputStream and
java.io.InputStream.
The reader classes are child classes of java.io.Reader, and the writer
classes are child classes of java.io.Writer.
These four classes are abstract and represent the common functionality
among their child classes.
22
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Output Streams
The OutputStream class is the parent class of all the output streams. It
contains five methods:
public void close(). Closes the output stream.
public void flush(). Flushes any buffers.
public void write(int b). Writes a single byte.
public void write(byte [] b). Writes an array of bytes.
public void write(byte [] b, int offset, int length). Writes length
number of elements in the array starting at the index specified by
offset.
23
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Output Streams
Each child class of OutputStream implements the write() methods
inherited from OutputStream in their own unique way.
For example, the FileOutput- Stream class writes the bytes to a file, and
the BufferedOutputStream writes the bytes to a buffer.
The filtered output stream classes (those that subclass
FilterOutputStream) contain additional write() methods for writing
different data types or objects.
For example, the DataOutputStream class contains methods for
writing ints, shorts, doubles, Strings, and so on.
24
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Input Streams
For each output stream class, there is a corresponding input stream
class for reading in the data.
The abstract InputStream class is the parent class of all the input
streams, and it contains read() methods that correspond to the write()
methods of the OutputStream class.
It also contains several other methods
25
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Input Streams
public int read(). Reads a single byte from the stream.
public int read(byte [] b). Reads in a collection of bytes and places them
in the given array. The return value is the actual number of bytes read.
public int read(byte [] b, int offset, int length). Reads a collection of
bytes into the specified location of the array.
public void close(). Closes the stream.
public long skip(long n). Skips the next n bytes in the stream.
26
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Input Streams
public void mark(int readLimit). Marks the current location of the
stream. This method is used in conjunction with the reset() method on
streams that allow support for pushback. After readLimit number of
bytes are read, the marked location becomes invalid.
public void reset(). Resets the position of the stream to the location of
the most recent mark() call, assuming that the marked location is still
valid.
public int available(). Returns the number of bytes that can be read
from
the input stream without blocking.
27
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Writer Class
The Writer class is the parent of all the writer classes in the java.io
package.
A writer is used for outputting data that is represented as characters.
The Writer class contains the flush() and close() methods, which are
similar to the ones in OutputStream.
It also contains five write() methods:
public void write(int c). Writes a single character to the stream.
public void write(char [] c). Writes the array of characters to the
stream.
28
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Writer Class
public void write(int c). Writes a single character to the stream.
public void write(char [] c). Writes the array of characters to the stream.
public void write(char [] c,int offset, int length). Writes length number
of characters in the array starting at the index specified by offset.
public void write(String s). Writes the given String to the stream.
public void write(String s, int offset, int length). Writes the specified
subset of the given String to the stream.
The child classes of Writer implement the write() methods in their own
unique ways. For example, the PipedWriter class writes the characters to a
pipe (a stream between two threads), and the OutputStreamWriter class
converts the writer into an output stream, converting the characters into bytes.
29
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Writer Class
public void write(char [] c,int offset, int length). Writes length number
of characters in the array starting at the index specified by offset.
public void write(String s). Writes the given String to the stream.
public void write(String s, int offset, int length). Writes the specified
subset of the given String to the stream.
The child classes of Writer implement the write() methods in their own
unique ways. For example, the PipedWriter class writes the characters
to a pipe (a stream between two threads), and the OutputStreamWriter
class converts the writer into an output stream, converting the
characters into bytes.
30
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Q & A……..
31
23/07/2017
SSZC313 Object Oriented
Programming and Design
•
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Credits
•Based on the book Java, the Complete Reference – Herbert Schilt
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
23/07/2017
SSZC313 Object Oriented
Programming and Design
32
CS F213
Object Oriented Programming
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
By Arun Vadekkedhil
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
The Java Utility Classes
(java.util package)
Agenda
• Collections Framework
• Collection Interfaces
• Collection Classes
• Array List
• Comparable & Comparator
• Iterators
• Java Lang
3
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
The Java Collections Framework
What is Collections
5
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Why Utils?
This important package contains a large assortment of classes
and interfaces that support a broad range of functionality. For
example, java.util has classes that generate pseudorandom
numbers, manage date and time, observe events, manipulate
sets of bits, tokenize strings, and handle formatted data.
The java.util package also contains one of Java’s most powerful
subsystems: the Collections Framework.
The Collections Framework is a sophisticated hierarchy of
interfaces and classes that provide state-of-the-art technology
for managing groups of objects. It merits close attention by all
programmers
6
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Why CF?
The Collections Framework was designed to meet several goals.
• First, the framework had to be high-performance. The
implementations for the fundamental collections (dynamic arrays,
linked lists, trees, and hash tables) are highly efficient.
• Second, the framework had to allow different types of collections to
work in a similar manner and with a high degree of interoperability.
• Third, extending and/or adapting a collection had to be easy.
• Toward this end, the entire Collections Framework is built upon a set
of standard interfaces.
• Several standard implementations (such as LinkedList, HashSet,
and TreeSet) of these interfaces are provided that you may use as-is.
• You may also implement your own collection, if you choose.
7
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
What is Collections
8
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
What is Collections
A toolbox of generic
interfaces and classes
• collection interfaces and
classes
• collection related utility
interfaces classes
Collection
can hold
objects.
A collection
a group of
The Collection interface
is extended by the
interfaces Set, List and
Queue.
23/07/2017
SSZC313 Object Oriented
Programming and Design
9
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Set Interface
The Set interface defines a set.
It extends Collection and specifies the behavior of a
collection that does not allow duplicate
elements.
Therefore, the add( ) method returns false if an
attempt is made to add duplicate elements to a
set.
It does not specify any additional methods of its
own.
Set is a generic interface that has this declaration:
interface Set<E>
Here, E specifies the type of objects that the set will
hold.
10
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Sorted Set Interface
SortedSet interface extends Set and declares the behavior of a set
sorted in ascending order.
SortedSet is a generic interface that has this declaration:
interface SortedSet<E>
Here, E specifies the type of objects that the set will hold.
In addition to those methods provided by Set, the SortedSet
interface declares the methods shown in next slide.
Several methods throw a NoSuchElementException when no items
are contained in the invoking set.
A ClassCastException is thrown when an object is incompatible
with the elements in a set.
A NullPointerException is thrown if an attempt is made to use a null
object and null is not allowed in the set.
An IllegalArgumentException is thrown if an invalid argument is
used.
11
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Sorted Set Interface
SortedSet defines several methods that make set processing
more convenient.
To obtain the first object in the set, call first( ).
To get the last element, use last( ).
You can obtain a subset of a sorted set by calling subSet( ),
specifying the first and last object in the set.
If you need the subset that starts with the first element in the
set, use headSet( ).
If you want the subset that ends the set, use tailSet( ).
12
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Sorted Set Interface Methods
13
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Navigable Set Interface
The NavigableSet interface extends SortedSet and
declares the behavior of a collection
that supports the retrieval of elements based on the
closest match to a given value or values.
NavigableSet is a generic interface that has this
declaration:
interface NavigableSet<E>
Here, E specifies the type of objects that the set will
hold
14
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
List Interface
The List interface extends Collection and declares
the behavior of a collection that stores a
sequence of elements.
Elements can be inserted or accessed by their
position in the list, using a zero-based index. A
list may contain duplicate elements. List is a
generic interface
that has this declaration:
interface List<E>
Here, E specifies the type of objects that the list will
hold.
15
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
List Interface
List throws the following exceptions
An UnsupportedOperationException if the list cannot be
modified
ClassCastException is generated when one object is
incompatible with another,
An IndexOutOfBoundsException if an invalid index is used.
A NullPointerException is thrown if an attempt is made to
store a null object and null elements are not allowed
in the list.
An IllegalArgumentException is thrown if an invalid argument
is used.
Note: Vector was the early implementation of the List
interface and has now been deprecated. We will only
focus on the newer ArrayList
16
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Queue Interface
The Queue interface extends
Collection and declares the
behavior of a queue, which is
often a first-in, first-out list. However,
there are types of queues in which
the ordering is
based upon other criteria. Queue is a
generic interface that has this
declaration:
interface Queue<E>
Here, E specifies the type of objects
that the queue will hold.
17
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Deque Interface
The Deque interface extends
Queue and declares the
behavior of a double-ended
queue.
Double-ended queues can
function as standard, first-in,
first-out queues or as last-in,
firstout
stacks. Deque is a generic
interface that has this
declaration:
interface Deque<E>
Here, E specifies the type of
objects that the deque will hold
18
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
The Collections Classes
Collection Classes - Set
20
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Collection Classes – Core
Classes
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Array List
22
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Array List
ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed
length.
But, sometimes, you may not know until run time precisely how large an array you need. To
handle this situation, the Collections Framework defines ArrayList. In essence, an ArrayList is
a variable-length array of object references.
That is, an ArrayList can dynamically increase or decrease in size.
Array lists are created with an initial size. When this size is exceeded, the collection is
automatically enlarged. When objects are removed, the array can be shrunk.
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)
The first constructor builds an empty array list.
The second constructor builds an array list that is initialized with the elements of the collection c.
The third constructor builds an array list that has the specified initial capacity.
The capacity is the size of the underlying array that is used to store the elements. The capacity
grows automatically as elements are added to an array list.
23
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Array List
24
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Linked List
The LinkedList class extends AbstractSequentialList and implements the List, Deque,
and
Queue interfaces.
It provides a linked-list data structure. LinkedList is a generic class that has this
declaration:
class LinkedList<E>
Here, E specifies the type of objects that the list will hold. LinkedList has the two
constructors shown here:
LinkedList( )
LinkedList(Collection<? extends E> c)
The first constructor builds an empty linked list.
The second constructor builds a linked list that is initialized with the elements of the
collection c.
25
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Linked List
26
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Set
Set is an interface which extends Collection. It is an
unordered collection of objects in which duplicate values
cannot be stored.
Basically, Set is implemented by HashSet, LinkedHashSet
or TreeSet (sorted representation).
Set has various methods to add, remove clear, size, etc to
enhance the usage of this interface
27
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Hash Set
HashSet extends AbstractSet and implements the Set interface. It creates a
collection that uses a hash table for storage. HashSet is a generic class
that has this declaration: class HashSet<E>
Here, E specifies the type of objects that the set will hold.
A hash table stores information by using a mechanism called hashing. In
hashing, the informational content of a key is used to determine a unique
value, called its hash code. The hash code is then used as the index at
which the data associated with the key is stored. The transformation of
the key into its hash code is performed automatically—you never see the
hash code itself. Also, your code can’t directly
index the hash table. The advantage of hashing is that it allows the execution
time of add( ), contains( ), remove( ), and size( ) to remain constant even
for large sets.
28
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Hash Set
The following constructors are defined:
–
–
–
–
HashSet( )
HashSet(Collection<? extends E> c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
The first form constructs a default hash set.
The second form initializes the hash set by using the elements of c.
The third form initializes the capacity of the hash set to capacity.
(The default capacity is 16.)
The fourth form initializes both the capacity and the fill ratio (also called load
capacity ) of the hash set from its arguments. The fill ratio must be between 0.0
and 1.0, and it determines how full the hash set can be before it is resized
upward.
Specifically, when the number of elements is greater than the capacity of the hash
set multiplied by its fill ratio, the hash set is expanded. For constructors that do
not
take a fill ratio, 0.75 is used
23/07/2017
29
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
The Comparable & Comparator
Comparable Interface
Java provides two interfaces to sort objects using data members of the class:
– Comparable
– Comparator
Using Comparable Interface
A comparable object is capable of comparing itself with another object. The class
itself must implements the java.lang.Comparable interface to compare its
instances.
Consider a Movie class that has members like, rating, name, year and we wish to
sort a list of Movies based on year of release.
We can implement the Comparable interface with the Movie class, and we
override the method compareTo() of Comparable interface.
31
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Comparable Interface
Java provides two interfaces to sort objects using data members of the class:
– Comparable
– Comparator
Using Comparable Interface
A comparable object is capable of comparing itself with another object. The class
itself must implements the java.lang.Comparable interface to compare its
instances.
Consider a Movie class that has members like, rating, name, year and we wish to
sort a list of Movies based on year of release.
We can implement the Comparable interface with the Movie class, and we
override the method compareTo() of Comparable interface.
32
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Comparator Interface
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Iterators
Iterator
Iterators are used in Collection framework in Java to retrieve elements one by
one. There are three iterators. (Enumeration, Iterators & List Iterators)
Enumeration : The Enumeration interface defines the methods by which you can
enumerate (obtain one at a time) the elements in a collection of objects.
This legacy interface has been superseded by Iterator. Although not deprecated,
Enumeration is considered obsolete for new code. However, it is used by several
methods defined by the legacy classes such as Vector and Properties, is used by
several other API classes, and is currently in widespread use in application code
Limitations of Enumeration :
• Enumeration is for legacy classes(Vector, Hashtable) only. Hence it is
not a universal iterator.
• Remove operations can’t be performed using Enumeration.
• Only forward direction iterating is possible.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Comparator Interface
• It is a universal iterator as we can apply it to any Collection object.
• By using Iterator, we can perform both read and remove operations.
• It is improved version of Enumeration with additional functionality of remove-
ability of an element.
• Iterator must be used whenever we want to enumerate elements in all Collection
framework implemented interfaces like Set, List, Queue, Deque and also in all
implemented classes of Map interface.
• Iterator is the only cursor available for entire collection framework.
• Iterator object can be created by calling iterator() method present in Collection
interface.
Limitations of Iterator :
•Only forward direction iterating is possible.
•Replacement and addition of new element is not supported by Iterator.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Comparator Interface
remove() method can throw two
exceptions
UnsupportedOperationException
: If the remove operation is not
supported by this iterator
IllegalStateException : If the next
method has not yet been called, or
the remove method has already
been called after the last call to the
next method
Limitations of Iterator :
•Only forward direction iterating is possible.
•Replacement and addition of new element is not supported by Iterator.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Credits
•Based on the book Java, the Complete Reference – Herbert Schilt
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
23/07/2017
SSZC313 Object Oriented
Programming and Design
38
CS F213
Object Oriented Programming
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
By Arun Vadekkedhil
Agenda
• Introduction to java.lang
• Overview of Classes & Interfaces
• Primitive Types & Wrappers
• Process & Runtime Classes
• Cloneable
• Iterators
• Java Lang
2
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
The Java Lang Package
What is java.lang
As you know,java.lang is automatically imported into all
programs. It contains classes and interfaces that are
fundamental to virtually all of Java programming. It is Java’s
most widely used package. java.lang includes the following
classes:
4
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
What is java.lang
As you know,java.lang is automatically imported into all
programs. It contains classes and interfaces that are
fundamental to virtually all of Java programming. It is Java’s
most widely used package. java.lang includes the following
interfaces:
5
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
The Primitive Types
Primitive Types
Java uses primitive types, such as int and char, for performance
reasons.
These data types are not part of the object hierarchy. They are passed
by value to methods and cannot be directly passed by reference.
Also, there is no way for two methods to refer to the same instance of
an int.
At times, you will need to create an object representation for one of
these primitive types and need to wrap the primitive type in a
class.
To address this need, Java provides classes that correspond to each of
the primitive types.
In essence, these classes encapsulate, or wrap, the primitive types
within a class. Thus, they are commonly referred to as type
wrappers.:
7
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Primitive Types
Java uses primitive types, such as int and char, for performance
reasons.
These data types are not part of the object hierarchy. They are passed
by value to methods and cannot be directly passed by reference.
Also, there is no way for two methods to refer to the same instance of
an int.
At times, you will need to create an object representation for one of
these primitive types and need to wrap the primitive type in a
class.
To address this need, Java provides classes that correspond to each of
the primitive types.
In essence, these classes encapsulate, or wrap, the primitive types
within a class. Thus, they are commonly referred to as type
wrappers.:
8
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Primitive Types
9
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Primitive Types
10
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Primitive Types
The abstract class Number defines a superclass that is implemented by the classes that
wrap the numeric types byte, short, int, long, float, and double.
Number has abstract methods that return the value of the object in each of the different
number formats. For example,doubleValue( ) returns the value as a double,
floatValue( ) returns the value as a float, and so on. These methods are shown here:
– byte byteValue( )
– double doubleValue( )
– float floatValue( )
– int intValue( )
– long longValue( )
– short shortValue( )
The values returned by these methods might be rounded, truncated, or result in a
“garbage” value due to the effects of a narrowing conversion.
Number has concrete subclasses that hold explicit values of each primitive numeric
type: Double, Float, Byte, Short, Integer, and Long
11
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Primitive Types
12
23/07/2017
SSZC313 Object Oriented
Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Primitive Types
13
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Primitive Types
14
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Primitive Types
15
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Enum
Enumerated means that something has a defined set of values it can
hold. Think of the days of the week. Unless something drastic
happens, we will always have Sunday through Saturday. These
values could be stored in an enumerated (in Java, we'll use the key
word enum) variable. They are unchanging and easily accessible.
In programming-speak, the values are static and final, which really
means they can't be changed. Other data types, like int and float,
could change during the course of a program.
Java enums are type-safe. There is no way to assign a value to the
enum that doesn't fit with the defined values. For example, the
DayOfWeek enum cannot accept anything other than the days of the
week that were defined. If you try to assign a 1 to it, the code will not
compile.
Additionally, an enum is a reference type, which means it behaves
more like a class or an interface. As a programmer, you can create
methods and variables inside the enum declaration.
16
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Enum
17
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Enum
18
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
class Class
The Class
Java provides a class with name Class in java.lang package.
Instances of the class Class represent classes and interfaces in a running Java
application.
The primitive Java types (boolean, byte, char, short, int, long, float, and double), and
the keyword void are also represented as Class objects. It has no public
constructor.
Class objects are constructed automatically by the Java Virtual Machine(JVM). It is a
final class, so we cannot extend it.
Given a object reference we can know the exact type of the object by using getClass()
method
–
Class c = e.getClass();
getClass() method returns a Class Object. Once you have a class object its name can
be printed as follows
–
System.out.println(e.getClass().getName());
Adding the suffix .class to a type also yields the Class object.
Rectangle.class, Employee.class , Student.class
20
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The Runtime Class
Java Runtime class is used to interact with java runtime
environment. Java Runtime class provides methods to execute
a process, invoke GC, get total and free memory etc. There is
only one instance of java.lang.Runtime class is available for
one java application.
The Runtime.getRuntime() method returns the singleton
instance of Runtime class.
21
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The Runtime Class
22
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
The Object Class
The Object class is the parent class of all the classes in java by default.
In other words, it is the topmost class of java.
The Object class is beneficial if you want to refer any object whose
type you don't know.
Notice that parent class reference variable can refer the child class
object, know as casting.
Let's take an example, there is getObject() method that returns an
object but it can be of any type like Employee,Student etc, we can
use Object class reference to refer that object.
For example:
Object obj=getObject();//we don't know what object will be returned
from this method
The Object class provides some common behaviors to all the objects
such as object can be compared, object can be cloned, object can
be notified etc.
23
23/07/2017
SSZC313 Object Oriented Programming and Design
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Methods of Object Class
•
toString() : toString() provides String representation of an Object and used to convert an object to String. The
default toString() method for class Object returns a string consisting of the name of the class of which the object is
an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the
object.
•
hashCode() : For every object, JVM generates a unique number which is hashcode. It returns distinct integers for
distinct objects. A common misconception about this method is that hashCode() method returns the address of
object, which is not correct. It convert the internal address of object to an integer by using an algorithm.
•
equals(Object obj) : Compares the given object to “this” object (the object on which the method is called). It gives
a generic way to compare objects for equality. It is recommended to override equals(Object obj) method to get
our own equality condition on Objects. getClass() : Returns the class object of “this” object and used to get actual
runtime class of the object. It can also be used to get metadata of this class. The returned Class object is the object
that is locked by static synchronized methods of the represented class. As it is final so we don’t override it.
•
clone() : It returns a new object that is exactly the same as this object. For clone() method refer Clone()
Cloning
•
While not recommended, cloning is a viable way to copy an object. Let's dive into
Shallow Cloning, Deep Cloning, how to use them both, and when to avoid them.
•
Cloning is also a way of creating an object, but in general, cloning is not just about
creating a new object. Cloning means creating a new object from an already present
object and copying all data of the given object to that new object.
•
In order to create a clone of an object, we generally design our class in such a way that:
– Our class should implement the Cloneable interface. Otherwise, the JVM will throw
CloneNotSupportedException if we will call clone() on our object.
– Our
class
should
have
CloneNotSupportedException.
a
clone
method,
which
should
handle
Cloning
•
And finally, we need to call the clone() method of the superclass, which will call its
super’s clone(). This chain will continue until it reaches the clone() method of the Object
class. The Object.clone() method is the actual worker that creates the clone of your
object, and another clone() method just delegates the call to its parent’s clone().
Cloning
•
By default, java cloning is ‘field by field copy’ i.e. as the Object class does not have
idea about the structure of class on which clone() method will be invoked.
•
So, JVM when called for cloning, do following things:
•
If the class has only primitive data type members then a completely new copy of the
object will be created and the reference to the new object copy will be returned.
•
If the class contains members of any class type then only the object references to
those members are copied and hence the member references in both the original
object as well as the cloned object refer to the same object.
•
Apart from above default behavior, you can always override this behavior and specify
your own. This is done using overriding clone() method. Let’s see how it is done.
Cloning
• Every language which supports cloning of objects has its own rules and so
does java. In java, if a class needs to support cloning it has to do following
things:
• You must implement Cloneable interface.
• You must override clone() method from Object class. [Its weird. clone() method
should have been in Cloneable interface.]
Shallow vs Deep Copy
•
Shallow copy A new object is created that has an
A deep copy copies all fields, and makes copies of
exact copy of the values in the original object. If
dynamically allocated memory pointed to by the fields. A
any of the fields of the object are references to
deep copy occurs when an object is copied along with the
other objects, just the reference addresses are
objects to which it refers.
copied i.e., only the memory address is copied.
•
In this figure, the MainObject1 have fields "field1" of int type, and
"ContainObject1" of ContainObject type.
•
When you do a shallow copy of MainObject1, MainObject2 is created with
•
"ContainObject1" of ContainObject type.
•
•
So any changes made to ContainObject1 in MainObject1 will reflect in
MainObject2.
When you do a deep copy of MainObject1, MainObject2 is created with
"field2" containing the copied value of "field1" and "ContainObject2"
"field2" containing the copied value of "field1" and "ContainObject2"
containing reference of ContainObject1.
In this figure, the MainObject1 have fields "field1" of int type, and
containing the copied value of ContainObject1.
•
So any changes made to ContainObject1 in MainObject1 will not
reflect in MainObject2.
Cloning
Java Shallow Copy
• Shallow clone is “default implementation” in Java. In overridden clone
method, if you are not cloning all the object types (not primitives), then you
are making a shallow copy.
• All above examples are of shallow copy only, because we have not cloned the
Department object on Employee class’s clone method. Now, I will move on to
next section where we will see the deep cloning.
Java Deep Copy
• Deep clone is the desired behavior in most the cases. In the deep copy, we
create a clone which is independent of original object and making changes in
the cloned object should not affect original object.
• Let see how deep copy is created in Java.
Cloning Disadvantages
Disadvantage of Object cloning
• Following is a list of some disadvantages of clone() method:
• To use the Object.clone() method, we have to change a lot of syntaxes to our code,
like implementing a Cloneable interface, defining the clone() method and handling
CloneNotSupportedException, and finally, calling Object.clone() etc.
• We have to implement cloneable interface while it doesnt have any methods in it. We
just have to use it to tell the JVM that we can perform clone() on our object.
• Object.clone() is protected, so we have to provide our own clone() and indirectly call
Object.clone() from it.
• Object.clone() doesnt invoke any constructor so we dont have any control over object
construction.
• If you want to write a clone method in a child class then all of its superclasses should
define the clone() method in them or inherit it from another parent class. Otherwise,
the super.clone() chain will fail.
• Object.clone() supports only shallow copying but we will need to override it if we need
deep cloning.
Credits
•Based on the book Java, the Complete Reference – Herbert Schilt
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
23/07/2017
SSZC313 Object Oriented
Programming and Design
32
CS F213
Object Oriented Programming
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
By Arun Vadekkedhil
Agenda
• What is Object Oriented Analysis & Design
• OOAD Process
2
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
Introducing the OOA & D
Introduction to OOA & D
Any construction activity requires proper planning, so is the case with
S/W development as well.
Software development consists of several important activities, which
are compiled and attached together to create a software that has
impeccable qualities, features and functionality.
It is these components of the software that decide its scalability,
performance, reliability, security, and more, as well as ensures that
the software or application is developed as per the requirements of
the client.
However, to initiate and implement such activities, software
engineers are required to prepare a proper design for the software,
which can guide them during the process of software
development.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Why Design?
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
What is OOD
Object Oriented Design (OOD) serves as part of the object oriented
programming (OOP) process of lifestyle.
It is mainly the process of using an object methodology to design a
computing system or application.
This technique enables the implementation of a software based on
the concepts of objects
The origins of Object Oriented Design (OOD) is debated, but the first
languages that supported it included Simula and SmallTalk. The
term did not become popular until Grady Booch wrote the first
paper titled Object-Oriented Design, in 1982.
The chief objective of this type of software design is to define the
classes and their relationships, which are needed to build a system
that meets the requirements contained in the Software
Requirement Specifications.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
OOD Process
Object-Oriented SW design: The goal is to identify the objects that
the system contains, relationships and interactions between the
objects.
SW development phases
OO Analysis
Models problem domain using Object-Oriented concepts,
leading to understanding of the problem. Objects represent
entities in the
problem domain.(called semantic objects)
OO Design
Models solution to the problem. Identifies Solution objects.
(Semantic + other objects)
OO Implementation
Includes programming, testing and deployment of the SW
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
OOA Stage
Object–Oriented Analysis (OOA) is the procedure of identifying software
engineering requirements and developing software specifications in
terms of a software system’s object model, which comprises of
interacting objects
Grady Booch has defined OOA as, “Object-oriented analysis is a method of
analysis that examines requirements from the perspective of the classes and
objects found in the vocabulary of the problem domain”.
The result of analysis phase is a textual description called Requirements
Specification Document (Functional and Non-functional)
Functional specs defines the task to be performed.
Readable both by domain expert and SW developer.
Diverse interested parties can review it.
It can be tested against reality.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
OOA Stage
Functional Requirements: Describe what to be done or what is the
functionality of the system. It includes both FS & NFS
Functional requirements include:
• Process the system carries out.
• Input
• Output
• Details about the data
Non-Functional requirements Covers the aspects that describe how
well the system provides the functionality.
• Performance
• Throughput
• Security
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
OODStage
OO Design is concerned with establishing how to deliver the functionality
that was specified in Functional Specs, while at the same time, meeting
non-functional requirements that may sometimes conflict with each
other.
Object-oriented design includes two main stages, namely, system design
and object design.
System Design
In this stage, the complete architecture of the desired system is designed.
The system is conceived as a set of interacting subsystems that in turn is
composed of a hierarchy of interacting objects, grouped into classes.
System design is done according to both the system analysis model and the
proposed system architecture. Here, the emphasis is on the objects
comprising the system rather than the processes in the system.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
OOD Stage
Object Design
In this phase, a design model is developed based on both the models developed
in the system analysis phase and the architecture designed in the system
design phase. All the classes required are identified. The designer decides
whether −
• new classes are to be created from scratch,
• any existing classes can be used in their original form, or
• new classes should be inherited from the existing classes.
The associations between the identified classes are established and the
hierarchies of classes are identified. Besides, the developer designs the
internal details of the classes and their associations, i.e., the data structure
for each attribute and the algorithms for the operations.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
OOD Stage
Implementation & Testing
In this stage, the design model developed in the object design is
translated into code in an appropriate programming language or
software tool. The databases are created and the specific hardware
requirements are ascertained. Once the code is in shape, it is tested
using specialized techniques to identify and remove the errors in the
code.
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Design Goals in OOAD
The important features of object–oriented programming are −
• Bottom–up approach in program design
• Programs organized around objects, grouped in classes
• Focus on data with methods to operate upon object’s data
• Interaction between objects through functions
• Reusability of design through creation of new classes by adding
features to existing classes
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
OOD Components
The conceptual framework of object–oriented systems is based upon the object model.
There are two categories of elements in an object-oriented system −
Major Elements − By major, it is meant that if a model does not have any one of these
elements, it ceases to be object oriented. The four major elements are −
• Abstraction➔ Focus on essential features
• Encapsulation ➔ Hiding Data & implementation by providing suitable interfaces
• Modularity ➔ Well defined, loosely coupled parts of a whole, to reduce complexity
• Hierarchy ➔ Definition or Ranking of the Classes (IS A & Part OF)
Minor Elements − By minor, it is meant that these elements are useful, but not
indispensable part of the object model. The three minor elements are −
• Typing ➔ Strongly typed vs Weakly typed etc.
• Concurrency ➔ Talks about the process in the Object model which are capable of
concurrently executing
• Persistence ➔ Details data about the final outcome of the data and or object
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Classes & Objects
Class :defines the structure and behavior of similar kind of objects.
Object: is an entity in a program that belong to a particular class
Each object has the following characteristics:
State(information stored by the object)
Behaviour (is defined by operations supported by the object that change
the state of the object)
Identity (to distinguish between similar class objects)
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Steps in OOAD
Problem description
Identifying classes
Identifying responsibilities
Identify Relationships between classes
Identify Use Cases
Identify Collaborations
Define interactions
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Sample Case Study
In a voice mail system, a person dials an extension number and,
provided the other party does not pick up the telephone, leaves
a message.
The other party can later retrieve the messages, keep them,
delete them.
Real-world systems have a multitude of fancy features: messages
can be forwarded to one or more mail boxes; distribution lists
can be defined, retained and edited; and authorized persons
can send broadcast messages to all users.
17
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Identifying Classes
Look at the problem description
Thumb rule: Look for nouns in the problem description.
Nouns:
• Mailbox
• Message
• User
• Passcode
• Extension
Class names should be nouns in singular form
18
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Identifying Responsibilities
Look at the problem description
Thumb rule:Look for verbs in the problem description.
Verbs:
• Messages are recorded, deleted, played
• Users login to the system
• Passcodes are authenticated
• Add Message to Mailbox is the responsibility of Mailbox
We must find one class that owns the responsibility.
A responsibility must belong to exactly one class.
19
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Collaborations / Relationships
Three common relationships are :
Dependency, Aggregation, inheritance
Dependency (coupling)
A class depends on another if it manipulates objects of
another class
It is easy to understand or implement if a class has no
dependency.
Ex: Mailbox manipulates Message objects.
As far as possible-Minimize coupling.
20
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Collaborations / Relationships
Aggregation-A class aggregates another if it contains objects of
another class.
Ex: MessageQueue aggregates Message objects.
Inheritance-A class inherits from another if it incorporates the
behavior of the other class.
Ex: ForwardedMessage inherits Message class.
Forwarded message contains specific info. Who forwarded it.
21
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Use Cases
Use cases are an analysis technique to describe in a
formal way how a system should work.
Each Use case focuses on describing the steps that are
necessary to bring it to successful completion.
Each step represents an interaction with people or
entities outside the system (actors) and the system
itself.
22
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Use Cases
Use cases list sequence of steps that yields a result that is of value to
an actor
Ex:
Leave a message-describes steps that caller must take to dial an
extension and leave the message. Caller is the actor here.
Retrieve messages–the mail box owner is the actor.
A use case should include variants that describe some failures in
achieving a result. All such variants are known as use case scenarios.
23
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
CRC (Classes, Responsibilities &
Collaborator) Cards
A Class Responsibility
Collaborator (CRC) model
is a collection of standard
index cards that have been
divided into three sections,
as depicted below .
A class represents a collection
of similar objects, a
responsibility is something
that a class knows or does,
and a collaborator is
another class that a class
interacts with to fulfill its
responsibilities.
24
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
CRC Cards
A CRC card is an index card that describes a class, its high-level
responsibilities, and its collaborations (dependent classes).
•It is a design technique for discovering class, responsibility and
relationships.
Index cards are good because:
1.They are small (discourage piling up too much responsibility into
one class)
2.Low-tech
3.Convenient to handle during brain storming sessions
25
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
CRC Cards
Guidelines
1.Don’t assign more than three responsibilities (high-level) to a
class
2.Maintain coherency (attach only related responsibilities)
3.Don’t add unnecessary responsibilities
4.Delete classes with no responsibilities
Notes:
–CRC cards are suited for group discussions.
–Is a mechanism for discovering classes
–Not a means of documenting design
26
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Interactions
OO programs work by sending/receiving messages from/to
objects.
Message is a request by sender to execute an operation of a
target object.
This kind of message passing is called as interaction between
objects.
27
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Benefits of OOA+D
The object oriented approach is a way of thinking about a problem
using real world concepts instead using ad-hoc function concepts.
We intend to learn OOAD approach for the following reason:
✓ Promotes better understanding of user requirements
✓ Leads cleaner design
✓ Design flexibility'
✓ Decomposition
✓ Facilitates data abstraction & information hiding
✓ Software reuse
✓ Easy maintenance
28
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
UML – Unified Modelling Language
What is UML
UML (Unified Modeling Language) is a general-purpose, graphical
modeling language in the field of Software Engineering.
UML is used to specify, visualize, construct, and document the
artifacts (major elements) of the software system.
It was initially developed by Grady Booch, Ivar Jacobson, and
James Rumbaugh in 1994-95 at Rational software, and its
further development was carried out through 1996.
In 1997, it got adopted as a standard by the Object Management
Group.
30
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
UML Goals
• Since it is a general-purpose modeling language, it can be
utilized by all the modelers.
• UML came into existence after the introduction of objectoriented concepts to systemize and consolidate the objectoriented development, due to the absence of standard
methods at that time.
• The UML diagrams are made for business users, developers,
ordinary people, or anyone who is looking forward to
understand the system, such that the system can be software
or non-software.
• Thus it can be concluded that the UML is a simple modeling
approach that is used to model all the practical systems.
31
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
UML Diagrams
1.Use Case Diagram
2.Class Diagram
3.Sequence Diagram
4.Collaboration Diagram
5.State Diagram
6.Activity Diagram
7.Object Diagram
8.Component Diagram
9.Deployment Diagram
32
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
UML Diagrams Views
Structural diagrams depict a static view
or structure of a system. It is widely
used in the documentation of software
architecture. It presents an outline for
the system. It stresses the elements to
be present that are to be modeled.
Behavioral diagrams portray a dynamic
view of a system or the behavior of a
system, which describes the functioning
of the system. It includes use case
diagrams, state diagrams, and activity
diagrams. It defines the interaction
within the system
33
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Class Diagrams
• Class diagrams are one of the
most widely used diagrams.
• It depicts the static structure
of the system.
• It displays the system's class,
attributes, and methods.
• It is helpful in recognizing the
relation
between
different
objects as well as classes.
34
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Class Diagrams
Following rules must be taken care of while representing a class:
1.A class name should always start with a capital letter.
2.A class name should always be in the center of the first compartment.
3.A class name should always be written in bold format.
4.UML abstract class name should be written in italics format.
35
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Class Diagrams - Class
Relationships
Classes are interrelated to each other in specific ways. In
particular, relationships in class diagrams include different
types of logical connections. The following are such types of
logical connections that are possible in UML:
1.
2.
3.
4.
5.
Association
6.
Directed Association 7.
Composition
8.
Aggregation
9.
Dependencies
Multiplicity
Inheritance
Realization
Generalization
36
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Class Diagrams - Association
& Directed Association
Association
Association is the most basic of
relationships. Association means any
type of relationship or connection
between classes.
Directed Association
Directed association shows a strong
relationship between classes. The
classes must communicate. We
represent a direct association with an
arrow pointing to our object class.
37
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Class Diagrams Composition & Aggregation
Aggregation
We use aggregation arrows when we
want to convey that two classes are
associated, but not as close as in
direct association. The child class can
exist independent of the parent
element. For example, a book still
exists if somebody checks it out from
the library.
Composition
The composition relationship is very
similar to the aggregation
relationship. with the only difference
being its key purpose of emphasizing
the dependence of the contained
class to the life cycle of the container
class. That is, the contained class will
be obliterated when the container
class is destroyed.
38
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Class Diagrams - Inheritance
& Realization
Inheritance / Generalization
We use Inheritance arrows to show a
child class inherits functionality from
the parent class.
Realization / Implementation
We use realization or implementation
arrows to indicate a place where one
class implements the function
defined in another class.
39
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Class Diagrams - Dependency
& Multiplicity
Dependency
Dependency arrows show us where two
elements depend on each other, but
in a less strong relationship than a
basic association. Changes to the
parent class will also affect the child
class.
Multiplicity
Multiplicity or cardinality arrows show a
place in our UML diagram where a
class might contain many (or
none!) items.
40
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Object Diagram
It describes the static structure of a system at a particular point in
time. It can be used to test the accuracy of class diagrams. It
represents distinct instances of classes and the relationship
between them at a time.
• The object diagram describes the behavioral relationships
among class instances during a point in time.
• This captures dynamic as well as runtime modifications in our
condition of the program.
• It could consist of data values of entities or attributes inside the
structure.
• An object diagram displays how those objects act at run time.
41
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Object Diagram
42
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Sequence Diagram
A sequence diagram
shows the time
ordering of
sequence of
method calls.
•Shows
communication
pattern among
objects.
•Represent message
sequencing in the
system (time
ordering of
messages)
43
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Collaboration Diagrams
Collaboration diagrams and
sequence diagrams are alternate
representations of an interaction.
Emphasizes the structural
organization of objects that
participate in the interaction.
Collaboration diagrams show
objects, their links, and their
messages.
44
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Use Case Diagrams
Use cases are an
analysis technique to
describe in a formal
way how a system
should work.
45
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
StateChart Diagrams
A state diagram shows the
states of an object and the
transitions between states.
State diagrams model the
possible life history of an
object.
They describe the behavior of
a system .
46
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Activity Diagrams
Is a special kind of state chart diagram
that shows flow from activity within a
system.
47
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Component Diagrams
Organization and dependencies among the components.
Component is a physical and replaceable part of the system that
conforms to and provides the realization of set of interfaces.
• Packages
• Libraries
• Class files
• File
• Database table
• Executable file
48
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Component Diagrams
49
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Deployment Diagrams
Shows configuration of run
time processing nodes and the
components that live in them. Address the static deployment view
50
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Rational Suite
A UML visual modeling and application development
solution (tool).
The IBM®Rational Rose® product family is designed for
Unified Modeling Language (UML) based development
of applications.
We can also use the following free UML Tools
Visual Paradigm
StarUML
UMLet
Violet UML Editor
51
23/07/2017
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Q & A……..
52
23/07/2017
SSZC313 Object Oriented
Programming and Design
•
BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956
Credits
•Based on the book Java, the Complete Reference – Herbert Schilt
BITS Pilani
Pilani|Dubai|Goa|Hyderabad
23/07/2017
SSZC313 Object Oriented
Programming and Design
53
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
Design
Patterns
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
T1: T1- Ch.5&11
And also refer to Class notes.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Content
1. What is a Design pattern
2. Some important patterns
3. Singleton pattern
4. Example
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Introduction
SW analyst or engineer applies potential solutions to
development problems, monitor the success or the failure
and produces more effective solutions on the next
occasion.
It is the nature of the software development that the same
problems tend to occur.
Different developers may tend to expend great deal of time
and effort on solving these problems from the first principles
each time they occur.
The solutions they produce may not be the most appropriate
that could be achieved.
This may result in SW systems that are inflexible, inefficient,
difficult to maintain.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Design Patterns
Patterns provide a means for capturing
knowledge about problems and successful
solutions in software development.
Experience that has been gained in the past can
be reused in similar situations.
Thus reducing the effort in producing more
resilient, more flexible and more efficient.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Frameworks
 Frameworks are partially completed systems which
contain unfinished elements which can be completed
according to the requirement.
 New elements can be added as per the need.
 Essentially, a framework is a reusable mini-architecture
that provides structure and behavior common to all
applications of this type.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Patterns Vs. Frameworks
 Patterns are more abstract and general than
Frameworks.
Pattern is a description of the way that a type problem
can be solved.
Pattern is not itself a solution.
 Patterns are more primitive than frameworks.
 A Framework can use several patterns, but a pattern
can’t employ a framework.
 Patterns normally don’t have implementations.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Documenting patterns
Patterns may be documented using templates.
The pattern description should include the following.
 Name: A pattern should be given a meaningful name that reflects the
knowledge embodied by the pattern. This may be a single word or a short
phrase.
 Problem: This is the description of the problem that a pattern addresses
(the intent of the problem). It should identify and describe the objectives to
be achieved.
 Context: This represents the circumstances or preconditions under which it
can occur.
 Forces: The forces embodied in a pattern are the constraints or issues that
must be addressed by the solutions.
 Solution: Description of the static and dynamic relationships among the
components of the pattern.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Types of design Patterns
Design patterns are classified according to their
scope and purpose.
Three main categories of purpose a pattern can
have are :
 Creational Pattern
 Structural pattern
 Behavioral pattern
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Creational Patterns
A creational design pattern is concerned with the
construction of object instances.
It separates the operation of an application from how its
objects are created.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Singleton Pattern
A singleton class has exactly one instance.
All clients need to access a single shared instance
of a class.
You want to ensure that no additional instances
can be created accidentally.
Define a class with private constructor.
Supply a static method that returns a reference to
the single object.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
//Sample Java Code
public class DBManager
{
private static DBManager dbm=null;
public static DBManager getInstance()
{
if(dbm==null)
{ dbm= new DBManager(); }
return dbm;
}
private DBManager()
{
}
}
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Description of Singleton
Pattern
Name: Singleton
Problem: How can a class be defined that should have only one
instance and that can be accessed globally within the application.
Context: In some applications it is important that a class have exactly
one instance. Ex: A Database manager.
Forces: One approach to making an object globally accessible is to
making it global variable, but in general it is not a good design
solution as it violates encapsulation.
Solution: Create a class operation getInstance(), which when the class
is first accessed, creates the relevant object instance and returns
the object to the client.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
DBManager
- dbm
+ getInstance()
Private Static member
Public Static operation
- DBManager()
Private
constructor
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Structural Patterns
A structural design pattern is concerned with the way the
classes and objects are organized.
Structural patterns offer effective ways of using objectoriented constructs such as inheritance, aggregation and
composition to satisfy particular requirements.
Ex: Composite pattern
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Behavioral Patterns
Behavioral design patterns address the problems that arise
when assigning responsibilities to classes and when
designing algorithms. They focus on structural
organization and also describe how objects
communicate with each other.
Ex: State pattern
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Other patterns
There are total 23 Design patterns
 Iterator
 Adapter
 Factory Method
 Proxy
 Decorator
 Prototype etc.
 Observer
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Architect Christopher Alexander
– A Pattern Language (1977)
“Gang of four”
• Erich Gamma
• Richard Helm
• Ralph Johnson
• John Vlissides
– Design Patterns: Elements of Reusable Object-Oriented Software (1995)
BITS Pilani, Hyderabad Campus
Summary
o What is a pattern
o Pattern templates
o Types of patterns with examples
o How and when to use patterns
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
CS F213
Object Oriented Programming
BITS Pilani
Hyderabad Campus
Prof.R.Gururaj
CS&IS Dept.
Other Object Oriented
Programming Languages
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
C#: is an OOP language part of the .NET framework.
C# is not a pure OOPL since it encompasses functional
programming in addition to the object-oriented paradigm.
It has an object-oriented syntax based on C++ and is
heavily influenced by Java. In some communities it is
thought of as Microsoft’s version of Java.
Like Java, it has garbage collection and it is compiled to an
intermediate language, which is executed by the runtime
environment known as Common Language Runtime (CLR)
which is similar to the JVM.
The C# supports conception of class and instances, as well
as inheritance and polymorphism.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
.NET
.NET is a software framework which is designed
and developed by Microsoft.
There is a variety of programming languages
available on the .Net platform- VB.Net and C#
being the most common ones are .
It is used to build applications for Windows,
phone, web etc.
BITS Pilani, Hyderabad Campus
Python is an object-oriented scripting language developed in
1990 by Guido Van Rossum.
It has become very popular in recent years due to its
application in variety of domains.
Python allows both procedural and objected-oriented
development.
Python allows multiple inheritance.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
Ruby is an object-oriented scripting language developed in
1993 by Matsumiko Yukihiro.
It is similar in purpose to python.
Ruby has a pure object-oriented support.
All methods must belong to some class.
Ruby only supports single inheritance.
Prof.R.Gururaj
Object Oriented Programming
BITS Pilani, Hyderabad Campus
●
Creating a Java Thread
●
Synchronized Keyword
●
Wait and Notify
●
We will create a thread that simply prints out a number 500
times in a row.
class MyThread extends Thread {
int i;
MyThread(int i) {
this.i = i;
}
public void run() {
for (int ctr=0; ctr < 500; ctr++) {
System.out.print(i);
}
}
}
●
To show the difference between parallel and non-parallel
execution, we have the following executable MyThreadDemo
class
class MyThreadDemo {
public static void main(String args[]) {
MyThread t1 = new MyThread(1);
MyThread t2 = new MyThread(2);
MyThread t3 = new MyThread(3);
t1.run();
t2.run();
t3.run();
System.out.print("Main ends");
}}
●
Upon executing MyThreadDemo, we get output that looks like
this
$ java MyThreadDemo
1111111111...22222222.....33333......Main ends
●
●
●
As can be seen, our program first executed t1's run method,
which prints 500 consecutive 1's.
After that t2's run method, which prints consecutuve 2's, and
so on.
Main ends appears at the last part of the output as it is the last
part of the program.
●
What happened was serial execution, no multithreaded
execution occurred
–
This is because we simply called MyThread's run() method
●
To start parallel execution, we call MyThread's start() method,
which is built-in in all thread objects.
class MyThreadDemo {
public static void main(String args[]) {
MyThread t1 = new MyThread(1);
MyThread t2 = new MyThread(2);
MyThread t3 = new MyThread(3);
t1.start();
t2.start();
t3.start();
System.out.print("Main ends");
}}
●
When we run MyThreadDemo we can definitely see that three
run methods are executing at the same time
> java MyThreadDemo
111111111122331122321122333331111Main ends111333222...
●
Note the appearance of the "Main ends" string in the middle of
the output sequence
> java MyThreadDemo
111111111122331122321122333331111Main ends111333222...
●
This indicates that the main method has already finished
executing while thread 1, thread 2 and thread 3 are still
running.
●
Running a main method creates a thread.
–
●
Normally, your program ends when the main thread ends.
However, creating and then running a thread's start method
creates a whole new thread that executes its run() method
independent of the main method.
………………
……………………………
Pausing and Joining
Threads
Threads can be paused by the sleep() method.
●
For example, to have MyThread pause for half a second
before it prints the next number, we add the following lines of
code to our for loop.
●
for (int ctr=0; ctr < 500; ctr++) {
System.out.print(i);
try {
Thread.sleep(500); // 500 miliseconds
} catch (InterruptedException e) { }
}
●
Thread.sleep() is a static method of class thread and can
be invoked from any thread, including the main thread.
for (int ctr=0; ctr < 500; ctr++) {
System.out.print(i);
try {
Thread.sleep(500); // 500 miliseconds
} catch (InterruptedException e) { }
}
●
The InterruptedException is an unchecked exeception that is
thrown by code that stops a thread from running.
–
●
Unchecked exception causing lines must be enclosed in a try-catch, in
this case, Thread.sleep().
An InterruptedException is thrown when a thread is waiting,
sleeping, or otherwise paused for a long time and another
thread interrupts it using the interrupt() method in class
Thread.
●
●
You can also make a thread stop until another thread finishes
running by invoking a thread's join() method.
For instance, to make our main thread to stop running until
thread t1 is finished, we could simply say...
public static void main(String args[]) {
...
t1.start();
try {
t1.join();
} catch (InterruptedException e) { }
t2.start();
●
This would cause all the 1's to be printed out before thread
2 and thread 3 start.
………………
……………………………
Critical Section
Problem
●
●
This section we will find out how to implement a solution to the
critical section problem using Java
Recall that only a single process can enter its critical section,
all other processes would have to wait
–
No context switching occurs inside a critical section
●
Instead of printing a continuous stream of numbers, MyThread
calls a print10() method in a class MyPrinter
–
●
print10() prints 10 continuous numbers on a single line before a
newline.
Our goal is to have these 10 continuous numbers printed
without any context switches occuring.
–
Our output should be:
...
1111111111
1111111111
2222222222
3333333333
1111111111
...
●
We define a class MyPrinter that will have our print10()
method
class MyPrinter {
public void print10(int value) {
for (int i = 0; i < 10; i++) {
System.out.print(value);
}
System.out.println(""); // newline after 10 numbers
}
}
●
Instead of printing numbers directly, we use the print10()
method in MyThread, as shown by the following
class MyThread extends Thread {
int i;
MyPrinter p;
MyThread(int i) {
this.i = i;
p = new MyPrinter();
}
public void run() {
for (int ctr=0; ctr < 500; ctr++) {
p.print10(i);
}
}
}
●
First, we will try to see the output of just a single thread
running.
class MyThreadDemo {
public static void main(String args[]) {
MyThread t1 = new MyThread(1);
// MyThread t2 = new MyThread(2);
// MyThread t3 = new MyThread(3);
t1.start();
// t2.start();
// t3.start();
System.out.print("Main ends");
}}
We comment out
the other threads
for now...
●
When we run our MyThreadDemo, we can see that the output
really does match what we want.
> java MyThreadDemo
1111111111
1111111111
1111111111
1111111111
1111111111
...
●
However, let us try to see the output with other threads.
class MyThreadDemo {
public static void main(String args[]) {
MyThread t1 = new MyThread(1);
MyThread t2 = new MyThread(2);
MyThread t3 = new MyThread(3);
t1.start();
t2.start();
t3.start();
System.out.print("Main ends");
}}
We run all three
threads
Our output would look like the following
●
> java MyThreadDemo
1111111111
111112222222
1111
22233333332
...
●
We do not achieve our goal of printing 10 consecutive
numbers in a row
–
all three threads are executing the print10's method at the same
time, thus having more than one number appearing on a single
line.
●
To achieve our goal there should not be any context switches
happening inside print10()
–
●
●
Only a single thread should be allowed to execute inside print10()
As can be seen, this is an example of the critical section
problem
To solve this, we can use some of the techniques discussed in
our synchronization chapter
●
●
●
●
Busy Wait
Wait and Notify
Semaphores
Monitors
●
●
Now we will discuss Java's
solution to the critical
section problem
Java uses a monitor
construct
–
Only a single thread may run
inside the monitor
Even if P2 is calling method2(), it
has to wait for P1 to finish
●
To turn an object into a monitor, simply put the synchronized
keyword on your method definitions
–
Only a single thread can run any synchronized method in an object
class MyPrinter {
public synchronized void print10(int value) {
for (int i = 0; i < 10; i++) {
System.out.print(value);
}
System.out.println(""); // newline after 10
numbers
}
}
However, even if we did turn our print10() method into a
synchronized method, it will still not work
●
> java MyThreadDemo
1111111111
111112222222
1111
22233333332
...
●
To find out how to make it work, we need to first find out
how the synchronized keyword works
●
Every object in Java has an intrinsic lock
●
When a thread tries to run a synchronized method, it first tries
to get a lock on the object
●
If a thread is successful, then it owns the lock and executes
the synchronized code.
●
Other threads cannot run the synchronized code because the
lock is unavailable
●
Threads can only enter once the thread owning the lock
leaves the synchronized method
●
Waiting threads would then compete on who gets to go next
●
So why doesn't our example work?
●
Because each thread has its own copy of the MyPrinter object!
class MyThread extends Thread {
int i;
MyPrinter p;
MyThread(int i) {
this.i = i;
p = new MyPrinter();
// each MyThread creates
its own MyPrinter!
}
public void run() {
for (int ctr=0; ctr < 500; ctr++) {
p.print10(i);
}
}
}
●
Recall our definition of synchronized methods
–
●
Only a single thread can run any synchronized method in an object
Since each thread has its own MyPrinter object, then no
locking occurs
●
So, to make it work, all threads must point to the same
MyPrinter object
●
Note how all MyThreads now have the same MyPrinter object
class MyThread extends Thread {
int i;
MyPrinter p;
MyThread(int i, MyPrinter p) {
this.i = i; this.p = p
}
public synchronized void run() {
for (int ctr=0; ctr < 500;
ctr++) {
p.print10(i);
}
}
}
class MyThreadDemo {
public static void main(String args[]) {
MyPrinter p = new
MyPrinter();
MyThread t1 = new
MyThread(1,p);
MyThread t2 = new
MyThread(2,p);
MyThread t3 = new
MyThread(3,p);
t1.start();
t2.start();
t3.start();
}}
●
A way to visualize it is that all Java objects can be doors
–
A thread tries to see if the door is open
–
Once the thread goes through the door, it locks it behind it,
–
No other threads can enter the door because our first thread has
locked it from the inside
–
Other threads can enter if the thread inside unlocks the door and goes
out
–
Lining up will only occur if everyone only has a single door to the
critical region
●
Running MyThreadDemo now correctly shows synchronized
methods at work
>java MyThreadDemo
1111111111
1111111111
1111111111
2222222222
3333333333
...
●
Only a single thread can run any synchronized method in an
object
–
●
If an object has a synchronized method and a regular method, only one
thread can run the synchronized method while multiple threads can run
the regular method
Threads that you want to have synchronized must share the
same monitor object
●
●
Aside from synchronized methods, Java also allows for
synchronized blocks.
You must specify what object the intrinsic lock comes from
●
Our print10() implementation, done using synchronized
statements, would look like this
class MyPrinter {
public void print10(int value) {
synchronized(this) {
for (int i = 0; i < 10; i++) {
System.out.print(value);
}
System.out.println(""); // newline after
10 numbers
}
}
}
We use a MyPrinter object for the
lock, replicating what the
synchronized method does
●
●
Synchronized blocks allow for flexibility, in the case if we want
our intrinsic lock to come from an object other than the current
object.
For example, we could define MyThread's run method to
perform the lock on the MyPrinter object before calling print10
class MyThread extends Thread {
MyPrinter p;
...
public void run() {
for (int i = 0; i < 100; i++) {
synchronized(p) {
p.print10(value);
}
}}}
Note that any lines
before and after our
synchronized block can
be executed
concurrently by threads
●
Also, the use of the synchronized block allows for more
flexibility by allowing different parts of code to be locked with
different objects.
●
For example, consider a modified MyPrinter which has two
methods, which we'll allow to run concurrently
class MyPrinter {
The blocks inside print10() and
Object lock1 = new Object();
squareMe() can run at the same time
Object lock2 = new Object();
because they use different objects for
public void print10(int value) {
their locking mechanism
synchronized(lock1) {
for (int i = 0; i < 10; i++) {
System.out.print(value);
}
System.out.println(""); // newline after 10 numbers
}
}
Synchronization still applies. For
public int squareMe(int i) {
example only a single thread can
synchronized (lock2) {
run the synchronized block in
return i * i;
squareMe() at any point in time
}
}
}
●
Creating a Java Thread
●
Synchronized Keyword
●
Wait and Notify
●
High Level Cuncurrency Objects
Synchronization/wait and notify

wait is a method of the Object class. It causes the calling method to wait (blocked) until notified (when
another thread calls notify or notifyAll)

While waiting, a thread relinquishes its object locks. This gives other thread a chance to access the object.

notify or notifyAll are all methods of the Object class.
 notify randomly selects a thread among those waiting for an object lock (inside the object) and
unblocks it.


notifyAll unblocks all threads waiting for an object lock (inside the object). Preferred because it
reduces the probability of deadlock (Exercise: Why is this?).
Note: wait, notify and notifyAll should only be called by a thread that is the owner of this
object's monitor (within synchronized method).
Synchronization/wait and notify
 In our example, a thread calls notifyAll when it is done with a object.
public synchronized void transfer(int from, int to,
int amount)
{ while (accounts[from] < amount)
{ try { wait(); }
catch(InterruptedException e) {}
}
…
notifyAll();
…}
SynchBankTest.java
Synchronization/Deadlock
Deadlock occurs when a number of threads waiting for each other
Example:
Account 1: $2,000
Account 2: $3,000
Thread 1: Transfer $3,000 from account 1 to account 2
Thread 2: Transfer $4,000 from account 2 to account 1
It is the responsibility of programmer to avoid deadlocks.
Summary
• A thread is a path of execution that executes within a process. When you run a Java
program, the main() method runs in a thread. The main() method can start other threads.
• A process terminates when all its non-daemon threads run to completion.
• A thread is created by writing a class that implements java.lang. Runnable and associating
an instance of this class with a new java.lang.Thread object. The new Thread is initially in
the born state.
• Invoking the start() method on a Thread object starts the thread and places it in its
appropriate runnable queue, based on its priority.
Summary
• Java uses a preemptive scheduling mechanism where threads of higher priority preempt
running threads of a lower priority. However, the actual behavior of threads also relies on
the underlying platform.
• A thread can also be written by writing a class that extends java.util.TimerTask and
associating an instance of this class with a java.util.Timer object. This type of thread is
useful when performing scheduled tasks.
Summary
• The synchronized keyword is used to synchronize a thread on a particular object. When a
thread is synchronized on an object, the thread owns the lock of the object. Any other
thread attempting to synchronize
• Care needs to be taken when synchronizing threads, since deadlock may occur. Ordering
locks is a common technique for avoiding deadlock.
• The wait() and notify() methods from the Object class are useful when multiple threads
need to access the same data in any type of producer/consumer scenario.
Utility Class
StringTokenizer
Need
Text processing, to break a given string
into constituent tokens.
Constructor
StringTokenizer(String str)
StringTokenizer(String str, String delim)
StringTokenizer(String str, String delim, boolean
returnValue)
Explanation
ST uses a given string in all cases. In the first
instance the default delimiter (space) is used,
in the second & third, the provided delimiter is
used to break the given string to tokens.
BitSet
A utility class to hold bit values as
Boolean values in a special type of
array
More clean way to manipulate objects
which have no values. Its an effort to
avoid null pointer exception
BitSet( )
BitSet(int size)
The first constructor instantiates a default
object, the second constructor allows to
specify an initial size.
The Date class encapsulates the current
date and time. This also implements
the comparable interface
Date( )
Date(long millisec)
The abstract Calendar class provides a
set of methods that allows you to
convert a time in
milliseconds to a number of useful
components
GregorianCalendar is a concrete
implementation of a Calendar that
implements the normal Gregorian
calendar with we are familiar. The
getInstance( ) method of
Calendar will typically return a
GregorianCalendar initialized with the
current date and time in the default
locale and time zone.
GregorianCalendar defines two fields:
AD and BC. These represent the two
eras defined by the Gregorian calendar.
The SimpleTimeZone class is a
convenient subclass of TimeZone. It
implements TimeZone's abstract
No public constructors are provided. This class
offers several protected variables
Optional,
OptionalDouble,
OptionalInt, and
OptionalLong
Date
Calendar
GregorianCalendar
SimpleTimeZone
class Optional<T>
The first constructor initializes the object with
the current date and time. The second
constructor accepts one argument that equals
the number of milliseconds that have elapsed
since midnight, January 1, 1970
GregorianCalendar(int year, int month, int
dayOfMonth)
GregorianCalendar(int year, int month, int
dayOfMonth, int hours,
int minutes)
GregorianCalendar(int year, int month, int
dayOfMonth, int hours,
int minutes, int seconds)
The first version sets the time to midnight.
The second version also sets the
hours and the minutes.
The third version adds seconds.
SimpleTimeZone(int timeDelta, String tzName)
SimpleTimeZone(int timeDelta, String tzId, int
dstMonth0,int dstDayInMonth0, int dstDay0, int
This constructor creates a SimpleTimeZone
object. The offset relative to Greenwich mean
time (GMT) is timeDelta. The time zone is
named tzName.
Locale
Random
Observable
Timer and
TimerTask
methods and allows you to work with
time zones for a Gregorian
calendar. It also computes daylight
saving time
time0, int dstMonth1, int dstDayInMonth1, int
dstDay1, int time1)
The Locale class is instantiated to
produce objects that describe a
geographical or cultural region.
It is one of several classes that provide
you with the ability to write programs
that can execute in different
international environments
Generate pseudo random numbers.
Locale(String language)
Locale(String language, String country)
Locale(String language, String country, String
variant)
The Observable class is used to create
subclasses that other parts of your
program can observe. When an object
of such a subclass undergoes a change,
observing classes are notified.
Observing classes must implement the
Observer interface, which defines the
update( ) method. The update( )
method is called when an observer is
notified of a change in an observed
object
An interesting and useful feature
offered by java.util is the ability to
schedule a task for execution at some
future time. The classes that support
this are Timer and TimerTask.
Using these classes, you can create a
thread that runs in the background,
waiting for a specific time
Here, the offset relative to GMT is specified in
timeDelta. The time zone name is passed in
tzId. The start of daylight-saving time is
indicated by the parameters dstMonth0,
dstDayInMonth0, dstDay0, and time0. The end
of daylight-saving time is indicated by the
parameters dstMonth1, dstDayInMonth1,
dstDay1, and time1.
These constructors build a Locale object to
represent a specific language and, in the case,
of the last two, country. These values must
contain standard language and country codes.
Auxiliary variant information can be provided
in variant.
Random( )
Random(long seed)
The first version creates a number generator
that uses a reasonably unique seed. The
second form allows you to specify a seed value
manually.
Timer( )
Timer(boolean DThread)
Timer(String tName)
Timer(String tName, boolean DThread)
Timer and TimerTask work together. Timer is
the class that you will use to schedule a
task for execution. The task being scheduled
must be an instance of TimerTask. Thus, to
schedule a task, you will first create a
TimerTask object and then schedule it for
execution using an instance of Timer.
ABSTRACT
Understand the purpose and usage of
each design pattern in order to pick and
implement the correct pattern as needed.
DESIGN
PATTERNS
Introduction
DESIGN PATTERNS
Contents
Introduction ........................................................................................................................................................................... 2
Goal of Design Pattern ..................................................................................................................................................... 2
Types of Design Pattern....................................................................................................................................................... 2
The Scope of design Pattern ........................................................................................................................................... 3
Creational Design Patterns .................................................................................................................................................. 3
Abstract Factory ................................................................................................................................................................ 3
Goal ................................................................................................................................................................................. 3
Problem ........................................................................................................................................................................... 4
Solution ........................................................................................................................................................................... 4
Structure ......................................................................................................................................................................... 4
Important Considerations ............................................................................................................................................... 5
Structural Design Patterns ...................................................................................................................................................... 5
Adapter ............................................................................................................................................................................... 6
Behavioral Design Patterns ..................................................................................................................................................... 6
DESIGN PATTERNS
VADEKKDHIL, ARUN (C)
DESIGN PATTERNS
Introduction
• A design pattern provides a general reusable solution for the common problems that occur in software
design.
• The pattern typically shows relationships and interactions between classes or objects.
• The idea is to speed up the development process by providing well-tested, proven development/design
paradigms.
• Design patterns are programming language independent strategies for solving a common problem.
• That means a design pattern represents an idea, not a particular implementation.
• By using design patterns, you can make your code more flexible, reusable, and maintainable.
• It’s not mandatory to always implement design patterns in your project. Design patterns are not meant
for project development.
• Design patterns are meant for common problem-solving.
• Whenever there is a need, you have to implement a suitable pattern to avoid such problems in the future.
• To find out which pattern to use, you just have to try to understand the design patterns and their
purposes. Only by doing that, you will be able to pick the right one.
Goal of Design Pattern
Understand the purpose and usage of each design pattern in order to pick and implement the correct
pattern as needed.
Types of Design Pattern
DESIGN PATTERNS
VADEKKDHIL, ARUN (C)
DESIGN PATTERNS
The Scope of design Pattern
By Scope, the patterns are broadly classified into class & object. A pattern may either be class-scope or objectscope. Class-scope patterns are those patterns whose goals are realized at compile time using mechanisms like
inheritance. These patterns need no further configuration at run-time. On the other hand, object-scope patterns
which are more common leverage relationships between objects in order to achieve their goals. Object scope
patterns tend to solve the problems by using instances of different polymorphic classes interchangeably. The
goal of an object scope pattern is not achieved merely after compiling since the realization of the purpose is
dependent on certain objects being instantiated and assigned to some special variables.
Creational Design Patterns
These design patterns are all about class instantiation. This pattern can be further divided into class-creation
patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the
instantiation process, object-creation patterns use delegation effectively to get the job done.
Abstract Factory
Goal
•
•
•
Provide an interface for creating families of related or dependent objects without specifying their concrete
classes.
A hierarchy that encapsulates: many possible "platforms", and the construction of a suite of "products".
The new operator considered harmful.
DESIGN PATTERNS
VADEKKDHIL, ARUN (C)
DESIGN PATTERNS
Problem
If an application is to be portable, it needs to encapsulate platform dependencies. These "platforms" might
include: windowing system, operating system, database, etc. Too often, this encapsulation is not engineered in
advance, and lots of #ifdef case statements with options for all currently supported platforms begin to procreate
like rabbits throughout the code.
Solution
Provide a level of indirection that abstracts the creation of families of related or dependent objects without
directly specifying their concrete classes. The "factory" object has the responsibility for providing creation services
for the entire platform family. Clients never create platform objects directly, they ask the factory to do that for
them.
This mechanism makes exchanging product families easy because the specific class of the factory object appears
only once in the application - where it is instantiated. The application can wholesale replace the entire family of
products simply by instantiating a different concrete instance of the abstract factory.
Because the service provided by the factory object is so pervasive, it is routinely implemented as a Singleton.
Structure
The Abstract Factory defines a Factory Method per product. Each Factory Method encapsulates the new operator
and the concrete, platform-specific, product classes. Each "platform" is then modeled with a Factory derived class.
DESIGN PATTERNS
VADEKKDHIL, ARUN (C)
DESIGN PATTERNS
Important Considerations
Sometimes creational patterns are competitors: there are cases when either Prototype or Abstract Factory could
be used profitably. At other times they are complementary: Abstract Factory might store a set of Prototypes from
which to clone and return product objects, Builder can use one of the other patterns to implement which
components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementation.
Abstract Factory, Builder, and Prototype define a factory object that's responsible for knowing and creating the
class of product objects, and make it a parameter of the system. Abstract Factory has the factory object producing
objects of several classes. Builder has the factory object building a complex product incrementally using a
correspondingly complex protocol. Prototype has the factory object (aka prototype) building a product by
copying a prototype object.
Abstract Factory classes are often implemented with Factory Methods, but they can also be implemented using
Prototype.
Abstract Factory can be used as an alternative to Facade to hide platform-specific classes.
Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product
objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory
is concerned, the product gets returned immediately.
Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and
evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers
where more flexibility is needed.
Structural Design Patterns
These design patterns are all about Class and Object composition. Structural class-creation patterns use
inheritance to compose interfaces. Structural object-patterns define ways to compose objects to obtain new
functionality.
DESIGN PATTERNS
VADEKKDHIL, ARUN (C)
DESIGN PATTERNS
Adapter
Behavioral Design Patterns
Behavioral Java patterns give an answer for the higher interaction between objects and the way to produce lose
coupling and adaptability to increase simply.
DESIGN PATTERNS
VADEKKDHIL, ARUN (C)
DESIGN PATTERNS
DESIGN PATTERNS
VADEKKDHIL, ARUN (C)
Download