164 - CS6456 Object Oriented Programming - Notes 1
164 - CS6456 Object Oriented Programming - Notes 1
1. CONTENT LIST:
Why Object-Oriented Programming in C++
2. SKILLS ADDRESSED:
Learning
4. OUTCOMES:
i. Explain the various Object Oriented concepts.
ii. Explain the difference between object oriented and procedure oriented concepts.
5. LINK SHEET:
i. What is Object oriented programming?
ii. List the Object Oriented concepts
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
INTRODUCTION TO C++:
Difference between Procedure oriented programming and Object oriented programming.
POP OOP
1) Emphasis on non-real item Emphasis on real item
2) Programs are divided into Programs are divided into Objects
functions Data are not sharable
3) Data are sharable Object Oriented Programming
4) Structured Programming Bottom-Up Approach
5) Top-Down Approach
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Tokens
Smallest individual unit in a program. C++ tokens are Keywords, Identifiers, Constants,
Strings, Operators.
Operators in C++
:: Scope Resolution Operator
: :* Member pointer operator
->* Pointer-to-Pointer Member using pointer to object Operator
.* Pointer-to-Pointer Member using object Operator
delete Memory Release Operator
endl Line feed operator
new Memory allocation operator
Setw Memory width operator
Casting operator for C-style casting from any type to any other irrelevant type
reinterpret_cast
const_cast Removing the const nature of a variable while casting.
dynamic_cast casting operator that can be used to safeguard against irrelevant
casting ,used in case of polymorphic classes.
typeid used to find type of an object at run time
throw useful for throwing an exception at the time of an error.
Expressions in C++
Constant Expressions
Integral Expressions
Float Expressions
Pointer Expressions
Relational Expressions
Logical Expressions
Bitwise Expressions
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Inheritance
Polymorphism
Dynamic binding
Message passing
OBJECTS :
Objects are the basic run-time entities in an object – oriented system. They represent a
person,place,a bank account or a table of data or item that a program has to handle.When
a program is executed,the objects interact by passing messages to each other.
Eg: Customer and account are two objects. The customer object may send a
message to the account object requesting for bank balance.
CLASSES :
A Class is collection of objects of similar type. Objects are variables of the type class.
Classes are user defined data-types and behave like a built in type of a programming
language.
Eg: Apple, Mango, Orange are members of the class fruits.
Syntax : fruit mango ; Fruits
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
attributes. The attributes are called members and functions as methods or member functions. The
classes use Data abstraction and are called Abstract Data Types(ADT).
Eg: Abstraction example: ATM is a good example of abstraction, we doesn't know what
are all the internal processes that are going when we access it..instead we know only the
inquiries, deposit, withdrawal etc.
The wrapping up of data and functions into a single unit(class) is called Encapsulation.
The data is not accessible to the outside world ,and those functions that are wrapped in the class
can access it. This insulation of program by direct access of program is called data hiding or
Information hiding.
Eg: Ink is the important component in pen but it is hiding by some other material.
you don't "need to know the internal working of the mobile phone to operate" with it.
You have an interface to use the device behaviour without knowing implementation details.
INHERITANCE :
Inheritance is the processs by which the object of one class acquire the properties
of objects of another class.
Eg: class Bird-> class flying bird ->class robin
ABSTRACT CLASSES:
Abstract class is the class with no objects. The abstract classes does not represent any
real-world entity. The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes cannot be used to
instantiate objects and serves only as an interface.
Consider the following example where parent class provides an interface to the base class to
implement a function called getArea():
#include <iostream>
// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
ABSTRACT CLASSES:
Abstract class is the class with no objects. The abstract classes does not represent any
real-world entity. The purpose of an abstract class (often referred to as an ABC) is to provide an
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
appropriate base class from which other classes can inherit. Abstract classes cannot be used to
instantiate objects and serves only as an interface.
Consider the following example where parent class provides an interface to the base class to
implement a function called getArea():
#include <iostream>
// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
POLYMORPHISM:
Polymorphism is a concept in which the operation may exhibit different behaviour in
different instances.
Eg: addition will sum two numbers in case of numerical operands. In case of
string , it will form a third string by concatenation.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
cout<<"Sum = "<<c<<endl;
}
void sum()
{
c= a+b;
}
};
void main()
{
add x; // x is a object off add
clrscr();
x.read();
x.sum();
x. display();
getch();
}
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time applications
Neural networks and parallel processing
Object oriented systems
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Native Types and Statements
2. SKILLS ADDRESSED:
Learning
4. OUTCOMES:
iii. Explain the various Object Oriented concepts.
iv. Explain the difference between object oriented and procedure oriented concepts.
5. LINK SHEET:
iii. What is Object oriented programming?
iv. List the Object Oriented concepts
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
C++ is a superset of C, and that virtually any legal C program is a legal C++ program.
C++ Compiler:
This is actual C++ compiler, which will be used to compile your source code into final
executable program.
Most C++ compilers don't care what extension you give your source code, but if you don't
specify otherwise, many will use .cpp by default
Most frequently used and free available compiler is GNU C/C++ compiler, otherwise you can
have compilers either from HP or Solaris if you have respective Operating Systems.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
int main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
Comments in C++
C++ supports single line and multi-line comments. All characters available inside any comment
are ignored by C++ compiler.
C++ comments start with /* and end with */. For example:
/* This is a comment */
A comment can also start with //, extending to the end of the line. For example:
#include <iostream>
using namespace std;
main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
C++ Primitive Built-in Types:
C++ offer the programmer a rich assortment of built-in as well as user-defined data types.
Following table list down seven basic C++ data types:
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
C++ Constants/Literals:
Constants refer to fixed values that the program may not alter and they are called literals.
Constants can be of any of the basic data types and can be divided in Integer Numerals, Floating-
Point Numerals, Characters, Strings and Boolean Values.
Again, constants are treated just like regular variables except that their values cannot be modified
after their definition.
signed
unsigned
long
short
The modifiers signed, unsigned, long, and short can be applied to integer base types. In
addition,signed and unsigned can be applied to char, and long can be applied to double.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For
exampleunsigned long int.
C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply
use the word unsigned, short, or long, without the int. The int is implied. For example, the
following two statements both declare unsigned integer variables.
unsigned x;
unsigned int y;
auto
register
static
extern
mutable
C++ Operators:
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provides following type of operators:
Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=)
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Statement Description
An if statement consists of a boolean expression followed by
if statement
one or more statements.
An if statement can be followed by an optional else statement,
if...else statement
which executes when the boolean expression is false.
A switch statement allows a variable to be tested for equality
switch statement
against a list of values.
You can use one if or else if statement inside another if or
nested if statements
else if statement(s).
You can use one swicth statement inside another switch
nested switch statements
statement(s).
C++ Functions:
The general form of a C++ function definition is as follows:
A C++ function definition consists of a function header and a function body. Here are all the
parts of a function:
Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without returning a
value. In this case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time applications
Neural networks and parallel processing
Object oriented systems
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Functions and Pointers
2. SKILLS ADDRESSED:
Learning
4. OUTCOMES:
v. Explain the various Functions.
vi. Explain in detail about pointers.
5. LINK SHEET:
v. What is Friend Functions
vi. Illustrate Arrays and pointers
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
FRIEND FUNCTIONS
The non-member functions are not allowed to access an object’s private and protected
members.
C++ allows the non-member functions to access the private members by using friend functions.
The functions that are declared with the keyword friend are called friend functions.
Characteristics:
The scope of the friend function is not limited to the class in which it has been declared.
A friend function can not be called using the object of that class.
It can not access the class members directly.
It can be declared either in private or in public.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Example
class student
{
private:
int number;
int total;
public:
void getdata(int n, int t)
{
number = n;
total = t;
}
friend void display(student s); // The non-member function display is declared as friend
};
void display(student s) // non-member function accesses the private members because it is
friend.
{
cout<<”Roll number is:”<<s.number;
cout<<”Total is:”<<s.total;
}
Example
class one
{
private:
int n1;
public:
void getdata(int num1)
{
n1=num1;
}
friend int add(one o, two t); // The non-member function add is declared as friend
};
class two
{
private:
int n2;
public:
void getdata(int num2)
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
{
n2=num2;
{
friend int add(one o, two t); // The non-member function add is declared as friend
};
int add(one o, two t) // non-member function accesses the private members n1& n2. because it
is friend
{
return(o.n1 + t.n2);
}
void main()
{
one o;
two t;
o.getdata(5);
t.getdata(10);
cout<<”result=”<<add(o,t);
}
Friend functions are special functions. The class grants these functions a special
privilege to access private variables of the class. It is given by writing the specific function’s
prototype in the class definition precedes with word friend.
Eg: program:
#include<iostream.h>
#include<conio.h>
class base
{
int val1,val2;
public:
void get()
{
cout<<"Enter two values:";
cin>>val1>>val2;
}
friend float mean(base ob);
};
float mean(base ob)
{
return float(ob.val1+ob.val2)/2;
}
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
void main()
{
clrscr();
base obj;
obj.get();
cout<<"\n Mean value is : "<<mean(obj);
getch();
}
Output:
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time applications
Neural networks and parallel processing
Object oriented systems
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Implementing ADTs in the Base Language
2. SKILLS ADDRESSED:
Learning
4. OUTCOMES:
Explain with an example about Stack.
5. LINK SHEET:
Illustrate Stack.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
This reading reviews strategies of problem solving discussed in this class. Then, building on
recent work, the reading introduces stacks and queues as examples of useful classes.
Handling Complexity:
Since many computer applications address complex problems, problem-solving with computers
must include a consideration of the handling of complexity. Already in this course, we have seen
several such strategies and use a variety of language capabilities.
Each of these topics allow us to organize a complex problem or task into relatively manageable
parts and then to focus on those parts. Note that several of the items lists involve abstraction: we
think of processing at a relatively high level, with details pushed aside to a separate procedure,
structure, or file.
For example, association lists allow a natural matching of keyword and data, so we can focus
upon the storage and retrieval of these information pairs. The assoc procedure retrieves relevant
data, and we need not be bothered about the details of this retrieval.
Stacks as ADTs:
Conceptually, the stack class or abstract data type mimics the information kept in a pile on a
desk. Informally, we first consider materials on a desk, where we may keep separate piles for
bills that need paying, magazines that we plan to read, and notes we have taken. These piles of
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
materials have several properties. Each pile contains some papers (information). In addition, for
each pile, we can do several tasks:
These operations allow us to do all the normal processing of data at a desk. For example, when
we receive bills in the mail, we add them to the pile of bills until payday comes. We then take the
bills, one at a time, off the top of the pile and pay them until the money runs out.
When discussing these operations it is customary to call the addition of an item to the top of the
pile a Push operation and the deletion of an item from the top a Pop operation.
More formally, a stack is defined as a class that can store data and that has the following
operations:
Make-Stack
Create a new, empty stack object.
Empty
Empty returns true or false (#t or #f), depending upon whether the stack contains any
items or not.
Push
Push adds the specified item to the top of the stack.
Pop
If the stack is not empty, Pop removes the top item from the stack, and this item is
returned.
If the stack is empty, nothing is returned, and an error is reported.
Top
If the stack is not empty, the top item is returned, but the contents of the stack are not
changed.
If the stack is empty, nothing is returned, and an error is reported.
This specification says nothing about how we will program the various stack operations; rather,
it tells us how stacks can be used. We can also infer some limitations on how we can use the
data. For example, stack operations allow us to work with only the top item on the stack. We
cannot look at other pieces of data lower down in the stack without first using Pop operations to
clear away items above the desired one.
A Push operation always puts the new item on top of the stack, and this is the first item returned
by a Pop operation. Thus, the last piece of data added to the stack will be the first item removed.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
One approach to problem solving involves an initial focus on data elements, operations on those
elements, and relationships among data. Within computer science, such an approach motivates
the viewpoint ofobject-oriented programming or OOP. When working within an OOP
framework, it is useful to distinguish between the general notion of a class and specific uses of
the class with definite data values, which constitutes an object.
Utilizing the notion of abstraction, we think of objects as self-contained entities, just as we might
consider each pile on a desk as an separate, independent collection of material. To support this
image, processing involving objects consists of sending messages to the objects, letting the
object react to the object in an appropriate way, and receiving responses back. Within an OOP
context, a mechanism for interpreting messages is called a method. For example, if our desk had
two piles -- one for magazines and one for bills, we might have the following interaction:
Stacks in Scheme
To implement a class within Scheme, we may proceed following the recent reading on Abstract
Data Types. The simplest approach is to maintain an internal list within the abstract data type or
class. With this approach, push and pop operations insert or delete an item from the front of the
list, the empty operation tests if the list is empty, and the top operation returns the head of the list.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Sometimes we want a data structure that provides access to its elements on "first-in, first-out"
basis, rather than the "last-in, first-out" constraint that a stack imposes. (For example, it might be
prudent to treat that pile of unpaid bills a little differently, adding new elements at the bottom of
the pile rather than the top, Paying off the most recent bill first, as in a stack, can make one's
other, older creditors a little testy.)
Such a structure is called a queue. Like a line of people waiting for some service, a queue
acquires new elements at one end (the rear of the queue) and releases old elements at the other
(the front). Here is the abstract data type definition for queues, with the conventional names for
the operations:
create
Create a new, empty queue object.
empty
Determine whether the queue is empty; return true if it is and false if it is not.
enqueue
Add a new element at the rear of a queue.
dequeue
Remove an element from the front of the queue and return it. (This operation cannot be
performed if the queue is empty.)
front
Return the element at the front of the queue (without removing it from the queue).
(Again, this operation cannot be performed if the queue is empty.)
Queues in Scheme
The implementation of queues in Scheme is somewhat trickier than the implementation of stacks.
Again, we'll keep the elements of the queue in a list. However, it turns out that
the enqueue operation can be slightly faster if we represent an empty queue by a list containing
one element, a "dummy header," and store the actual queue elements after this header, oldest
first. The dummy header is not inserted byenqueue and cannot be removed by the dequeue. It is
not there to provide a value, but just to keep the list from becoming null, so that one can always
apply the set-cdr! procedure to it without first testing to see whether it is null. The fact that the
underlying list never becomes completely null is an invariant of this implementation of queues.
The other novel feature of this implementation is that we'll actually be accessing the list through
two different fields, front and rear. The front field always contains the entire list structure,
beginning with the dummy header; (cdr front) is the list of the actual elements of the queue,
and (cadr front) is the first element of the queue (when it is not empty). The rear field, on the
other hand, is always a one-element list; it contains the last element of the queue, except when
the queue is empty, in which case the rear field contains the dummy header.
The following box-and-pointer diagram shows a queue into which the symbols a, b, and c have
been enqueued, in that order:
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
(define queue-class
(lambda ()
(let* ((front (list 'dummy-header))
(rear front))
(lambda (message . arguments)
(case message
((empty?) (null? (cdr front)))
((enqueue!)
(if (null? arguments)
(error 'queue-class "method ENQUEUE!: An argument is required")
(begin
((dequeue!)
(if (null? (cdr front))
(error 'queue-class "method DEQUEUE!: The queue is empty")
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
((front)
(if (null? (cdr front))
(error 'queue "method FRONT: The queue is empty")
(cadr front)))
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time applications
Neural networks and parallel processing
Object oriented systems
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Data Hiding and Member Functions
2. SKILLS ADDRESSED:
Learning
4. OUTCOMES:
i. Explain Data hiding.
ii. Explain member function.
5. LINK SHEET:
i. What is Data hiding?
ii. Illustrate member function
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Encapsulation is an Object Oriented Programming concept that binds together the data and
functions that manipulate the data, and that keeps both safe from outside interference and misuse.
Data encapsulation led to the important OOP concept of data hiding.
Data encapsulation is a mechanism of bundling the data, and the functions that use them
and data abstraction is a mechanism of exposing only the interfaces and hiding the
implementation details from the user.
C++ supports the properties of encapsulation and data hiding through the creation of user-
defined types, called classes. We already have studied that a class can contain private,
protected and publicmembers. By default, all items defined in a class are private. For example:
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
The variables length, breadth, and height are private. This means that they can be
accessed only by other members of the Box class, and not by any other part of your program.
This is one way encapsulation is achieved.
To make parts of a class public (i.e., accessible to other parts of your program), you must declare
them after the public keyword. All variables or functions defined after the public specifier are
accessible by all other functions in your program.
Making one class a friend of another exposes the implementation details and reduces
encapsulation. The ideal is to keep as many of the details of each class hidden from all other
classes as possible.
Any C++ program where you implement a class with public and private members is an
example of data encapsulation and data abstraction. Consider the following example:
#include <iostream>
using namespace std;
class Adder{
public:
// constructor
Adder(int i = 0)
{
total = i;
}
// interface to outside world
void addNum(int number)
{
total += number;
}
// interface to outside world
int getTotal()
{
return total;
};
private:
// hidden data from outside world
int total;
};
int main( )
{
Adder a;
a.addNum(10);
a.addNum(20);
a.addNum(30);
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
When the above code is compiled and executed, it produces the following result:
Total 60
Above class adds numbers together, and returns the sum. The public
members addNum and getTotalare the interfaces to the outside world and a user needs to know
them to use the class. The private member total is something that is hidden from the outside
world, but is needed for the class to operate properly.
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time applications
Neural networks and parallel processing
Object oriented systems
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Object Creation and Destruction
2. SKILLS ADDRESSED:
Learning
4. OUTCOMES:
Explain the concept of constructor.
Explain copy constructor.
Illustrate constructor with default arguments.
Explain how objects can be initialized dynamically.
Explain about default constructor.
Explain about destructors.
Explain the difference between constructors and destructors
5. LINK SHEET:
What is a constructor ?
Give the syntax for constructor.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
CONSTRUCTORS :
Constructor is a special member function whose task is to initialize object of its class. It is
special because its name is same as that of class name. The constructor is invoked when an
object of its associated class is created. It is called constructor because it constructs the values of
data members of its class.
Eg : Program
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
PARAMETERIZED CONSTRUCTORS :
The constructors that take arguments are called Parameterized constructors.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Eg : Program
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Output:
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
The constructor can accept a reference to its class as a parameter and the constructor is called
copy constructor.
Eg : Program
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
OUTPUT:
COPY CONSTRUCTOR :
A copy constructor takes a reference to an object of the same class as itself as an
argument.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
OUTPUT :
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Here, the value of real is 5.0 and imag takes the value 0.0
Here, real takes the value 2.0 to real and 3.0 to imag.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
OUTPUT :
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
The parameters for the program are given at run time and the inputs can be:
Amount, period and interest in decimal form
DYNAMIC CONSTRUCTOR:
Allocation of memory to objects at the time of their construction is called
dynamic construction of objects. The memory is allocated with the help of new operator.
Eg : Program
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
OUTPUT :
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
DESTRUCTORS :
When we define a variable in C++, it continues to be in effect until its scope is over. If a
variable is defined as global variable, it remains in effect throughout the execution of the
program. If a variable is defined as a local variable, it remains in effect till the function exits.
Destructors are opposites to constructors. They come into effect when objects goes out of scope.
Like constructors, they are automatically applied and calling them explicitly is also possible. The
main use of destructor is to return the memory that is dynamically allocated. They also providing
terminating effects.
A destructor is a special member function of a class that is executed whenever an object
of it's class goes out of scope or whenever the delete expression is applied to a pointer to the
object of that class.
A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither
return a value nor can it take any parameters. Destructor can be very useful for releasing
resources before coming out of the program like closing files, releasing memories etc.
#include <iostream>
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(); // This is the constructor declaration
~Line(); // This is the destructor: declaration
private:
double length;
};
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
return 0;
}
When the above code is compiled and executed, it produces the following result:
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time applications
Neural networks and parallel processing
Object oriented systems
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Iterators and Containers
2. SKILLS ADDRESSED:
Learning
4. OUTCOMES:
i. Explain Iterators.
ii. Explain Containers.
5. LINK SHEET:
i. What Iterators
ii. Illustrate Containers
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Container classes are the solution to a specific kind of code reuse problem. They are building
blocks used to create object-oriented programs – they make the internals of a program much
easier to construct.
A container class describes an object that holds other objects. Container classes are so important
that they were considered fundamental to early object-oriented languages. In Smalltalk, for
example, programmers think of the language as the program translator together with the class
library, and a critical part of that library is the container classes. So it became natural that C++
compiler vendors also include a container class library. You‟ll note that the vector was so useful
that it was introduced in its simplest form very early in this book.
Like many other early C++ libraries, early container class libraries followed Smalltalk‟s object-
based hierarchy, which worked well for Smalltalk, but turned out to be awkward and difficult to
use in C++. Another approach was required.
This chapter attempts to slowly work you into the concepts of the C++ Standard Template
Library (STL), which is a powerful library of containers (as well as algorithms, but these are
covered in the following chapter). In the past, I have taught that there is a relatively small subset
of elements and ideas that you need to understand in order to get much of the usefulness from the
STL. Although this can be true it turns out that understanding the STL more deeply is important
to gain the full power of the library. This chapter and the next probe into the STL containers and
algorithms.
If you don‟t know how many objects you‟re going to need to solve a particular problem, or how
long they will last, you also don‟t know how to store those objects. How can you know how
much space to create? You can‟t, since that information isn‟t known until run time.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
The solution to most problems in object-oriented design seems flippant: you create another type
of object. For the storage problem, the new type of object holds other objects, or pointers to
objects. Of course, you can do the same thing with an array, but there‟s more. This new type of
object, which is typically referred to in C++ as a container (also called a collection in some
languages), will expand itself whenever necessary to accommodate everything you place inside
it. So you don‟t need to know how many objects you‟re going to hold in a collection. You just
create a collection object and let it take care of the details.
Fortunately, a good OOP language comes with a set of containers as part of the package. In C++,
it‟s the Standard Template Library (STL). In some libraries, a generic container is considered
good enough for all needs, and in others (C++ in particular) the library has different types of
containers for different needs: a vector for consistent access to all elements, and a linked list for
consistent insertion at all elements, for example, so you can choose the particular type that fits
your needs. These may include sets, queues, hash tables, trees, stacks, etc.
All containers have some way to put things in and get things out. The way that you place
something into a container is fairly obvious. There‟s a function called “push” or “add” or a
similar name. Fetching things out of a container is not always as apparent; if it‟s an array-like
entity such as a vector, you might be able to use an indexing operator or function. But in many
situations this doesn‟t make sense. Also, a single-selection function is restrictive. What if you
want to manipulate or compare a group of elements in the container?
The solution is an iterator, which is an object whose job is to select the elements within a
container and present them to the user of the iterator. As a class, it also provides a level of
abstraction. This abstraction can be used to separate the details of the container from the code
that‟s accessing that container. The container, via the iterator, is abstracted to be simply a
sequence. The iterator allows you to traverse that sequence without worrying about the
underlying structure – that is, whether it‟s a vector, a linked list, a stack or something else. This
gives you the flexibility to easily change the underlying data structure without disturbing the
code in your program.
From the design standpoint, all you really want is a sequence that can be manipulated to solve
your problem. If a single type of sequence satisfied all of your needs, there‟d be no reason to
have different kinds. There are two reasons that you need a choice of containers. First, containers
provide different types of interfaces and external behavior. A stack has a different interface and
behavior than that of a queue, which is different than that of a set or a list. One of these might
provide a more flexible solution to your problem than the other. Second, different containers
have different efficiencies for certain operations. The best example is a vector and a list. Both are
simple sequences that can have identical interfaces and external behaviors. But certain operations
can have radically different costs. Randomly accessing elements in a vector is a constant-time
operation; it takes the same amount of time regardless of the element you select. However, in a
linked list it is expensive to move through the list to randomly select an element, and it takes
longer to find an element if it is further down the list. On the other hand, if you want to insert an
element in the middle of a sequence, it‟s much cheaper in a list than in a vector. These and other
operations have different efficiencies depending upon the underlying structure of the sequence.
In the design phase, you might start with a list and, when tuning for performance, change to a
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
vector. Because of the abstraction via iterators, you can change from one to the other with
minimal impact on your code.
In the end, remember that a container is only a storage cabinet to put objects in. If that cabinet
solves all of your needs, it doesn‟t really matter how it is implemented (a basic concept with
most types of objects). If you‟re working in a programming environment that has built-in
overhead due to other factors, then the cost difference between a vector and a linked list might
not matter. You might need only one type of sequence. You can even imagine the “perfect”
container abstraction, which can automatically change its underlying implementation according
to the way it is used.
You will notice that this chapter does not contain exhaustive documentation describing each of
the member functions in each STL container. Although I describe the member functions that I
use, I‟ve left the full descriptions to others: there are at least two very good on-line sources of
STL documentation in HTML format that you can keep resident on your computer and view with
a Web browser whenever you need to look something up. The first is the Dinkumware library
(which covers the entire Standard C and C++ library) mentioned at the beginning of this book
section (page XXX). The second is the freely-downloadable SGI STL and documentation, freely
downloadable at http://www.sgi.com/Technology/STL/. These should provide complete
references when you‟re writing code. In addition, the STL books listed in Appendix XX will
provide you with other resources.
The C++ STL[16] is a powerful library intended to satisfy the vast bulk of your needs for
containers and algorithms, but in a completely portable fashion. This means that not only are
your programs easier to port to other platforms, but that your knowledge itself does not depend
on the libraries provided by a particular compiler vendor (and the STL is likely to be more tested
and scrutinized than a particular vendor‟s library). Thus, it will benefit you greatly to look first to
the STL for containers and algorithms, before looking at vendor-specific solutions.
A fundamental principle of software design is that all problems can be simplified by introducing
an extra level of indirection. This simplicity is achieved in the STL using iterators to perform
operations on a data structure while knowing as little as possible about that structure, thus
producing data structure independence. With the STL, this means that any operation that can be
performed on an array of objects can also be performed on an STL container of objects and vice
versa. The STL containers work just as easily with built-in types as they do with user-defined
types. If you learn the library, it will work on everything.
The drawback to this independence is that you‟ll have to take a little time at first getting used to
the way things are done in the STL. However, the STL uses a consistent pattern, so once you fit
your mind around it, it doesn‟t change from one STL tool to another.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Consider an example using the STL set class. A set will allow only one of each object value to
be inserted into itself. Here is a simple set created to work with ints by providing int as the
template argument toset:
//: C04:Intset.cpp
// Simple use of STL set
#include <set>
#include <iostream>
using namespace std;
int main() {
set<int> intset;
for(int i = 0; i < 25; i++)
for(int j = 0; j < 10; j++)
// Try to insert multiple copies:
intset.insert(j);
// Print to output:
copy(intset.begin(), intset.end(),
ostream_iterator<int>(cout, "\n"));
} ///:~
The insert( ) member does all the work: it tries putting the new element in and rejects it if it‟s
already there. Very often the activities involved in using a set are simply insertion and a test to
see whether it contains the element. You can also form a union, intersection, or difference of
sets, and test to see if one set is a subset of another.
In this example, the values 0 - 9 are inserted into the set 25 times, and the results are printed out
to show that only one of each of the values is actually retained in the set.
The copy( ) function is actually the instantiation of an STL template function, of which there are
many. These template functions are generally referred to as “the STL Algorithms” and will be
the subject of the following chapter. However, several of the algorithms are so useful that they
will be introduced in this chapter. Here, copy( ) shows the use of iterators. The set member
functions begin( ) and end( )produce iterators as their return values. These are used by copy( ) as
beginning and ending points for its operation, which is simply to move between the boundaries
established by the iterators and copy the elements to the third argument, which is also an iterator,
but in this case, a special type created for iostreams. This places int objects on cout and
separates them with a newline.
Because of its genericity, copy( ) is certainly not restricted to printing on a stream. It can be used
in virtually any situation: it needs only three iterators to talk to. All of the algorithms follow the
form ofcopy( ) and simply manipulate iterators (the use of iterators is the “extra level of
indirection”).
Now consider taking the form of Intset.cpp and reshaping it to display a list of the words used in
a document. The solution becomes remarkably simple.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
//: C04:WordSet.cpp
#include "../require.h"
#include <string>
#include <fstream>
#include <iostream>
#include <set>
using namespace std;
The only substantive difference here is that string is used instead of int. The words are pulled
from a file, but everything else is the same as in Intset.cpp. The operator>> returns a
whitespace-separated group of characters each time it is called, until there‟s no more input from
the file. So it approximately breaks an input stream up into words. Each string is placed in
the set using insert( ), and the copy( )function is used to display the results. Because of the
way set is implemented (as a tree), the words are automatically sorted.
Consider how much effort it would be to accomplish the same task in C, or even in C++ without
the STL.
The primary idea in the STL is the container (also known as a collection), which is just what it
sounds like: a place to hold things. You need containers because objects are constantly marching
in and out of your program and there must be someplace to put them while they‟re around. You
can‟t make named local objects because in a typical program you don‟t know how many, or what
type, or the lifetime of the objects you‟re working with. So you need a container that will expand
whenever necessary to fill your needs.
All the containers in the STL hold objects and expand themselves. In addition, they hold your
objects in a particular way. The difference between one container and another is the way the
objects are held and how the sequence is created. Let‟s start by looking at the simplest
containers.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
A vector is a linear sequence that allows rapid random access to its elements. However, it‟s
expensive to insert an element in the middle of the sequence, and is also expensive when it
allocates additional storage. A deque is also a linear sequence, and it allows random access
that‟s nearly as fast as vector, but it‟s significantly faster when it needs to allocate new storage,
and you can easily add new elements at either end (vector only allows the addition of elements
at its tail). A list the third type of basic linear sequence, but it‟s expensive to move around
randomly and cheap to insert an element in the middle. Thuslist, deque and vector are very
similar in their basic functionality (they all hold linear sequences), but different in the cost of
their activities. So for your first shot at a program, you could choose any one, and only
experiment with the others if you‟re tuning for efficiency.
Many of the problems you set out to solve will only require a simple linear sequence like
a vector, deque or list. All three have a member function push_back( ) which you use to insert a
new element at the back of the sequence (deque and list also have push_front( )).
But now how do you retrieve those elements? With a vector or deque, it is possible to use the
indexing operator[ ], but that doesn‟t work with list. Since it would be nicest to learn a single
interface, we‟ll often use the one defined for all STL containers: the iterator.
An iterator is a class that abstracts the process of moving through a sequence. It allows you to
select each element of a sequence without knowing the underlying structure of that sequence.
This is a powerful feature, partly because it allows us to learn a single interface that works with
all containers, and partly because it allows containers to be used interchangeably.
One more observation and you‟re ready for another example. Even though the STL containers
hold objects by value (that is, they hold the whole object inside themselves) that‟s probably not
the way you‟ll generally use them if you‟re doing object-oriented programming. That‟s because
in OOP, most of the time you‟ll create objects on the heap with new and then upcast the address
to the base-class type, later manipulating it as a pointer to the base class. The beauty of this is
that you don‟t worry about the specific type of object you‟re dealing with, which greatly reduces
the complexity of your code and increases the maintainability of your program. This process of
upcasting is what you try to do in OOP with polymorphism, so you‟ll usually be using containers
of pointers.
Consider the classic “shape” example where shapes have a set of common operations, and you
have different types of shapes. Here‟s what it looks like using the STL vector to hold pointers to
various types of Shape created on the heap:
//: C04:Stlshape.cpp
// Simple shapes w/ STL
#include <vector>
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() = 0;
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
int main() {
Container shapes;
shapes.push_back(new Circle);
shapes.push_back(new Square);
shapes.push_back(new Triangle);
for(Iter i = shapes.begin();
i != shapes.end(); i++)
(*i)->draw();
// ... Sometime later:
for(Iter j = shapes.begin();
j != shapes.end(); j++)
delete *j;
} ///:~
The creation of Shape, Circle, Square and Triangle should be fairly familiar. Shape is a pure
abstract base class (because of the pure specifier =0) that defines the interface for all types
of shapes. The derived classes redefine the virtual function draw( ) to perform the appropriate
operation. Now we‟d like to create a bunch of different types of Shape object, but where to put
them? In an STL container, of course. For convenience, this typedef:
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
uses that alias to create another one, for vector<Shape*>::iterator. Notice that
the container type name must be used to produce the appropriate iterator, which is defined as a
nested class. Although there are different types of iterators (forward, bidirectional, reverse, etc.,
which will be explained later) they all have the same basic interface: you can increment them
with ++, you can dereference them to produce the object they‟re currently selecting, and you can
test them to see if they‟re at the end of the sequence. That‟s what you‟ll want to do 90% of the
time. And that‟s what is done in the above example: after creating a container, it‟s filled with
different types of Shape*. Notice that the upcast happens as
the Circle, Square or Rectangle pointer is added to the shapes container, which doesn‟t know
about those specific types but instead holds only Shape*. So as soon as the pointer is added to
the container it loses its specific identity and becomes an anonymous Shape*. This is exactly
what we want: toss them all in and let polymorphism sort it out.
The first for loop creates an iterator and sets it to the beginning of the sequence by calling
the begin( ) member function for the container. All containers have begin( ) and end( ) member
functions that produce an iterator selecting, respectively, the beginning of the sequence and one
past the end of the sequence. To test to see if you‟re done, you make sure you‟re != to the iterator
produced by end( ). Not <or <=. The only test that works is !=. So it‟s very common to write a
loop like:
What do you do with the iterator to produce the element it‟s selecting? You dereference it using
(what else) the „*‟ (which is actually an overloaded operator). What you get back is whatever the
container is holding. This container holds Shape*, so that‟s what *i produces. If you want to
send a message to the Shape, you must select that message with ->, so you write the line:
(*i)->draw();
This calls the draw( ) function for the Shape* the iterator is currently selecting. The parentheses
are ugly but necessary to produce the proper order of evaluation. As an alternative, operator-> is
defined so that you can say:
i->draw();
As they are destroyed or in other cases where the pointers are removed, the STL containers do
not call delete for the pointers they contain. If you create an object on the heap with new and
place its pointer in a container, the container can‟t tell if that pointer is also placed inside another
container. So the STL just doesn‟t do anything about it, and puts the responsibility squarely in
your lap. The last lines in the program move through and delete every object in the container so
proper cleanup occurs.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
It‟s very interesting to note that you can change the type of container that this program uses with
two lines. Instead of including <vector>, you include <list>, and in the first typedef you say:
instead of using a vector. Everything else goes untouched. This is possible not because of an
interface enforced by inheritance (there isn‟t any inheritance in the STL, which comes as a
surprise when you first see it), but because the interface is enforced by a convention adopted by
the designers of the STL, precisely so you could perform this kind of interchange. Now you can
easily switch between vector and listand see which one works fastest for your needs.
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time applications
Neural networks and parallel processing
Object oriented systems
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Templates - Function templates, class templates
2. SKILLS ADDRESSED:
Listening
Understanding
Analysis and implementation
4. OUTCOMES:
i. Explain about Templates.
ii. Explain about Function Templates.
iii. Explain generic sorting
iv. Explain non-generic parameters and arguments
v. Explain template argument deduction.
vi. Define class template outside the class.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
5. LINK SHEET:
i. What is a Template?
ii. What is function template?
iii. What are the drawbacks of using Macros?
iv. Explain about single argument function template.
v. What is instantiation?
vi. What is Generic sorting?
vii. Explain function templates with multiple arguments ad 2 arguments.
viii. Explain about non-generic parameters and arguments in template function.
ix. Explain template argument deduction
x. What is a class template and define it.
xi. Explain class template with multiple generic datatypes.
xii. Explain class templates using non-type arguments and default arguments.
xiii. What is static data members?
xiv. Explain the friends of class templates
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
// ...
};
Function templates :
Function templates are generic functions, which work for any data type that is
passed to them.
Drawbacks of using macros :
Macros are not visible to the compiler.
Just some mechanical changes are need to be done in the normal function to
make it a function template.
Eg :
If you want to create a function approximate(), which determines whether two values are
within 5% of each other, you can define the following template:
#include <math.h>
template <class T> int approximate (T first, T second)
{
double aptemp=double(first)/double(second);
return int(abs(aptemp-1.0) <= .05);
};
Assuming that you have two values of type float you want to compare. You can use
the approximate function template:
The above example generates the following template function to resolve the call:
int approximate(float,float).
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Include the function template definition (both the .h and .c files) in all files that may
reference the corresponding template functions.
Include the function template declaration (the .h file only) in all files that may reference
the corresponding template functions. However, include the function definition (both
the .h and .c files) in one file only.
Include the declaration of the function templates in a header file and the definition in a
source file that has the same name. When you include the header file in your source, the
compiler automatically generates the template functions.
The following examples use two files to illustrate all three methods:
File stack.h
#ifndef _STACK_TPL_H
#define _STACK_TPL_H
template<class T>
class stack
{
private:
T* v;
T* p;
int sz;
public:
stack( int );
~stack();
void push( T );
};
#endif
File stackdef.h
#include "stack.h"
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
To instantiate a stack of 50 ints, you would declare the following in each source file that requires
it:
stack<int> intStack(50);
For method 1, each source file that uses the template should include
both stack.h and stackdef.h.
For method 2, every source file should include stack.h. However, only one of the files needs to
includestackdef.h.
For method 3, every source file should include stack.h. The compiler automatically generates
the template functions in the TEMPINC PDS. You can use the TEMPINC option to set your
own TEMPINC PDS.
LSEARCH('USR.INCLUDE.+')
For information about include files, and the TEMPINC and LSEARCH options, see the OS/390
C/C++ User's Guide.
FUNCTION TEMPLATE
Is a template used to generate template functions. A function template can be only a
declaration, or it can define the function.
Template function
Is a function generated by a function template.
If you want to create a function approximate(), which determines whether two values are
within 5% of each other, you can define the following template:
#include <math.h>
template <class T> int approximate (T first, T second)
{
double aptemp=double(first)/double(second);
return int(abs(aptemp-1.0) <= .05);
};
Assuming that you have two values of type float you want to compare. You can use
the approximate function template:
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
The above example generates the following template function to resolve the call:
int approximate(float,float)
1. Looks for a function with an exact type match. It does not include template functions,
unless you explicitly declare such functions by using a function declaration. OS/390 C++
performs trivial conversions if they produce an exact type match.
2. Looks for a function template that allows generation of a function with an exact type
match. OS/390 C++ performs trivial conversions if they produce an exact type match.
3. Tries ordinary overloading resolution for functions already present. This does not include
template functions, unless you have explicitly declared such functions by using a function
declaration.
A call to a template function causes an error, and OS/390 C++ does no overloading if the
following conditions are true:
In the case of the approximate() function template, if the two input values are of different
types, overloading resolution does not take place:
float a=3.24;
double b=3.35;
if (approximate(a,b)) // error, different types
{ /* ... */ }
The solution is to force a conversion to one of the available function types by explicitly declaring
the function for the chosen type. To resolve the above example, include the following function
declaration:
This declaration creates a function, approximate() that expects two arguments of type double.
When you callapproximate(a,b), the overloading is resolved by converting variable a to
type double.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
You can generate template functions in all compilation units that contain function template
definitions. Consequently, you may want to group function template definitions into one or two
compilation units.
In some situations, a function template can define a group of functions in which, for one function
type, the function definition would be inappropriate. For instance, consider the following
function template:
The following explicitly defined template function compares two strings and returns a value that
indicates whether more than 5% of the characters differ between the two strings:
#include <string.h>
int approximate(char *first, char *second)
{
if (strcmp(first,second) == 0)
return 1; // strings are identical
double difct=0;
int maxlen=0;
if (strlen(first)>strlen(second))
maxlen=strlen(first);
else maxlen=strlen(second);
for (int i=0; i<=maxlen ; ++i)
if ( first[i] != second[i] ) difct++;
return int((difct / maxlen) <= .05 );
}
Given this definition, the following function call invokes the above explicitly defined function,
and no template function is generated:
double a=3.54;
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
float b=3.5;
approximate(a,b);
approximate(double a, double b)
When you define a template function explicitly within a compilation unit, the compiler uses this
definition in preference to any instantiation from the function template. For example, if one
compilation unit contains the code:
#include <iostream.h>
template <class T> T f(T i) {return i+1;}
void main()
{
cout << f(2) << endl;
}
When compiled and run, the program prints the number 4 to standard output. This indicates that
the compiler uses the explicitly defined function to resolve the call to f().
A function whose name matches a function template's name you have declared, and the
compiler can generate an appropriate template function.
A function whose name matches a function template's name you have called, and the
compiler can generate an appropriate template function.
A function whose name matches a function template's name you have called, and you
have explicitly defined the template function.
You take the address of a template function in such a way that instantiation can occur.
This means that the pointer to function must supply a return type and supply argument
types that can be used to instantiate the template function.
Class Templates
The relationship between a class template and an individual class is like the relationship between
a class and an individual object. An individual class defines how a group of objects can be
constructed, while a class template defines how a group of classes can be generated.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Note the distinction between the terms class template and template class:
Class template
Is a template used to generate template classes. A class template can be only a
declaration, or it can be a definition of the class.
Template class
Is an instance of a class template.
A template definition is identical to any valid class definition that the template might generate,
except for the following:
Types, variables, constants and objects within the class template can be declared with
arguments of user-defined type as well as with explicit types (for example, int or char).
The template-argument-list can include argument-declarations (for
example, int a or char* b), which are generally used to define constant values within the
created class.
A class template can declare a class without defining it by using an elaborated type specifier, for
example:
Using the type specifier reserves the name as a class template name. All template declarations for
a class template must have the same types and number of template arguments. OS/390 C++
allows only one template declaration that contains the class definition.
You can instantiate the class template by declaring a template class. If the template class member
function definitions are not inline, you have to define them. When you instantiate a template
class, its argument list must match the argument list in the class template declaration.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
// .
// .
// .
};
void main ()
{
class key <int, vector<int> >; // instantiate template
}
Any of the techniques that are used to access ordinary class member objects and
functions can access objects and functions of individual template classes. For example, assume
you have this class template:
You must declare a class template before declaring a corresponding template class. A class
template definition can only appear once in any single compilation unit. You must define a class
template before using a template class that requires the size of the class, or refers to members of
the class.
The following example declares the class template key before defining it. The declaration of the
pointer keyiptris valid because the example does not need the size of the class. The declaration
of keyi, however, causes an error.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
// .
// .
// .
};
If you use a template class before defining the corresponding class template, the compiler issues
an error. The compiler considers a class name, with the appearance of a template class name, to
be a template class. In other words, angle brackets are valid in a class name only if that class is a
template class.
The compiler does not compile the definition of a class template until it requires the definition of
a template class. At that point, it compiles the class template definition by using the argument list
of the template class to instantiate the template arguments. The compiler flags any errors in the
class definition at this time. If the compiler never requires the definition of a class template, it
does not compile it. In this case, the compiler will not flag any errors in the definition.
You can only define a class template once within a compilation unit. You cannot declare the
class template name to refer to any other template, class, object, function, value, or type in the
same scope.
A nontype template argument that is provided within a template argument list is an expression
whose value can be determined at compile time. Such arguments must be constant expressions,
addresses of functions, objects with external linkage, or addresses of static class members. You
normally use nontype template arguments to initialize a class or to specify the sizes of class
members.
The resulting values of nontype template arguments within a template argument list form part of
the template class's type. If two template class names have the same template name and if their
arguments have identical values, they are the same class.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
In this example, the template argument size becomes a part of the template class name. It
creates an object of such a template class with both the type arguments of the class and the
values of any additional template arguments.
From this template, you can create an object x and its corresponding template class with
arguments double andsize=200. Use a value as the second template argument:
myfilebuf<double,200> x;
myfilebuf<double,10*20> x;
If the template arguments do not evaluate identically, the objects that are created are of
different types:
The instantiation of y fails because the value 200.0 is of type double, and the template argument
is of type int.
myfilebuf<double, 128> x
myfilebuf<double, 512> y
These two objects belong to separate template classes, and referencing either of these objects
later withmyfilebuf<double> is an error.
A class template does not need to have a type argument if it has nontype arguments. For
example, the following template is a valid class template:
class C<100>;
class C<200>;
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Again, these two declarations refer to distinct classes because the values of their nontype
arguments differ.
You can override the class template definition of a particular template class by providing a class
definition for the type of class required. For example, the following class template creates a class
for each type that it references, but that class may be inappropriate for a particular type:
Using the applicable template class name can define the type for which the template class is
inappropriate. Assuming the inappropriately defined type is stocks, you can redefine the
class portfolio<stocks> as follows:
class portfolio<stocks>
{
double capital;
stocks yield;
// ...
};
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Application for designing
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
STL
2. SKILLS ADDRESSED:
Listening
Understanding
4. OUTCOMES:
Explain Standard Template Library.
Explain the principles in STL.
5. LINK SHEET:
What is a standard template library ?
List the principles of standard template library.
What is generic programming.
Explain about generic software components .
Explain generic algorithms
What is an iterator ?
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Generic programming
o It is a mechanism of designing generic software components like vector, list,
dequeue,..The genetic algorithms work with many variants of different software
components without any change.
Genetic software components (containers)
o They are basically collection of other objects
o Advantages:
Small in number
Generality
Efficient, tested, debugged, and standardized
Portability and reusability
Genetic algorithms
o Advantages:
o Programmers are freed from writing routines
o The algorithm use the best mechanisms to be as efficient as possible
o Genetic algorithms are standardized
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Software components are collection of other objects. Iterators provide efficient methods
to traverse these ocntainers.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// create a vector to store int
vector<int> vec;
int i;
// display the original size of vec
cout << "vector size = " << vec.size() << endl;
// push 5 values into the vector
for(i = 0; i < 5; i++){
vec.push_back(i);
}
// display extended size of vec
cout << "extended vector size = " << vec.size() << endl;
// access 5 values from the vector
for(i = 0; i < 5; i++){
cout << "value of vec [" << i << "] = " << vec[i] << endl;
}
// use iterator to access the values
vector<int>::iterator v = vec.begin();
while( v != vec.end()) {
cout << "value of v = " << *v << endl;
v++;
}
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
return 0;
}
When the above code is compiled and executed, it produces the following result:
vector size = 0
extended vector size = 5
value of vec [0] = 0
value of vec [1] = 1
value of vec [2] = 2
value of vec [3] = 3
value of vec [4] = 4
value of v = 0
value of v = 1
value of v = 2
value of v = 3
value of v = 4
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Iterators
Concepts and modelling
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Inheritance
2. SKILLS ADDRESSED:
Listening
Understanding
Analysis
4. OUTCOMES:
Explain about inheritance.
Define derived classes using a single base class.
5. LINK SHEET:
What is Inheritance ?
List the advantages of using inheritance.
Explain Isa and part of relationship.
Define derived class using a single base class and explain using public,private and
protected access modifier.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Inheritance forms a tree like hierarchical structure. A base class exists in a hierarchical
relationship with its derived classes.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
A base class’s public members are accessible by all functions in the program. A base class’s
private members are accessible only by member functions and friends of the base class.
PROTECTED MEMBERS :
Protected access is an intermediate level of protection between public and private
access. A base class’s protected members may be accessed only by members and friends of the
base class and by members and friends of the derived classes. Derived class members can refer
to public and protected members of the base class simply by using the member names. Protected
breaks encapsulation-a change to protected members of a base class may require modification of
all derived classes.
MULTIPLE INHERITANCE:
#include<iostream.h>
#include<conio.h>
class student
{
protected:
int rno,m1,m2;
public:
void get()
{
cout<<"Enter the Roll no :";
cin>>rno;
cout<<"Enter the two marks :";
cin>>m1>>m2;
}
};
class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
{
cout<<"\nEnter the sports mark :";
cin>>sm;
}
};
class statement:public student,public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal : "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();
}
Output:
90
80
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
MULTILEVEL INHERITANCE:
A class be can derived from a derived class which is known as multilevel
inhertiance.
EG:
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout<<"Base class content.";
}
};
class B : public A
{
};
class C : public B
{
};
int main()
{
C c;
c.display();
return 0;
}
Output
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time systems.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Exceptions
2. SKILLS ADDRESSED:
Listening
Understanding
4. OUTCOMES:
Explain Exception Handling.
5. LINK SHEET:
What is Exception handling ?
Explain traditional error handling.
What is the need for exceptional handling ?
What are the challenges in exception handling ?
Explain the use of throw within and outside a function.
Explain the usage of multiple catch.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
EXCEPTION HANDLING :
Exception handling is a mechanism to handle exceptions. Exceptions are error like
situations. When exception handling is in place, instead of providing normal means of execution
when an exception occurs, we need to provide an alternative path of execution. In case if
exception is not applicable, the program will be terminated.
Traditional error handling :
Three ways :
1. Returning error number
2. Global flag manipulation
3. Abnormal termination
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Try :
The try block is the one which can throw an exception. The code that we want to monitor
for exceptions is placed within the try block.
Catch :
This is the section where the exception is handled.
Eg:
try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Throw :
Eg:
#include <iostream>
#include <exception>
using namespace std;
int main () {
try
{
throw myex;
}
catch (exception& e)
{
cout << e.what() << '\n';
}
return 0;
}
#include <iostream.h>
int testeh(void);
class A {
int i;
public:
A(int j) { i = j; cout << "A ctor: i=" << i << '\n';}
~A() { cout << "A dtor: i=" << i << '\n';}
};
class B {
char c;
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
public:
B(char d) { c = d; cout << "B ctor: c=" << c << '\n'; }
~B() { cout << "B dtor: c=" << c << '\n'; }
};
A globA(1);
B globB('a');
main()
{
int rc = 55;
A a(1001);
try {
cout << "calling testeh\n";
testeh();
}
catch(char c) { cout << "caught char\n"; }
catch(short s) { cout << "caught short s = " << s << '\n'; }
catch(int i) { cout << "caught int i = " << i << '\n'; }
cout << "rc = " << rc << '\n';
return(rc);
}
testeh() throw(int,short)
{
A a(2001);
B b('k');
short k=12;
try {
cout << "testeh running\n";
throw (6);
}
catch(char c) { cout << "testeh caught char\n";}
catch(int j) { cout << "testeh caught int j = " << j << '\n';
try {
cout << "testeh throwing a short\n";
throw(k);
}
catch(char d) { cout << "char d caught\n"; }
}
cout << "this line should not be printed\n";
return(0);
}
A ctor: i=1
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
B ctor: c=a
A ctor: i=1001
calling testeh
A ctor: i=2001
B ctor: c=k
testeh running
testeh caught int j = 6
testeh again throwing a short
B dtor: c=k
A dtor: i=2001
caught short s = 12
rc = 55
A dtor: i=1001
B dtor: c=a
A dtor: i=1
Rethrowing an Exception
If a catch block cannot handle the particular exception it has caught, you can rethrow the
exception. The rethrow expression, throw with no argument, causes the originally thrown object
to be rethrown.
The handler has already caught the exception at the scope in which the rethrow expression
occurs. Consequently, the exception is rethrown to the next dynamically enclosing try block.
Therefore, catch blocks at the scope in which the rethrow expression occurred cannot handle it.
Any catch blocks following the dynamically enclosing try block have an opportunity to catch the
exception.
In the following example, catch(FileIO) catches any object of type FileIO, and any objects
that are public base classes of the FileIO class. The example then checks for those exceptions it
can handle. For any exception it cannot handle, it issues a rethrow expression to rethrow the
exception. This allows another handler in a dynamically enclosing try block to handle the
exception.
#include <iostream.h>
class FileIO
{
public:
int notfound;
int endfile;
FileIO(); // initialize data members
// the following member functions throw an exception
// if an input error occurs
void advance(int x);
void clear();
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
The rethrow expression can be caught by any catch whose argument matches the argument of
the exception originally thrown. Note that in this example, the catch(...) will not catch the
rethrow expression. When the example issues a rethrow expression, it passes control out of the
scope of the function f() into the next dynamically enclosing block.
Catching Exceptions
You can declare a handler to catch many types of exceptions. You declare the allowable
objects that a function can catch in the parentheses that follow the catch keyword (the catch
argument). You can catch objects of the fundamental types, base and derived class objects,
references, and pointers to all of these types. You can also catch const and volatile types.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
You can also use the catch(...) form of the handler to catch all thrown exceptions that
have not been caught by a previous catch block. The ellipsis in the catch argument indicates that
this handler can handle any exception that is thrown.
If an exception is caught by a catch(...) block, there is no direct way to access the object
thrown. Information about an exception caught by catch(...)is very limited.
You can declare an optional variable name if you want to access the thrown object in the
catch block.
A catch block can only catch accessible objects. The object that is caught must have an
accessible copy constructor.
try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}
Exception Specifications
C++ provides a mechanism that limits a given function to throwing only a specified list
of exceptions. An exception specification at the beginning of any function acts as a guarantee to
the function's caller that the function will not directly or indirectly throw any exception not
contained in the exception specification. For example, consider the following function:
The above function explicitly states that it will not throw any exception other
than unknown_word orbad_grammar. The function translate() must handle any exceptions
thrown by functions it might call, unless those exceptions are specified in the exception
specification of translate(). Consider if an exception is thrown by a function called
by translate() and the exception is not handled by translate() or contained in the exception
specification of translate(). Then, OS/390 C/C++ calls unexpected(). The
functionunexpected() is discussed in Special Exception Handling Functions.
There are qualifications to the rule about throwing only a specified list of exceptions. If a
class A is included in the exception specification of a function, the function will also allow
exception objects of any classes that are publicly derived from class A. Also, if a pointer type B*
is included in the exception specification of a function, the function will allow exceptions of type
B* or of pointers to any type publicly derived from B*.
A function with an empty throw() specification guarantees that the function will not
throw any exceptions.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
A function without an exception specification allows any object to be thrown from the function.
The compiler does not prevent an exception specification from defining more valid
exceptions than the set of exceptions the function may actually throw. Such an error is detected
only at run time, and only if the unspecified exception is thrown.
In the following example, NameTooShort is thrown from within a function that explicitly
states that it will only throw NameTooLong. This is a valid function, although at run time,
if NameTooShort is thrown, a call tounexpected() will be made.
If a function with an exception specification calls a subfunction with a less restrictive exception
specification (one that contains more objects than the calling function's exception specification),
any thrown objects from within the subfunction that are not handled by the subfunction, and that
are not part of the outer function's specification list, must be handled within the outer function. If
the outer function fails to handle an exception not in its exception specification, a call
to unexpected() is made.
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Error handling
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Why Object-Oriented Programming in C++
2. SKILLS ADDRESSED:
Learning
4. OUTCOMES:
vii. Explain the various Object Oriented concepts.
viii. Explain the difference between object oriented and procedure oriented concepts.
5. LINK SHEET:
xv. What is Object oriented programming?
xvi. List the Object Oriented concepts
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
INTRODUCTION TO C++:
Difference between Procedure oriented programming and Object oriented programming.
POP OOP
1) Emphasis on non-real item Emphasis on real item
2) Programs are divided into Programs are divided into Objects
functions Data are not sharable
3) Data are sharable Object Oriented Programming
4) Structured Programming Bottom-Up Approach
5) Top-Down Approach
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Tokens
Smallest individual unit in a program. C++ tokens are Keywords, Identifiers, Constants,
Strings, Operators.
Operators in C++
:: Scope Resolution Operator
: :* Member pointer operator
->* Pointer-to-Pointer Member using pointer to object Operator
.* Pointer-to-Pointer Member using object Operator
delete Memory Release Operator
endl Line feed operator
new Memory allocation operator
Setw Memory width operator
Casting operator for C-style casting from any type to any other irrelevant type
reinterpret_cast
const_cast Removing the const nature of a variable while casting.
dynamic_cast casting operator that can be used to safeguard against irrelevant
casting ,used in case of polymorphic classes.
typeid used to find type of an object at run time
throw useful for throwing an exception at the time of an error.
Expressions in C++
Constant Expressions
Integral Expressions
Float Expressions
Pointer Expressions
Relational Expressions
Logical Expressions
Bitwise Expressions
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
OBJECTS :
Objects are the basic run-time entities in an object – oriented system. They represent a
person,place,a bank account or a table of data or item that a program has to handle.When
a program is executed,the objects interact by passing messages to each other.
Eg: Customer and account are two objects. The customer object may send a
message to the account object requesting for bank balance.
CLASSES :
A Class is collection of objects of similar type. Objects are variables of the type class.
Classes are user defined data-types and behave like a built in type of a programming
language.
Eg: Apple, Mango, Orange are members of the class fruits.
Syntax : fruit mango ; Fruits
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
defined as a list of abstract attributes such as size,weight,cost and functions to operate on these
attributes. The attributes are called members and functions as methods or member functions. The
classes use Data abstraction and are called Abstract Data Types(ADT).
Eg: Abstraction example: ATM is a good example of abstraction, we doesn't know what
are all the internal processes that are going when we access it..instead we know only the
inquiries, deposit, withdrawal etc.
The wrapping up of data and functions into a single unit(class) is called Encapsulation.
The data is not accessible to the outside world ,and those functions that are wrapped in the class
can access it. This insulation of program by direct access of program is called data hiding or
Information hiding.
Eg: Ink is the important component in pen but it is hiding by some other material.
you don't "need to know the internal working of the mobile phone to operate" with it.
You have an interface to use the device behaviour without knowing implementation details.
INHERITANCE :
Inheritance is the processs by which the object of one class acquire the properties
of objects of another class.
Eg: class Bird-> class flying bird ->class robin
ABSTRACT CLASSES:
Abstract class is the class with no objects. The abstract classes does not represent any
real-world entity. The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes cannot be used to
instantiate objects and serves only as an interface.
Consider the following example where parent class provides an interface to the base class to
implement a function called getArea():
#include <iostream>
// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
ABSTRACT CLASSES:
Abstract class is the class with no objects. The abstract classes does not represent any
real-world entity. The purpose of an abstract class (often referred to as an ABC) is to provide an
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
appropriate base class from which other classes can inherit. Abstract classes cannot be used to
instantiate objects and serves only as an interface.
Consider the following example where parent class provides an interface to the base class to
implement a function called getArea():
#include <iostream>
// Base class
class Shape
{
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w)
{
width = w;
}
void setHeight(int h)
{
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape
{
public:
int getArea()
{
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea()
{
return (width * height)/2;
}
};
int main(void)
{
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
// Print the area of the object.
cout << "Total Triangle area: " << Tri.getArea() << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
POLYMORPHISM:
Polymorphism is a concept in which the operation may exhibit different behaviour in
different instances.
Eg: addition will sum two numbers in case of numerical operands. In case of
string , it will form a third string by concatenation.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
cout<<"Sum = "<<c<<endl;
}
void sum()
{
c= a+b;
}
};
void main()
{
add x; // x is a object off add
clrscr();
x.read();
x.sum();
x. display();
getch();
}
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time applications
Neural networks and parallel processing
Object oriented systems
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Data types, variables and arrays
2. SKILLS ADDRESSED:
Listening
Understanding
Analysis and implementation
4. OUTCOMES:
i. Explain about data types and variables in java.
ii. Explain about array in java.
5. LINK SHEET:
i. Illustrate data types and variables.
ii. What is an array?
iii. Illustrate the use of array with a sample java program
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
DATA TYPE
Data type specifies the size and type of values that can be stored in an identifier. The Java
language is rich in its data types. Different data types allow you to select the type appropriate to
the needs of the application.
1. Integer
Integer types can hold whole numbers such as 123 and −96. The size of the values that can be
stored depends on the integer type that we choose.
Type Size Range of values that can be stored
9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,755,807
The range of values is calculated as −(2n−1) to (2n−1)−1; where n is the number of bits required.
For example, the byte data type requires 1 byte = 8 bits. Therefore, the range of values that can
be stored in the byte data type is −(28−1) to (28−1)−1
= −27 to (27) -1
= −128 to 127
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
2. Floating Point
Floating point data types are used to represent numbers with a fractional part. Single precision
floating point numbers occupy 4 bytes and Double precision floating point numbers occupy 8
bytes. There are two subtypes:
Type Size Range of values that can be stored
3. Character
It stores character constants in the memory. It assumes a size of 2 bytes, but basically it can hold
only a single character because char stores unicode character sets. It has a minimum value of
‗u0000′ (or 0) and a maximum value of ‗uffff‘ (or 65,535, inclusive).
4. Boolean
Boolean data types are used to store values with two states: true or
false. Java Tokens
A token is the smallest element in a program that is meaningful to the compiler. These tokens
define the structure of the language. The Java token set can be divided into five categories:
Identifiers, Keywords, Literals, Operators, and Separators.
1. Identifiers
Identifiers are names provided by you. These can be assigned to variables, methods, functions,
classes etc. to uniquely identify them to the compiler.
2. Keywords
Keywords are reserved words that have a specific meaning for the compiler. They cannot be used
as identifiers. Java has a rich set of keywords. Some examples are: boolean, char, if, protected,
new, this, try, catch, null, threadsafe etc.
3. Literals
Literals are variables whose values remain constant throughout the program. They are also called
Constants. Literals can be of four types. They are:
a. String Literals
String Literals are always enclosed in double quotes and are implemented using the
java.lang.String class. Enclosing a character string within double quotes will automatically create
a new String object. For example, String s = "this is a string";. String objects are immutable,
which means that once created, their values cannot be changed.
b. Character Literals
These are enclosed in single quotes and contain only one character.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
c. Boolean Literals
They can only have the values true or false. These values do not correspond to 1 or 0 as in C or
C++.
d. Numeric Literals
Numeric Literals can contain integer or floating point values.
4. Operators
An operator is a symbol that operates on one or more operands to produce a result.
They will be discussed in greater detail in the next article.
5. Separators
Separators are symbols that indicate the division and arrangement of groups of code. The
structure and function of code is generally defined by the separators. The separators used in Java
are as follows:
parentheses ( )
Used to define precedence in expressions, to enclose parameters in method definitions,
and enclosing cast types.
braces { }
Used to define a block of code and to hold the values of arrays.
brackets [ ]
Used to declare array types.
semicolon ;
Used to separate statements.
comma ,
Used to separate identifiers in a variable declaration and in the forstatement.
period .
Used to separate package names from classes and subclasses and to separate a variable or
a method from a reference variable.
VARIABLES
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
marked as static since, conceptually, the same number of gears will apply to all instances. The
codestatic int numGears = 6; would create such a static field.
3. Local Variables
A method stores its temporary state in local variables. The syntax for declaring a local variable is
similar to declaring a field (for example, int count = 0;). There is no special keyword designating
a variable as local; that determination comes entirely from the location in which the variable is
declared—between the opening and closing braces of a method. As such, local variables are only
visible to the methods in which they are declared; they are not accessible from the rest of the
class.
4. Parameters
They are the variables that are passed to the methods of a class.
Variable Declaration
Identifiers are the names of variables. They must be composed of only letters, numbers, the
underscore, and the dollar sign ($). They cannot contain white spaces. Identifiers may only begin
with a letter, the underscore, or the dollar sign. A variable cannot begin with a number. All
variable names are case sensitive.
Syntax for variable declaration
datatype1 variable1, datatype2 variable2, … datatypen variablen;
For example:
Initialisation
Variables can be assigned values in the following way: Variablename = value;
For example;
ch='a';
a=0;
ARRAY
An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is fixed. You
have seen an example of arrays already, in the main method of the "Hello World!" application.
This section discusses arrays in greater detail.
Each item in an array is called an element, and each element is accessed by its
numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th
element, for example, would therefore be accessed at index 8.
The following program, ArrayDemo, creates an array of integers, puts some values in the
array, and prints each value to standard output.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
class ArrayDemo {
public static void main(String[] args) {
// declares an array of integers
int[] anArray;
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Arrays are a powerful and useful concept used in programming. Java SE provides methods to
perform some of the most common manipulations related to arrays. For instance,
the ArrayCopyDemo example uses the arraycopy() method of the System class instead of
manually iterating through the elements of the source array and placing each one into the
destination array. This is performed behind the scenes, enabling the developer to use just one line
of code to call the method.
For your convenience, Java SE provides several methods for performing array manipulations
(common tasks, such as copying, sorting and searching arrays) in thejava.util.Arrays class. For
instance, the previous example can be modified to use the CopyOfRange() method of
the java.util.Arrays class, as you can see in theArrayCopyOfDemo example. The difference is
that using the CopyOfRange() method does not require you to create the destination array before
calling the method, because the destination array is returned by the method:
class ArrayCopyOfDemo {
public static void main(String[] args) {
System.out.println(new String(copyTo));
}
}
As you can see, the output from this program is the same (caffein), although it requires fewer
lines of code.
Some other useful operations provided by methods in the java.util.Arrays class, are:
Searching an array for a specific value to get the index at which it is placed
(the binarySearch() method).
Comparing two arrays to determine if they are equal or not (the equals() method).
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Filling an array to place a specific value at each index (the fill() method).
Sorting an array into ascending order. This can be done either sequentially, using
the sort() method, or concurrently, using the parallelSort() method introduced in Java SE
8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array
sorting.
8. TEXT BOOKS :
1. E Balagurusamy,‖Object Oriented Programming with C++ and Java‖.
2. Ira Pohl, ―Object-Oriented Programming Using C++‖, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
RPC
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
operators
2. SKILLS ADDRESSED:
Listening
Understanding
4. OUTCOMES:
Explain different types of operator.
5. LINK SHEET:
List the types of operator and explain it in detail.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators
into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13;
now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
~a = 1100 0011
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Assume Boolean variables A holds true and variable B holds false, then:
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide
which value should be assigned to the variable. The operator is written as:
Value of b is : 30
Value of b is : 20
instanceof Operator:
This operator is used only for object reference variables. The operator checks whether the object
is of a particular type(class type or interface type). instanceof operator is wriiten as:
If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is the example:
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
true
This operator will still return true if the object being compared is the assignment compatible with
the type on the right. Following is one more example:
class Vehicle {}
true
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
8. TEXT BOOKS :
1. E Balagurusamy,‖Object Oriented Programming with C++ and Java‖.
2. Ira Pohl, ―Object-Oriented Programming Using C++‖, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time applications
Neural networks and parallel processing
Object oriented systems
www.BrainKart.com
Click Here for Object Oriented Programming full study material.
1. CONTENT LIST:
Control statements
2. SKILLS ADDRESSED:
Listening
Analysis
4. OUTCOMES:
Explain about control statements.
5. LINK SHEET:
Illustrate control statement
www.BrainKart.com
7. LECTURE NOTES: (40 Minutes)
There may be a situation when we need to execute a block of code several number of times,
and is often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
The while Loop:
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the while
loop will be executed.
Example:
public class Test {
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
value of x : 10
value of x : 11
value of x : 12
www.BrainKart.com
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Syntax:
The syntax of a do...while loop is:
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in
the loop execute again. This process repeats until the Boolean expression is false.
Example:
public class Test {
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
value of x : 10
value of x : 11
value of x : 12
www.BrainKart.com
The for Loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
The syntax of a for loop is:
The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here, as long as
a semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and flow of control jumps to the next statement
past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement can be
left blank, as long as a semicolon appears after the Boolean expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Example:
public class Test {
www.BrainKart.com
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Syntax:
The syntax of enhanced for loop is:
for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block and
its value would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be
an array variable or method call that returns an array.
Example:
public class Test {
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
www.BrainKart.com
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
10,20,30,40,50,
James,Larry,Tom,Lacy,
Syntax:
The syntax of a break is a single statement inside any loop:
break;
Example:
public class Test {
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
www.BrainKart.com
10
20
In a for loop, the continue keyword causes flow of control to immediately jump to the
update statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.
Syntax:
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test {
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
10
20
40
50
www.BrainKart.com
8. TEXT BOOKS :
1. E Balagurusamy,‖Object Oriented Programming with C++ and Java‖.
2. Ira Pohl, ―Object-Oriented Programming Using C++‖, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time systems.
www.BrainKart.com
1. CONTENT LIST:
Classes, objects, methods
2. SKILLS ADDRESSED:
Learning
Remembering
Implementing
4. OUTCOMES:
Describe objects and classes in java.
5. LINK SHEET:
What is an object?
Illustrate methods, objects and classes in java
www.BrainKart.com
6. EVOCATION: (10 Minutes)
OBJECTS
A typical Java program creates many objects, which as you know, interact by invoking methods.
Through these object interactions, a program can carry out various tasks, such as implementing a
GUI, running an animation, or sending and receiving information over a network. Once an object
has completed the work for which it was created, its resources are recycled for use by other
objects.
Here's a small program, called CreateObjectDemo, that creates three objects: one Point object
and two Rectangle objects. You will need all three source files to compile this program.
www.BrainKart.com
// move rectTwo and display its new position
rectTwo.move(40, 72);
System.out.println("X Position of rectTwo: " + rectTwo.origin.x);
System.out.println("Y Position of rectTwo: " + rectTwo.origin.y);
}
}
This program creates, manipulates, and displays information about various objects. Here's
the output:
www.BrainKart.com
cadence = newValue;
}
A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:
MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a
method to set it (mountain bikes have seats that can be moved up and down as the terrain
demands).
www.BrainKart.com
8.TEXT BOOKS :
1. E Balagurusamy,‖Object Oriented Programming with C++ and Java‖.
2. Ira Pohl, ―Object-Oriented Programming Using C++‖, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
RPC
www.BrainKart.com
1. CONTENT LIST:
Inheritance
2. SKILLS ADDRESSED:
Learning
Implementing
4. OUTCOMES:
Describe inheritance.
Explain the types of inheritance
5.LINK SHEET:
What is Inheritance?
Illustrate the types of inheritance
www.BrainKart.com
6.EVOCATION: (10 Minutes)
When we talk about inheritance, the most commonly used keyword would
be extends andimplements. These words would determine whether one object IS-A type of
another. By using these keywords we can make one object acquire the properties of another
object.
IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword
is used to achieve inheritance.
public class Animal{
}
Now, based on the above example, In Object Oriented terms, the following are true:
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes.
www.BrainKart.com
Now, if we consider the IS-A relationship, we can say:
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
Example:
public class Dog extends Mammal{
true
true
true
Since we have a good understanding of the extends keyword let us look into how
the implementskeyword is used to get the IS-A relationship.
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be
extended by the classes.
Example:
public interface Animal {}
www.BrainKart.com
The instanceof Keyword:
Let us use the instanceof operator to check determine whether Mammal is actually an Animal,
and dog is actually an Animal
interface Animal{}
true
true
true
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HAS-
Acertain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets us look into an example:
In Object-Oriented feature, the users do not need to bother about which object is doing the real
work. To achieve this, the Van class hides the implementation details from the users of the Van
class. So basically what happens is the users would ask the Van class to do a certain action and
the Van class will either do the work by itself or ask another class to perform the action.
www.BrainKart.com
A very important fact to remember is that Java only supports only single inheritance. This means
that a class cannot extend more than one class. Therefore following is illegal:
However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance.
8. TEXT BOOKS :
1. E Balagurusamy,‖Object Oriented Programming with C++ and Java‖.
2. Ira Pohl, ―Object-Oriented Programming Using C++‖, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
RPC
www.BrainKart.com
1. CONTENT LIST:
Packages and Interfaces
2. SKILLS ADDRESSED:
Learning
Analysis
4.OUTCOMES:
Describe packages in java.
Describe interfaces.
5.LINK SHEET:
What is a package?
How to create a package in java?
Illustrate the use of set CLASSPATH system variable in package.
What is a java interface?
www.BrainKart.com
6.EVOCATION: (10 Minutes)
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
Creating a package:
When creating a package, you should choose a name for the package and put
a package statement with that name at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be put into an unnamed package.
www.BrainKart.com
Example:
Let us look at an example that creates a package called animals. It is common practice to use
lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Now, put an implementation in the same package animals:
package animals;
www.BrainKart.com
The import Keyword:
If a class wants to use another class in the same package, the package name does not need to be
used. Classes in the same package find each other without any special syntax.
Example:
Here, a class named Boss is added to the payroll package that already contains Employee. The
Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by
the following Boss class.
package payroll;
What happens if Boss is not in the payroll package? The Boss class must then use one of the
following techniques for referring to a class in a different package.
The fully qualified name of the class can be used. For example:
payroll.Employee
The package can be imported using the import keyword and the wild card (*). For example:
import payroll.*;
The class itself can be imported using the import keyword. For example:
import payroll.Employee;
Note: A class file can contain any number of import statements. The import statements must
appear after the package statement and before the class declaration.
The Directory Structure of Packages:
Two major results occur when a class is placed in a package:
The name of the package becomes a part of the name of the class, as we just discussed in the
previous section.
The name of the package must match the directory structure where the corresponding
bytecode resides.
www.BrainKart.com
Here is simple way of managing your files in Java:
Put the source code for a class, interface, enumeration, or annotation type in a text file whose
name is the simple name of the type and whose extension is .java. For example:
// File Name : Car.java
package vehicle;
....\vehicle\Car.java
In general, a company uses its reversed Internet domain name for its package names. Example: A
company's Internet domain name is apple.com, then all its package names would start with
com.apple. Each component of the package name corresponds to a subdirectory.
Example: The company had a com.apple.computers package that contained a Dell.java source
file, it would be contained in a series of subdirectories like this:
....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class, interface
and enumeration defined in it. The base name of the output file is the name of the type, and its
extension is.class
For example:
package com.apple.computers;
public class Dell{
}
class Ups{
www.BrainKart.com
Now, compile this file as follows using -d option:
$javac -d . Dell.java
.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows:
import com.apple.computers.*;
Like the .java source files, the compiled .class files should be in a series of directories that reflect
the package name. However, the path to the .class files does not have to be the same as the path
to the .java source files. You can arrange your source and class directories separately, as:
<path-one>\sources\com\apple\computers\Dell.java
<path-two>\classes\com\apple\computers\Dell.class
By doing this, it is possible to give the classes directory to other programmers without revealing
your sources. You also need to manage source and class files in this manner so that the compiler
and the Java Virtual Machine (JVM) can find all the types your program uses.
The full path to the classes directory, <path-two>\classes, is called the class path, and is set with
the CLASSPATH system variable. Both the compiler and the JVM construct the path to your
.class files by adding the package name to the class path.
Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the
compiler and JVM will look for .class files in <path-two>\classes\com\apple\compters.
A class path may include several paths. Multiple paths should be separated by a semicolon
(Windows) or colon (Unix). By default, the compiler and the JVM search the current directory
and the JAR file containing the Java platform classes so that these directories are automatically
in the class path.
www.BrainKart.com
In UNIX -> % unset CLASSPATH; export CLASSPATH
INTERFACE
An interface is not a class. Writing an interface is similar to writing a class, but they are
two different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface
need to be defined in the class.
An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
The bytecode of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
www.BrainKart.com
Declaring Interfaces:
An interface is implicitly abstract. You do not need to use the abstract keyword when
declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
Example:
/* File name : Animal.java */
interface Animal {
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
www.BrainKart.com
public class MammalInt implements Animal{
Mammal eats
Mammal travels
When overriding methods defined in interfaces there are several rules to be followed:
Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.
The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
An implementation class itself can be abstract and if so interface methods need not be
implemented.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a class can extend another
class.
www.BrainKart.com
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
RPC
www.BrainKart.com
1. CONTENT LIST:
Exception handling
2. SKILLS ADDRESSED:
Learning
Understanding
Analysis
4. OUTCOMES:
Describe exception handling.
5. LINK SHEET:
What is exception handling?
www.BrainKart.com
6. EVOCATION: (10 Minutes)
A network connection has been lost in the middle of communications or the JVM has
run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three
categories of exceptions:
www.BrainKart.com
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in
case of severe failures, which are not handled by the java programs. Errors are generated to
indicate errors generated by the runtime environment. Example : JVM is out of Memory.
Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
Here is a list of most common checked and unchecked Java's Built-in Exceptions.
Exceptions Methods:
Following is the list of important medthods available in the Throwable class.
www.BrainKart.com
public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at
5
index 0 represents the top of the call stack, and the last element in the array
represents the method at the bottom of the call stack.
public Throwable fillInStackTrace()
6 Fills the stack trace of this Throwable object with the current stack trace, adding
to any previous information in the stack trace.
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch block
is referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If
the type of exception that occurred is listed in a catch block, the exception is passed to the catch
block much as an argument is passed into a method parameter.
Example:
The following is an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.
www.BrainKart.com
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
Multiple catch Blocks:
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of them
after a single try. If an exception occurs in the protected code, the exception is thrown to the first
catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets
caught there. If not, the exception passes down to the second catch statement. This continues
until the exception either is caught or falls through all catches, in which case the current method
stops execution and the exception is thrown down to the previous method on the call stack.
Example:
Here is code segment showing how to use multiple try/catch statements.
try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}
www.BrainKart.com
The throws/throw Keywords:
If a method does not handle a checked exception, the method must declare it using
the throwskeyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught,
by using the throw keyword. Try to understand the different in throws and throw keywords.
The following method declares that it throws a RemoteException:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions are
declared in a list separated by commas. For example, the following method declares that it
throws a RemoteException and an InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
The finally Keyword
The finally keyword is used to create a block of code that follows a try block. A finally block of
code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no
matter what happens in the protected code.
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
//Protected code
www.BrainKart.com
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Example:
public class ExcepTest{
It is not compulsory to have finally clauses when ever a try/catch block is present.
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
www.BrainKart.com
Declaring you own Exception:
You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes:
If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to extend the RuntimeException class.
You just need to extend the Exception class to create your own Exception class. These are
considered to be checked exceptions. The following InsufficientFundsException class is a user-
defined exception that extends the Exception class, making it a checked exception. An exception
class is like any other class, containing useful fields and methods.
Example:
// File Name InsufficientFundsException.java
import java.io.*;
To demonstrate using our user-defined exception, the following CheckingAccount class contains
a withdraw() method that throws an InsufficientFundsException.
www.BrainKart.com
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods
of CheckingAccount.
www.BrainKart.com
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo, this would produce the following result:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
8.TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time applications
Neural networks and parallel processing
Object oriented systems
www.BrainKart.com
1. CONTENT LIST:
Multithreaded programming
2. SKILLS ADDRESSED:
Learning
Understanding
Analysis
4. OUTCOMES:
Describe threads.
Illustrate multithreading
Explain the life cycle of thread
5. LINK SHEET:
What is a thread?
Explain the life-cycle of a thread.
Give the thread priorities.
Create a thread using extends.
www.BrainKart.com
6. EVOCATION: (10 Minutes)
Multithreading enables you to write in a way where multiple activities can proceed concurrently
in the same program.
www.BrainKart.com
Above-mentioned stages are explained here:
New: A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
this state is considered to be executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for
another thread to perform a task.A thread transitions back to the runnable state only when
another thread signals the waiting thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for a specified interval
of time. A thread in this state transitions back to the runnable state when that time interval
expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in
which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated
processor time before lower-priority threads. However, thread priorities cannot guarantee the
order in which threads execute and very much platform dependentant.
As a first step you need to implement a run() method provided by Runnable interface. This
method provides entry point for the thread and you will put you complete business logic inside
this method. Following is simple syntax of run() method:
public void run( )
STEP 2:
At second step you will instantiate a Thread object using the following constructor:
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface
and threadName is the name given to the new thread.
www.BrainKart.com
STEP 3
Once Thread object is created, you can start it by calling start( ) method, which executes a call
to run( ) method. Following is simple syntax of start() method:
void start( );
Example:
Here is an example that creates a new thread and starts it running:
www.BrainKart.com
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Create Thread by Extending Thread Class:
The second way to create a thread is to create a new class that extends Thread class using the
following two simple steps. This approach provides more flexibility in handling multiple threads
created using available methods in Thread class.
STEP 1
You will need to override run( ) method available in Thread class. This method provides entry
point for the thread and you will put you complete business logic inside this method. Following
is simple syntax of run() method:
public void run( )
STEP 2
Once Thread object is created, you can start it by calling start( ) method, which executes a call
to run( ) method. Following is simple syntax of start() method:
void start( );
www.BrainKart.com
Example:
Here is the preceding program rewritten to extend Thread:
www.BrainKart.com
}
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Thread Methods:
Following is the list of important methods available in the Thread class.
www.BrainKart.com
public void interrupt()
7 Interrupts this thread, causing it to continue execution if it was blocked for any
reason.
public final boolean isAlive()
8 Returns true if the thread is alive, which is any time after the thread has
been started but before it runs to completion.
The previous methods are invoked on a particular Thread object. The following methods in the
Thread class are static. Invoking one of the static methods performs the operation on the
currently running thread.
Example:
The following ThreadClassDemo program demonstrates some of these methods of the Thread
class. Consider a class DisplayMessage which implements Runnable:
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{
www.BrainKart.com
System.out.println(message);
}
}
}
Following is the main program which makes use of above defined classes:
www.BrainKart.com
Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
This would produce the following result. You can try this example again and again and you
would get different result every time.
8. TEXT BOOKS :
www.BrainKart.com
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
Real time systems.
1. CONTENT LIST:
Strings
2. SKILLS ADDRESSED:
Learning
Implementing
www.BrainKart.com
3. OBJECTIVE OF THIS LESSON PLAN:
To facilitate students understand about strings in java.
4. OUTCOMES:
Describe strings in java.
5. LINK SHEET:
What are all the string operations that can be done in java?
Illustrate the strings with a sample java program
www.BrainKart.com
7.LECTURE NOTES (45 minutes)
Strings, which are widely used in Java programming, are a sequence of characters. In the
Java programming language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings:
The most direct way to create a string is to write:
Whenever it encounters a string literal in your code, the compiler creates a String object
with its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has eleven constructors that allow you to provide the initial value of
the string using different sources, such as an array of characters.
www.BrainKart.com
hello.
String Length:
Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the number
of characters contained in the string object.
After the following two lines of code have been executed, len equals 17:
String Length is : 17
Concatenating Strings:
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the
concat() method with string literals, as in:
"Hello, world!"
www.BrainKart.com
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
Using String's static format() method allows you to create a formatted string that you can reuse,
as opposed to a one-time print statement. For example, instead of:
String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
RPC
www.BrainKart.com
1. CONTENT LIST:
Input/Output
2. SKILLS ADDRESSED:
Learning
Understanding
Analysis
4. OUTCOMES:
Describe streams.
5. LINK SHEET:
What are the streams that are used in java?
www.BrainKart.com
6. EVOCATION: (10 Minutes)
A stream can be defined as a sequence of data. The InputStream is used to read data from
a source and the OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to Files and networks but this
tutorial covers very basic functionality related to streams and I/O. We would see most commonly
used example one by one:
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many classes related to byte streams but the most frequently used classes are
, FileInputStream andFileOutputStream. Following is an example which makes use of these
two classes to copy an input file into an output file:
import java.io.*;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
www.BrainKart.com
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content:
This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put above code in CopyFile.java file and
do the following:
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as
Java Characterstreams are used to perform input and output for 16-bit unicode. Though there
are many classes related to character streams but the most frequently used classes are
, FileReader and FileWriter.. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here major difference is that FileReader reads two bytes at
a time and FileWriter writes two bytes at a time.
We can re-write above example which makes use of these two classes to copy an input file
(having unicode characters) into an output file:
import java.io.*;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
www.BrainKart.com
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content:
This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put above code in CopyFile.java file and
do the following:
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where user's program can take
input from a keyboard and then produce output on the computer screen. If you are aware if C or
C++ programming languages, then you must be aware of three standard devices STDIN,
STDOUT and STDERR. Similar way Java provides following three standard streams
Standard Input: This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's program and
usually a computer screen is used to standard output stream and represented as System.out.
Standard Error: This is used to output the error data produced by the user's program and
usually a computer screen is used to standard error stream and represented as System.err.
Following is a simple program which creates InputStreamReader to read standard input stream
until the user types a "q":
import java.io.*;
www.BrainKart.com
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This
program continues reading and outputting same character until we press 'q':
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
Reading and Writing Files:
As described earlier, A stream can be defined as a sequence of data. The InputStream is used to
read data from a source and the OutputStream is used for writing data to a destination.
Here is a hierarchy of classes to deal with Input and Output streams.
www.BrainKart.com
The two important streams are FileInputStream and FileOutputStream, which would be
discussed in this tutorial:
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new
and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file.:
Following constructor takes a file object to create an input stream object to read the file. First we
create a file object using File() method as follows:
www.BrainKart.com
public int read(byte[] r) throws IOException{}
4 This method reads r.length bytes from the input stream into an array. Returns the
total number of bytes read. If end of file -1 will be returned.
public int available() throws IOException{}
5 Gives the number of bytes that can be read from this file input stream. Returns
an int.
There are other important input streams available, for more detail you can refer to the following
links:
ByteArrayInputStream
DataInputStream
FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
file:
Following constructor takes a file object to create an output stream object to write the file. First,
we create a file object using File() method as follows:
www.BrainKart.com
There are other important output streams available, for more detail you can refer to the following
links:
ByteArrayOutputStream
DataOutputStream
Example:
Following is the example to demonstrate InputStream and OutputStream:
import java.io.*;
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();
The above code would create file test.txt and would write given numbers in binary format. Same
would be output on the stdout screen.
File Class
FileReader Class
FileWriter Class
www.BrainKart.com
Directories in Java:
A directory is a File which can contains a list of other files and directories. You use File object to
create directories, to list down files available in a directory. For complete detail check a list of all
the methods which you can call on File object and what are related to directories.
Creating Directories:
There are two useful File utility methods, which can be used to create directories:
The mkdir( ) method creates a directory, returning true on success and false on failure.
Failure indicates that the path specified in the File object already exists, or that the directory
cannot be created because the entire path does not exist yet.
The mkdirs() method creates both a directory and all the parents of the directory.
Following example creates "/tmp/user/java/bin" directory:
import java.io.File;
Note: Java automatically takes care of path separators on UNIX and Windows as per
conventions. If you use a forward slash (/) on a Windows version of Java, the path will still
resolve correctly.
Listing Directories:
You can use list( ) method provided by File object to list down all the files and directories
available in a directory as follows:
import java.io.File;
try{
// create new file object
file = new File("/tmp");
www.BrainKart.com
paths = file.list();
8. TEXT BOOKS :
1. E Balagurusamy,”Object Oriented Programming with C++ and Java”.
2. Ira Pohl, “Object-Oriented Programming Using C++”, Pearson Education Asia, 2003.
3. H.M.Deitel, P.J.Deitel, "Java : how to program", Fifth edition, Prentice Hall of India
private limited, 2003
9. APPLICATIONS :
RPC
www.BrainKart.com