Ppl-Unit-4 R16
Ppl-Unit-4 R16
Ppl-Unit-4 R16
Object-Oriented Programming
A language that is object oriented must provide support for three key language features:
Inheritance
1. The parent class can define some of its variables or methods to have private access, which
means they will not be visible in the subclass.
2. The subclass can add variables and/or methods to those inherited from the parent class.
3. The subclass can modify the behavior of one or more of its inherited methods. A modified
method has the same name, and often the same protocol, as the one of which it is a modification.
The new method is said to override the inherited method, which is then called an overridden
method.
Classes can have two kinds of methods and two kinds of variables. The most commonly used
methods and variables are called instance methods and instance variables. Every object of a
class has its own set of instance variables, which store the object’s state. The only difference
WWW.KVRSOFTWARES.BLOGSPOT.COM
between two objects of the same class is the state of their instance variables. For example, a class
for cars might have instance variables for color, make, model, and year. Instance methods
operate only on the objects of the class. Class variables belong to the class, rather than its
object, so there is only one copy for the class. For example, if we wanted to count the number of
instances of a class, the counter could not be an instance variable—it would need to be a class
variable
class base_class
{
private:
int a;
float x;
protected:
int b;
float y;
public:
int c;
float z;
};
class subclass_1 : public base_class { … };
// In this one, b and y are protected and
// c and z are public
class subclass_2 : private base_class { … };
// In this one, b, y, c, and z are private,
WWW.KVRSOFTWARES.BLOGSPOT.COM
// and no derived class has access to any
// member of base_class
Dynamic binding
Member functions that must be dynamically bound must be declared to be virtual functions by preceding
their headers with the reserved word virtual, which can appear only in a class body. A method can be
defined to be virtual, which means that they can be called through polymorphic variables and
dynamically bound to messages. A pointer variable that has the type of a base class can be used to
point to any heap-dynamic objects of any class publicly derived from that base class, making it a
polymorphic variable. A polymorphic variable can be defined in a class that is able to reference (or point
to) objects of the class and objects of any of its descendants C++ does not allow value variables to be
polymorphic. A pure virtual function has no definition at all . A class that has at least one pure
virtual function is an abstract class
class Shape
{
public:
virtual void draw() = 0;
. . .
};
class Circle : public Shape
{
public:
void draw() { . . . }
. . .
};
class Rectangle : public Shape
{
public:
void draw() { . . . }
. . .
};
class Square : public Rectangle
{
public:
void draw() { . . . }
. . .
};
Given these definitions, the following code has examples of both statically and dynamically bound calls:
Square* sq = new Square;
WWW.KVRSOFTWARES.BLOGSPOT.COM
Rectangle* rect = new Rectangle;
Shape* ptr_shape;
ptr_shape = sq; // Now ptr_shape points to a
// Square object
ptr_shape->draw(); // Dynamically bound to the draw
// in the Square class
rect->draw(); // Statically bound to the draw
// in the Rectangle class
This situation is shown in Figure 12.6.
dynamic binding allows the code that uses members like draw to be written before all or even any of the
versions of draw are written. New derived classes could be added years later, without requiring any
change to the code that uses such dynamically bound members. This is a highly useful feature of object-
oriented languages.
Abstract classes and inheritance together support a powerful technique for software development.
Dynamic binding Allows software systems to be more easily extended during both development
and maintenance e.g., new shape classes are defined later
WWW.KVRSOFTWARES.BLOGSPOT.COM
Single and multiple inheritance
Object allocation and deallocation
Dynamic and static binding
Nested classes
Initialization of objects
• Everything is an object
– Advantage - elegance and purity
– Disadvantage - slow operations on simple objects
• Add objects to a complete typing system
– Advantage - fast operations on simple objects
– Disadvantage - results in a confusing type system (two kinds of entities)
• Include an imperative-style typing system for primitives but make everything else objects
– Advantage - fast operations on simple objects and a relatively small typing system
– Disadvantage - still some confusion because of the two type systems
Does an “is-a” relationship hold between a parent class object and an object of subclass?
If a derived class is-a parent class, then objects of derived class behave same as
parent class object
subtype small_Int is Integer range 0 .. 100;
Every small_Int variable can be used anywhere Integer variables can be used
A derived class is a subtype if methods of subclass that override parent class are type
compatible with the overridden parent methods
Subclass can only add variables and methods and override inherited methods in
“compatible” ways
Polymorphism may require dynamic type checking of parameters and the return value
Dynamic type checking is costly and delays error detection
If overriding methods are restricted to having the same parameter types and return type,
the checking can be static
Dynamic type checking is costly and delays error detection
Multiple inheritance allows a new class to inherit from two or more classes
Disadvantages of multiple inheritance:
Language and implementation complexity (in part due to name collisions)
Potential inefficiency - dynamic binding costs more with multiple inheritance (but
not much)
Advantage:
WWW.KVRSOFTWARES.BLOGSPOT.COM
Sometimes it is quite convenient and valuable
Nested Classes
• If a new class is needed by only one class, there is no reason to define so it can be seen by
other classes
– Can the new class be nested inside the class that uses it?
– In some cases, the new class is nested inside a subprogram rather than directly in
another class
• Other issues:
– Which facilities of the nesting class should be visible to the nested class and vice
versa
WWW.KVRSOFTWARES.BLOGSPOT.COM
12.11 Implementation of Object-Oriented Constructs
There are at least two parts of language support for object-oriented programming
In C++, classes are defined as extensions of C’s record structures—structs. This similarity
suggests a storage structure for the instance variables of class instances—that of a record. This
form of this structure is called a class instance record (CIR). The structure of a CIR is static, so
it is built at compile time and used as a template for the creation of the data of class instances.
Every class has its own CIR. When a derivation takes place, the CIR for the subclass is a copy of
that of the parent class, with entries for the new instance variables added at the end. Because the
structure of the CIR is static, access to all instance variables can be done as it is in records, using
constant offsets from the beginning of the CIR instance. This makes these accesses as efficient as
those for the fields of records.
• Methods in a class that are statically bound need not be involved in the CIR; methods that
will be dynamically bound must have entries in the CIR
– Calls to dynamically bound methods can be connected to the corresponding code
thru a pointer in the CIR
– The storage structure is sometimes called virtual method tables (vtable)
– Method calls can be represented as offsets from the beginning of the vtable
Consider the following Java example, in which all methods are dynamically bound:
public class A
{
public int a, b;
public void draw() { . . . }
public int area() { . . . }
}
public class B extends A
{
public int c, d;
public void draw() { . . . }
public void sift() { . . . }
}
WWW.KVRSOFTWARES.BLOGSPOT.COM
The CIRs for the A and B classes, along with their vtables, are shown in Figure 12.7. Notice that
the method pointer for the area method in B’s vtable points to the code for A’s area method. The
reason is that B does not override A’s area method, so if a client of B calls area, it is the area
method inherited from A. On the other hand, the pointers for draw and sift in B’s vtable point to
B’s draw and sift. The draw method is overridden in B and sift is defined as an addition in B.
WWW.KVRSOFTWARES.BLOGSPOT.COM
The C class inherits the variable a and the init method from the A class. It redefines the fun
method, although both its fun and that of the parent class A are potentially visible through a
polymorphic variable (of type A). From B, C inherits the variable b and the sum method. C
defines its own variable, c, and defines an uninherited method, dud. A CIR for C must include
A’s data, B’s data, and C’s data, as well as some means of accessing all visible methods. Under
single inheritance, the CIR would include a pointer to a vtable that has the addresses of the code
of all visible methods.
There must also be two vtables: one for the A and C view and one for the B view. The first part
of the CIR for C in this case can be the C and A view, which begins with a vtable pointer for the
methods of C and those inherited from A, and includes the data inherited from A. Following this
in C’s CIR is the B view part, which begins with a vtable pointer for the virtual methods of B,
which is followed by the data inherited from B and the data defined in C. The CIR for C is
shown in Figure 12.8.
13 Concurrency
13.1 Introduction
13.2 Introduction to Subprogram-Level Concurrency
13.3 Semaphores
13.4 Monitors
13.5 Message Passing
13.6 Ada Support for Concurrency
13.7 Java Threads
13.8 C# Threads
13.9 Concurrency in Functional Languages
13.10 Statement-Level Concurrency
WWW.KVRSOFTWARES.BLOGSPOT.COM
Introduction
• Involves a different way of designing software that can be very useful—many real-world
situations involve concurrency
• Multiprocessor computers capable of physical concurrency are now widely used
Introduction to Subprogram-Level Concurrency
• A task or process is a program unit that can be in concurrent execution with other
program units
• Tasks differ from ordinary subprograms in that:
– A task may be implicitly started
– When a program unit starts the execution of a task, it is not necessarily suspended
– When a task’s execution is completed, control may not return to the caller
• Tasks usually work together
Two General Categories of Tasks
• Heavyweight tasks execute in their own address space
• Lightweight tasks all run in the same address space – more efficient
• A task is disjoint if it does not communicate with or affect the execution of any other task
in the program in any way
WWW.KVRSOFTWARES.BLOGSPOT.COM
Task Synchronization
Cooperation synchronization
• Task B must wait for task A to complete some specific activity before task B can
continue its execution, e.g., the producer-consumer problem
Competition synchronization
• Two or more tasks must use some resource that cannot be simultaneously used, e.g., a
shared counter
– Competition is usually provided by mutually exclusive access (approaches are
discussed later)
Need for Competition Synchronization
Scheduler
• Providing synchronization requires a mechanism for delaying task execution
• Task execution control is maintained by a program called the scheduler, which maps task
execution onto available processors
Task Execution States
• New - created but not yet started
• Rready - ready to run but not currently running (no available processor)
• Running
WWW.KVRSOFTWARES.BLOGSPOT.COM
• Blocked - has been running, but cannot now continue (usually waiting for some event to
occur)
• Dead - no longer active in any sense
WWW.KVRSOFTWARES.BLOGSPOT.COM
Cooperation Synchronization with Semaphores
release(aSemaphore)
if aSemaphore’s queue is empty then
increment aSemaphore’s counter
else
put the calling task in the task ready queue
transfer control to a task from aSemaphore’s queue
end
WWW.KVRSOFTWARES.BLOGSPOT.COM
fullstops.count = 0;
emptyspots.count = BUFLEN;
task producer;
loop
-- produce VALUE –-
wait (emptyspots); {wait for space}
DEPOSIT(VALUE);
release(fullspots); {increase filled}
end loop;
end producer;
Consumer Code
task consumer;
loop
wait (fullspots);{wait till not empty}}
FETCH(VALUE);
release(emptyspots); {increase empty}
-- consume VALUE –-
end loop;
end consumer;
producer code
WWW.KVRSOFTWARES.BLOGSPOT.COM
Consumer Code
task consumer;
loop
wait(fullspots);{wait till not empty}
wait(access); {wait for access}
FETCH(VALUE);
release(access); {relinquish access}
release(emptyspots); {increase empty}
-- consume VALUE –-
end loop;
end consumer;
Evaluation of Semaphores
• Misuse of semaphores can cause failures in cooperation synchronization, e.g., the buffer
will overflow if the wait of fullspots is left out
• Misuse of semaphores can cause failures in competition synchronization, e.g., the
program will deadlock if the release of access is left out
Monitors
One solution to some of the problems of semaphores in a concurrent environment is to
encapsulate shared data structures with their operations and hide their representations—that is, to
make shared data structures abstract data types with some special restrictions
• The idea: encapsulate the shared data and its operations to restrict access
• A monitor is an abstract data type for shared data
Competition Synchronization
• Shared data is resident in the monitor (rather than in the client units)
• All access resident in the monitor
– Monitor implementation guarantee synchronized access by allowing only
one access at a time
– Calls to monitor procedures are implicitly queued if the monitor is busy at
the time of the call
Cooperation Synchronization
WWW.KVRSOFTWARES.BLOGSPOT.COM
Fig: A program using a monitor to control access to a shared buffer
Evaluation of Monitors
Message Passing
•
Message passing is a general model for concurrency
– It can model both semaphores and monitors
– It is not just for competition synchronization
• Central idea: task communication is like seeing a doctor--most of the time she
waits for you or you wait for her, but when you are both ready, you get together,
or rendezvous
Message Passing Rendezvous
• To support concurrent tasks with message passing, a language needs:
WWW.KVRSOFTWARES.BLOGSPOT.COM
task Task_Example is
entry ENTRY_1 (Item : in Integer);
end Task_Example;
Task Body
• The body task describes the action that takes place when a rendezvous occurs
• A task that sends a message is suspended while waiting for the message to be
accepted and during the rendezvous
• Entry points in the spec are described with accept clauses in the body
The task executes to the top of the accept clause and waits for a message
During execution of the accept clause, the sender is suspended
The basic concept of synchronous message passing is that tasks are often busy, and when busy, they
cannot be interrupted by other units. Suppose task A and task B are both in execution, and A wishes to
WWW.KVRSOFTWARES.BLOGSPOT.COM
send a message to B. Clearly, if B is busy, it is not desirable to allow another task to interrupt it. That
would disturb B’s current processing. . The alternative is to provide a Linguistic mechanism that allows a
task to specify to other tasks when it is ready to receive messages.
.
If task A is waiting for a message at the time task B sends that message, the message can be
transmitted. This actual transmission of the message is called a rendezvous. Note that a rendezvous can
occur only if both the sender and receiver want it to happen. During a rendezvous, the information of the
message can be transmitted in either or both directions.
Both cooperation and competition synchronization of tasks can be conveniently handled with the
message-passing model, as described in the following section.
- Example:
task body buf_task is
begin
loop
--------
end DEPOSIT;
end loop;
end buf_task;
WWW.KVRSOFTWARES.BLOGSPOT.COM
Def: A clause whose guard is true is called open.
Def: A clause whose guard is false is called closed.
WWW.KVRSOFTWARES.BLOGSPOT.COM
end loop;
end Consumer;
Java Threads
• The concurrent units in Java are methods named run
– A run method code can be in concurrent execution with other such methods
– The process in which the run methods execute is called a thread
Class myThread extends Thread
public void run () {…}
}
…
Thread myTh = new MyThread ();
myTh.start();
• A method that includes the synchronized modifier disallows any other method
from running on the object while it is in execution
…
public synchronized void deposit( int i) {…}
public synchronized int fetch() {…}
…
• The above two methods are synchronized which prevents them from interfering
with each other
• If only a part of a method must be run without interference, it can be synchronized
thru synchronized statement
synchronized (expression)
statement
WWW.KVRSOFTWARES.BLOGSPOT.COM
Cooperation Synchronization with Java Threads
Synchronizing Threads
WWW.KVRSOFTWARES.BLOGSPOT.COM
Statement-Level Concurrency
• Objective: Provide a mechanism that the programmer can use to inform compiler
of ways it can map the program onto multiprocessor architecture
• Minimize communication among processors and the memories of the other
processors
High-Performance Fortran
• Number of processors
!HPF$ PROCESSORS procs (n)
• Distribution of data
!HPF$ DISTRIBUTE (kind) ONTO procs :: identifier_list
– kind can be BLOCK (distribute data to processors in blocks) or CYCLIC
(distribute data to processors one element at a time)
• Relate the distribution of one array with that of another
ALIGN array1_element WITH array2_element
WWW.KVRSOFTWARES.BLOGSPOT.COM
•Specifies that all 1,000 RHSs of the assignments can be evaluated before any
assignment takes place
Summary
• Concurrent execution can be at the instruction, statement, or subprogram level
• Physical concurrency: when multiple processors are used to execute concurrent
units
• Logical concurrency: concurrent united are executed on a single processor
• Two primary facilities to support subprogram concurrency: competition
synchronization and cooperation synchronization
• Mechanisms: semaphores, monitors, rendezvous, threads
• High-Performance Fortran provides statements for specifying how data is to be
distributed over the memory units connected to multiple processors
WWW.KVRSOFTWARES.BLOGSPOT.COM
Exception Handling Control Flow
exception_choice form:
exception_name | others
• Handlers are placed at the end of the block or unit in which they occur
Example:
WWW.KVRSOFTWARES.BLOGSPOT.COM
use Age_IO;
Age_List : Age_List_Type;
. . .
begin
for Age_Count in 1..4 loop
loop -- loop for repetition when exceptions occur
Except_Blk:
begin -- compound to encapsulate exception handling
Put_Line("Enter an integer in the range 0..125");
Get(Age_List(Age_Count));
exit;
exception
when Data_Error => -- Input string is not a number
Put_Line("Illegal numeric value");
Put_Line("Please try again");
when Constraint_Error => -- Input is < 0 or > 125
Put_Line("Input number is out of range");
Put_Line("Please try again");
end Except_Blk;
end loop; -- end of the infinite loop to repeat input
-- when there is an exception
end loop; -- end of for Age_Count in 1..4 loop
. . .
Predefined Exceptions
Evaluation
• Ada was the only widely used language with exception handling until it was added
to C++
WWW.KVRSOFTWARES.BLOGSPOT.COM
try {
-- code that is expected to raise an exception
}
catch (formal parameter) {
-- handler code
}
...
catch (formal parameter) {
-- handler code
}
int main()
{
int a,b;
cout<<“enter a,b values:”;
cin>>a>>b;
try{
if(b!=0)
cout<<“result is:”<<(a/b);
else
throw b;
}
catch(int e)
{
cout<<“divide by zero error occurred due
to b= “ << e;
}
}
WWW.KVRSOFTWARES.BLOGSPOT.COM
Binding Exceptions to Handlers
Classes of Exceptions
• Like those of C++, except every catch requires a named parameter and all
parameters must be descendants of Throwable
• Syntax of try clause is exactly that of C++, except for the finally clause
• Exceptions are thrown with throw, as in C++, but often the throw includes the new
operator to create the object as : throw new MyException();
• The Java throws clause is quite different from the throw clause of C++
WWW.KVRSOFTWARES.BLOGSPOT.COM
• Exceptions of class Error and RunTimeException and all of their descendants are
called unchecked exceptions; all other exceptions are called checked exceptions
• Checked exceptions that may be thrown by a method must be either:
– Listed in the throws clause, or
– Handled in the method
finally clause
import java.io.*;
class Test
{
public static void main(String args[]) throws IOException
{
int a[],b,c;
DataInputStream dis=new DataInputStream(System.in);
a=new int[5];
for(int i=0;i<5;i++)
{
a[i]=Integer.parseInt(dis.readLine());
}
WWW.KVRSOFTWARES.BLOGSPOT.COM
//displaying the values from array
try{
for(int i=0;i<7;i++)
{
System.out.println(a[i]);
}
}
catch(Exception e)
{
finally
{
}
}
O/P: 1 2 3 4 5
12345
The runtime error is : ArrayIndexOutOfBoundsException: 5
100% wiil be executed
Assertions
• The types of exceptions makes more sense than in the case of C++
• The throws clause is better than that of C++ (The throw clause in C++ says little to
the programmer)
WWW.KVRSOFTWARES.BLOGSPOT.COM
• The finally clause is often useful
• The Java interpreter throws a variety of exceptions that can be handled by user
programs
• User interactions with GUI components create events that can be caught by event
handlers, called event listeners
• An event generator tells a listener of an event by sending a message
• An interface is used to make event-handling methods conform to a standard protocol
• A class that implements a listener must implement an interface for the listener
• One class of events is ItemEvent, which is associated with the event of clicking a
checkbox, a radio button, or a list item
• The ItemListener interface prescribes a method, itemStateChanged, which is a handler for
ItemEvent events
• The listener is created with addItemListener
• /* RadioB.java
• An example to illustrate event handling with interactive
• radio buttons that control the font style of a textfield
• */
package radiob;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioB extends JPanel implements
ItemListener {
private JTextField text;
private Font plainFont, boldFont, italicFont,
boldItalicFont;
private JRadioButton plain, bold, italic, boldItalic;
private ButtonGroup radioButtons;
// The constructor method is where the display is initially
// built
WWW.KVRSOFTWARES.BLOGSPOT.COM
public RadioB() {
// Create the test text string and set its font
text = new JTextField(
"In what font style should I appear?", 25);
text.setFont(plainFont);
// Create radio buttons for the fonts and add them to
// a new button group
plain = new JRadioButton("Plain", true);
bold = new JRadioButton("Bold");
italic = new JRadioButton("Italic");
boldItalic = new JRadioButton("Bold Italic");
radioButtons = new ButtonGroup();
radioButtons.add(plain);
radioButtons.add(bold);
radioButtons.add(italic);
radioButtons.add(boldItalic);
// Create a panel and put the text and the radio
// buttons in it; then add the panel to the frame
JPanel radioPanel = new JPanel();
radioPanel.add(text);
radioPanel.add(plain);
radioPanel.add(bold);
radioPanel.add(italic);
radioPanel.add(boldItalic);
add(radioPanel, BorderLayout.LINE_START);
// Register the event handlers
plain.addItemListener(this);
bold.addItemListener(this);
italic.addItemListener(this);
boldItalic.addItemListener(this);
// Create the fonts
plainFont = new Font("Serif", Font.PLAIN, 16);
boldFont = new Font("Serif", Font.BOLD, 16);
italicFont = new Font("Serif", Font.ITALIC, 16);
boldItalicFont = new Font("Serif", Font.BOLD +
Font.ITALIC, 16);
} // End of the constructor for RadioB
// The event handler
public void itemStateChanged (ItemEvent e) {
// Determine which button is on and set the font
// accordingly
if (plain.isSelected())
text.setFont(plainFont);
else if (bold.isSelected())
text.setFont(boldFont);
else if (italic.isSelected())
text.setFont(italicFont);
else if (boldItalic.isSelected())
text.setFont(boldItalicFont);
} // End of itemStateChanged
// The main method
public static void main(String[] args) {
// Create the window frame
JFrame myFrame = new JFrame(" Radio button
example");
// Create the content pane and set it to the frame
JComponent myContentPane = new RadioB();
WWW.KVRSOFTWARES.BLOGSPOT.COM
myContentPane.setOpaque(true);
myFrame.setContentPane(myContentPane);
// Display the window.
myFrame.pack();
myFrame.setVisible(true);
}
} // End of RadioB
Output oRadioB.java
WWW.KVRSOFTWARES.BLOGSPOT.COM