unit-4
unit-4
unit-4
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
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,
// 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
Example of dynamic binding
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;
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 bindingAllows software systems to be more easily extended during both development
and maintenance e.g., new shape classes are defined later
• 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:
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
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() { . . . }
}
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.
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
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
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
• Blocked - has been running, but cannot now continue (usually waiting for some event to
occur)
• Dead - no longer active in any sense
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
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
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
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:
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
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;
Def: A clause whose guard is true is called open.
Def: A clause whose guard is false is called closed.
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
Cooperation Synchronization with Java Threads
Synchronizing Threads
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
exception_choice form:
exception_name | others
• Handlers are placed at the end of the block or unit in which they occur
Example:
Predefined Exceptions
Evaluation
• Ada was the only widely used language with exception handling until it was added
to C++
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;
}
}
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++
• 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());
}
//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)
• The finally clause is often useful
• The Java interpreter throws a variety of exceptions that can be handled by user
programs
Output oRadioB.java