Sie sind auf Seite 1von 304

M.Sc.

Information Technology
(DISTANCE MODE)

DCS 115 Object Oriented Programming

I SEMESTER COURSE MATERIAL

Centre for Distance Education


Anna University Chennai Chennai 600 025

Author

Mr. Ahamed Ali


Lecturer Department of Information Technology Velammal Engineering College Chennai 600 066

Reviewer

Dr. Rhymend Utharayaraj


Professor Ramanujan Computing Centre Anna University Chennai Chennai 600 025

Editorial Board

Dr. C. Chellappan
Professor Department of Computer Science and Engineering Anna University Chennai Chennai 600 025

Dr. T.V. Geetha


Professor Department of Computer Science and Engineering Anna University Chennai Chennai 600 025

Dr. H. Peeru Mohamed


Professor Department of Management Studies Anna University Chennai Chennai 600 025

Copyrights Reserved (For Private Circulation only)

ACKNOWLEDGEMENT
I would like to express my sincere thanks to Dr.C.Chellapppan, Professor and Deputy Director, Centre for Distance Education, Anna University, Chennai for providing me theme the opportunity to prepare this course material.

I am deeply Indebted to the course material reviewer Dr.V.Rhymend Uthariaraj Director RCC, Anna University Chennai for giving valuable comments which have resulted in a better presentation of the course material.

I would like to thank Prof. N. Duraipandian, HOD IT, Velammal Engineering College for having suggested writing the course material and for the constant encouragement throughout the preparation of the course material.

I also express my special debt of gratitude to all my colleagues of Velammal Engineering College, family members and friends for their constant encouragement.

I am very much grateful to acknowledge the following sources from where the inputs where drawn to prepare this course material, to meet the requirements of the syllabus H.Schildt, Teach yourself C++, Osborne 2000 E. Balagurusamy Object Oriented Progamming with c++, Tat Mcgraw till 2000 Walter Savitch, Problem Solving with c++, Addison Wesly 2002 (4th Edition) 1995 Rick Mercer, Computing fundamentals with c++, Object Oriented Programming & design, Mac Millan Press IInd edition 1995 Stroustrup, B., The c++ Programming Language Addision-Wesley,1997 (3rd edition) Bruce Eckel, Thinking in c++, 2000 prentice Hall. Jamie Jaworski Java2 Certification guide ,2000, New Riders http:// www. Sun.com Brouce Eckel, Thinking in Java, 2000 prentice Hall E. Balagurusamy, Programming with Java, Tata Mcgraw hill 2000.

Patrick Naughton & Herbert Schildt Java 2: Mcgraw hill, 2000

The Complete Reference, Tata

David Flanagan, Java in a Nutshell, O.Rcilly 1999. Mr. S. AHAMED ALI M.E., Senoir Lecturer, Department Of Information Technology, Velammal Engineering College, Chennai 600 066.

DCS 115 OBJECT ORIENTED PROGRAMMING UNIT I C++ Programming: Introduction to C++ - Tokens, expressions and control structures Functions in C++ - Classes and Objects Constructors Destructors Operator Overloading and Type conversions. UNIT II Inheritance and Polymorphism and Files: Inheritance Multilevel inheritance Multiple inheritance Hierarchical inheritance Hybrid inheritance Virtual base class Abstract class Virtual functions pure virtual functions File stream operations Sequential Input and Output operations Random Access Error handling during file operation. UNIT III Templates and Exception Handling: Templates Function templates class Templates Overloading of Template Functions Member function Templates Exception handling basics Exception handing mechanism Throwing mechanism catching mechanism Rethrowing an exception specifying exceptions. UNIT IV Introduction to JAVA:Overview of Java language Implementing a Java Program Java virtual Machine Operators and expressions Classes, Objects and methods Constructors Overriding methods Final class Finalizer methods Abstract classes and methods Visibility controls Arrays Strings and vectors. UNIT V Interfaces, Packages and Threads: Interface Extending Interface Implementation Interfaces Accessing Interface variables Java API packages creating packages Accessing and using packages Adding and Hiding classes creating threads Extending the Thread class Stopping and Blocking a Thread Life cycle of a thread Thread priority Synchronization. TEXT BOOKS 1. E. Balagurusamy, Object Oriented Programming, 2nd Edition, Tata McGraw Hill Pub. Co., Delhi, 2001. 2. E. Balagurusamy, Programming with Java, A Primer, Tata McGraw Hill Pub. Co., Delhi, 2000. REFERENCES 1. Herbert Schildt, C++ : The Complete Reference, Tata McGraw Hill, 1999. 2. Herbert Schildt, Java 2 : The Complete Reference, Fourth Edition, Tata McGraw Hill, 2001. 3. Kamthane, A.N., Object Oriented Programming with ANSI and Turbo C++, Pearson Education, Delhi, 2003.

DCS 115

OBJECT ORIENTED PROGRAMMING

Page Nos.

CHAPTER 1 - INTRODUCTION TO C++ PROGRAMMING CHAPTER 2 - FUNCTIONS CHAPTER 3 - CLASSES AND OBJECTS IN C++ CHAPTER 4 - OPERATOR OVERLOADING AND TYPE CONVERSIONS CHAPTER 5 - INHERITANCE CHAPTER 6 - POLYMORPHISM CHAPTER 7 - FILES CHAPTER 8 - TEMPLATES CHAPTER 9 - EXCEPTION HANDLING CHAPTER 10 - INTRODUCTION TO JAVA PROGRAMMING CHAPTER11 - OBJECT OREINTED CONCEPTS IN JAVA CHAPTER 12 - ARRAYS AND VECTORS CHAPTER 13 - STRING HANDLING CHAPTER 14 - INTERFACES CHAPTER 15 -PACKAGES CHAPTER 16 - MULTITHREADED PROGRAMMING

1 21 37

65 83 113 123 143 159 175 197 224 235 249 260 273

DCS 116

DATA STRUCTURES Page Nos.

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 1

INTRODUCTION TO C++ PROGRAMMING


Structure of the Unit Basic C++ I/O statements Basic I/O Manipulators C++ Tokens Keywords Identifiers Constants Operators Data Types Built in Data Types User Defined Data Types Derived Data Types Control Structures Expressions Conditional Expressions

1.1. Introduction C++ is an object oriented language. It is an expanded version of C language.C++ was invented by Bjarne Stroustrup in 1979 at Bell laboratories in Murray Hill, New Jersy. C++ was originally called as C with classes , however the name was changed to C++ in 1983. C++ is a superset of C, hence almost all concepts available in C is also available in C++.This chapter discuss about all the fundamental concepts of this programming language. This chapter introduces basic console I/O statements and manipulators. This chapter then discusses all C++ tokens, data types and control structures. This chapter provides the necessary background to understand the C++ concepts presented in the subsequent chapters. 1.2 Learning Objectives To introduce the basic console I/O statements To write simple C++ programs To write programs using I/O manipulators To understand the various C++ tokens To discuss the three categories of data types To understand the various control structures To show how expressions can be used in C++ programs.
1 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

1.3 Basic Console I/O Statements in C++ Since C++ is a superset of C, all elements of the C language are also contained in the C++ language. Therefore, it is possible to write C++ programs that look just like C programs. You can still use functions such as printf( ) and scanf( ), C++ I/O is performed using I/O operators instead of I/O functions. The output operator is <<. To output to the console, we write cout << expression; Where expression can be any valid C++ expression, including another output expression. cout << Hello World .\n; cout << 236.99; The input operator is >>. To input values from keyboard, use cin >> variables; For example: cin>>a>>b. Example 1: The following C++ program makes use of the basic Console I/O statements to read and print two integer variables. #include < iostream.h> int main( ) { // variables declaration int i,j; cout << Enter two integers \n ; // input two integers cin >> i ; cin>>j; // output i then j and newline cout << i= << i cout<< j= << j << \n; return 0; }

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

Output of the Program Enter two integers 10 20 i=10 j=20

NOTES

You can input any items as you like in one input statement. As in C, individual data items must be separated by whitespace characters (spaces, tabs, or newlines). When a string is read, input will stop when the first whitespace character is encountered.
NOTE : A comment in C++ can be given in a same way as we give in C. /* .... */ is a multline comment and // is a single line comment. For Example /* This is a multiline comment and can Span for multilines.This comment is similar to C */ // This is a singleline comment

Have you Understood Questions? 1. Write the two basic C++ I/O statements. 2. How will you write multiple line comment in C++? 1.4 Basic I/O Manipulators C++ supports some I/O manipulators to format the display.The most frequently used manipulators are endl and setw.To use these functions you have to include iomanip.h header file. The end manipulator is similar to the newline character \n.Thus the statement cout<<a<<endl<<b<<c<<,endl; will print the value of a,b and c in newline. The setw manipulator is used to specify the width of the data to be displayed.Note that in C++ characters are left justified and numbers are right justified.Example cout<<setw(5)<<123;willoutput 1 2 3 Here we have set the width as 5; since numbers are right justified the first two columns appear blank. Now consider this example cout<<setw(10)<<Hello,thentheoutputwillbe H E l l o Apart from these manipulators C++ allows us to create our own manipulators.
3 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Have you Understood Questions? 1. The width of an integer variable has to bet set to 5.How will you set it? 2. Write the manipulator that will cause a line break. 1.5 C++ Tokens In C++ every statement is made up of smallest individual elements called tokens. Tokens are the basic lexical elements. Tokens in C++ include the following Keywords Identifiers Constants Operators

1.5.1 Keywords The list given below contains all the C++ keywords. Every keyword will perform a specific operation in C++. Keywords in C++ cannot be redefined by a programmer; further keywords cannot be used as identifier name. and bool compl do export goto namespace or_eq return struct try using xor and_eq break const double extern if new private short switch typedef virtual xor eq asm case const_cast dynamic_cast false inline not protected signed template typeid void auto catch continue else float int not_eq public sizeof this typename volatile bitand char default enum for long operator register static throw union wchar t bitor class delete explicit friend mutable or reinterpret_cast static_cast true unsigned while

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

1.5.2 Identifiers Every named program component in C++ like variables, functions, arrays, classes etc. must have legal identifier (name) .In C++ all variables must be declared before they are used. Furthermore, variables must be used in a manner consistent with their associated type. An identifier is formed with a sequence of letters (including _ ) and digits. The first character must be a letter. Identifiers are case sensitive, i.e., first_name is different from First_name. Examples of valid variable names are myname, jj, name123 Examples of invalid variables 12B Basic pay ABC,1 Invalid variable name since its starts with a number. Invalid variable name since it has a space Invalid variable name since , is a special character

NOTES

1.5.3 Constants Constants refer to values that do not change during the execution of the program. Examples for constants are 1998 25.789 Hello World a 1.5.4 Operators The various operators in C++ and their associatively are listed below in the Table 1.1. The Operators are listed according to their precedence Associativity left to right left to right Right to left Right to left Left to right :: () [], ->, ., typeid, casts, ! (negation), ~ (bit-not) new, delete ++, , - (unary) , * (unary), & (unary), sizeof *, /, % (modulus)
5 Anna University Chennai

Integer constant Floating point constant String constant Character constant

Operator

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left Left to right Left to right

-+ <<, >> <, <=, >, >= = =, != & (bit-and), | (bit-or) ^ (bit-xor) && (logical and) || (logical or) ?: throw
,

Right to left

=, +=, -=, /=, %=, >>=, &=

Table 1.1 Operator Precedence Have you Understood Questions? 1. Write the four basic C++ tokens. 2. How does a constant differ from a variable 1.6 Data Types C++ supports three categories of data types.They are Built in Data types User Defined Data types Derived Data types

1.6.1 Built in Data Types C++ supports the following built in data types. They are Signed integer: The signed integer types are short int (abbreviation short), int and long int (abbreviation long). Optionally the keyword signed can be used in front of these definitions, e.g. signed int. The size of these variables depends on the implementation of the compiler. The only rule for the length of short, int, long is: short<= int<=long, i. e. they may have all the same size. Examples for signed integer variable declarations are listed below. int x,y long int a;
6

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

Unsigned integer: The unsigned integer types are unsigned short int (abbreviation unsigned short), unsigned int and unsigned long int (abbreviation unsigned long). The sizes follow the same rules as for singed integers. Examples for unsigned integer variable declarations are listed below. unsigned short a; unsigned long x;

NOTES

Character type: Character type variables can hold a single character. The character types are char, signed char and unsigned char. Note that a simple char can mean either signed or unsigned, as this is not defined in ANSI C. It depends therefore only on the implementation of the compiler. A variable can be declared as character type as given below. char x

Floating point types: The floating point types are float, double and long double. A float variable has a single precision value. A double or long double variable has at least single precision, but often has double precision (however, this depends on the implementation). The rule for the size of floating point types is: float <= double<=long double. Examples for floating point variable declarations are listed below. double m float f

Boolean type: Standard C++ has an explicit boolean type bool. (C only has an implicit boolean type: 0 = logical false, nonzero = logical true). This type is used to express results of logical operations. The value of the Boolean type is symbolic, either false or true. To ensure compatibility with C and older C++ compiler, the boolean type is automatically converted to/from integer values. In these cases an integer value of 0 indicates false and a non-zero value indicates true. A variable can be declared as boolean type as given below. bool logic

Empty type: The special type void is used for three occasions: defining a function without parameters, defining a function that has no return value and for generic pointers. Example
7 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

void func() The following Table 1.2 with sizes of data types has been generated on a Windows NT and Linux system Data Type Size in Bytes for Windows NT 1 2 4 4 8 8 Table 1.2 Data Types and their Size 1.6.2 User Defined Data Types Structures, Unions and Classes A structure is a collection of one or more variables; the variables may belong to different types, grouped together under a single name for easy handling. A structure in C++ can be declared as struct point { int x; int y; }; The keyword struct introduces a structure declaration, which is a list of declarations enclosed in braces. A struct declaration defines a user defined type. The close brace that terminates the list of members may be followed by a list of variables, just as for any basic type. For example the variables of the struct point can be declared as struct point a,b,c ; The members of the structures are accessed using dot operator. Example a.x=10, b.x=20. If a structure pointer is created then the members are accessed using -> operator. For example a->x=10 ,b->x=20. A union is a user defined data type that may hold (at different times) objects of different types and sizes, with the compiler keeping track of size and alignment requirements. Unions provide a way to manipulate different kinds of data in a Size in Bytes for Linux System 1 2 4 4 8 12

Char Short int Int Float Double long double

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

single area of storage, without embedding any machine-dependent information in the program.The syntax is based on structures: union u1 { int i; float f; char c; } u; The variable u will be large enough to hold the largest of the three types; the specific size is implementation-dependent. In this example the size of the union variable will be 4 bytes (since the float variable occupies 4 bytes). Unions allow only one variable to refer at a time; all union variables cannot be accessed simultaneously. Syntactically, members of a union are accessed as union-name.member or union-pointer->member. Classes are discussed in detail in chapter 3 Enumeration Data Type An enumeration is a set of named integer constants that specify all the allowable set of values a variable of that type may have.The general syntax of enumeration data type is enum enum-name{enumeration values} ; Example enum states{Andhara,Karnataka,Kerala,Tamilnadu} ; enum currency { dollar,euro,rupees} Once the enumeration is created, we can declare variables of that type. Example coin money; states s; Given these declarations the following statements are valid. The statements if(s= =kerala) cout<<Welcome to Gods Own Country; and cin>>money; if(money==rupees) { //do this
9

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

} are perfectly valid. 1.6.3 Derived Data Type Arrays In C++ arrays are handled in the same way as of C. For example the declaration int a[10]; defines an array of size 10, that is, a block of 10 consecutive objects named a[0], a[1], ...,a[9].

The notation a[i] refers to the i-th element of the array. Pointers A pointer is a variable that contains the address of a variable. Pointers in C++ are declared and initialized as in C. Examples int a= 1, b= 2 int *ip; /* ip is a pointer to int */ ip = &a /* ip now points to a*/ b= *ip; /* bis now 1 */ *ip = 0; /* a is now 0 */ From these examples you can see that the declaration and usage of pointer in C and C++ are similar. Pointers are extensively used in C++ for dynamic memory management and to achieve run time polymorphism. Functions Functions provide modular structure to the programming. Functions in C++ were discussed in detail in chapter 2. Have you Understood Questions? 1. 2. 3. 4. Mention the three categories of data types available in C++ How a structure does differ from union? What do you mean by enumeration data type? What is a pointer variable?

Anna University Chennai

10

DCS 115

OBJECT ORIENTED PROGRAMMING

1.7 Control Structures The control-flow of a language specifies the order in which computations are performed. The various control structures supported by C++ is discussed below. If-Else The if-else statement is used for making decisions. The syntax is if (expression) statement1 else statement2 The flow chart for if else is given below.

NOTES

True Expression

False

Statements

Statements

Where the else part is optional. The expression is evaluated; if it is true (that is, if expression has a non-zero value), statement1 is executed. If it is false (expression is zero) and if there is an else part, statement2 is executed instead. Example if(a>b) c=a; else c=b; Flow Chart

True a>b

False

C=a
11

C=b
Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

In this example the value of a will be assigned c if a is greater than b else the value of b will be assigned to c. Else if The syntax for else-if ladder structure is given below if (expression) statement else if (expression) statement else if (expression) statement else if (expression) statement else statement This sequence of if statements is the most general way of writing a multi-way decision. The expressions are evaluated in order; if an expression is true, the statement associated with it is executed, and this terminates the whole chain. The last else part handles the default case where none of the other conditions is satisfied. An example for this construct is given below. if (( a>b) && (a>c)) cout<<A is big; else if ((b>a) && (b>c)) cout<<B is big; else if ((c>a) && (c>b)) cout<<C is big; Switch Statement The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly. The syntax of switch statement is given below. switch (expression) { case const-expr: statements

Anna University Chennai

12

DCS 115

OBJECT ORIENTED PROGRAMMING

case const-expr: statements default: statements } Each case is labeled by one or more integer-valued constants or constant expressions. If a case matches the expression value, execution starts at that case. A default is optional; it gets executed if none of the cases is matched. Cases and the default clause can occur in any order. An example for switch case construct is given below. switch(k) { case 1:
cout<< The value of k is 1 ; break; case 2: cout<< The value of k is 1 ; break; case 3: cout<< The value of k is 1 ; break; default: cout<< The value of k is other than 1,2,3 ; } Here based on the value of k case 1, case 2 or case 3 will be executed .I f the value of k is other than 1, 2 and 3 then default case will be executed. The break statement

NOTES

causes an immediate exit from the switch after the code for one case is done, execution falls through to the next case unless you leave the switch .You can use break statement to explicitly come out of the switch. Looping Statements C++ supports three type of looping statements as C language .They are While Loop DoWhile Loop For Loop

While Loop The Syntax of while loop is while (expression) {


13 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

statements; } the expression is evaluated. If it is non-zero(i.e. if the condition given in the expression is true) , statements is executed and expression is re-evaluated. This cycle continues until expression becomes zero (false). Example i=0; //initial value while(i<100) //condition { cout<<i; i=i+2 //increment } Here in this example the while loop prints all the even numbers between 0 and 100.Note the while loop checks for the condition i<100 every time when the loop iterates. For Loop
The for statement is given below

for (expr1; expr2; expr3) { statements ; } is equivalent to the while statement given in the previous example expr1 while (expr2) { statement expr3 ;
}

Most commonly, expr1 and expr3 are assignments or function calls and expr2 is a relational expression. Any of the three parts can be omitted, although the semicolons must remain. If expr1 or expr3 is omitted, it is simply dropped from the expansion. If the test, expr2, is not present, it is taken as permanently true.
Anna University Chennai 14

DCS 115

OBJECT ORIENTED PROGRAMMING

Example for (i=0 ;i<100 ;i=i+2) cout<<i; This is the for loop version of the previous program for printing even numbers between 0 and 100.Here we can note that in for loop the initilaization,condition and increment statements are kept together in the for statement. Do...while Loop The while and for loops test the termination condition at the top. But the dowhile, tests at the bottom after making each pass through the loop body; the body is always executed at least once. The Syntax of do while statement is do { Statements; }while (expression); The statement is executed, and then expression is evaluated. If it is true, statement is evaluated again, and so on. When the expression becomes false, the loop terminates. do...while loop is essential when we expect the loop to be executed at least once irrespective of the condition. Example i=0; //initialization do { cout<<i; i+=2; //increment }while(i<100); //condition. Break and Continue Statements Sometimes it will require exiting from a loop other than by testing at the top or bottom. The break statement provides an early exit from for, while, and do, just as from switch. A break causes the innermost enclosing loop or switch to be exited immediately. The example given below helps a better understanding about break statement.
15

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

while (i<100) { cout<<ENTER NEGATIVE NUMBER TO EXIT; cin>>a; if(a < 0) break; sum+=a; } In this example the while loop is writtern to execute 100 times but however when the user gives a negative input the break statement causes the loop to make an early exit The continue statement is related to break, it causes the next iteration of the enclosing for, while, or do loop to begin. In the while and do, this means that the test part is executed immediately; in the for, control passes to the increment step. The continue statement applies only to loops, not to switch. Consider the example for (i = 0; i < 100; i++) { cin>>c; if (c <= 0) /* skip the remaining part of the loop */ continue; no_of_positive++; } The continue statement is used here to skip the remaining part of the loop when a negative number is given as input. Have you Understood Questions? 1. Mention the control structures that is used for multi way decisions 2. How does a while loop differs from do while loop 3. In which situations we will use break and continue statements 1.8 Expressions An expression is a combination of operands (both variables and constants), operators arranged as per the syntax of the language.An expression may be an simple expression such as i=i+2 An expression may also use combination of simple expressions such as i=i * 2 + (m +1)/2

Anna University Chennai

16

DCS 115

OBJECT ORIENTED PROGRAMMING

An expression such as a=a+2 in which the variable on the left side is repeated immediately on the right, can be written in the compressed form a+= 2 The operator += is called an assignment operator. Most binary operators (operators like + that have a left and right operand) have a corresponding assignment operator op=, where op is one of + - * / % << >> & ^ | k += m*5 is equivalent to k=k+m*5 Conditional Expressions The statements if (a > b) c = a; else c = b; Assign c the maximum of a and b. The conditional expression, written with the ternary operator ?:, provides an alternate way to write this and similar constructions. In the expression expr1 ? expr2 : expr3 the expression expr1 is evaluated first. If it is non-zero (true), then the expression expr2 is evaluated, and that is the value of the conditional expression. Otherwise expr3 is evaluated, and that is the value. Only one of expr2 and expr3 is evaluated. Thus to set c to the maximum of a and b.

NOTES

17

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Have you Understood Questions? 1. Write the expression in short form a=a+b 2. What is a conditional expression? Summary C++ is an object oriented language. It is an expanded version of C language. C++ I/O is performed using I/O operators instead of I/O functions,C++ uses cin and cout statements for performing I/O operations C++ supports some I/O manipulators to format the display. The most frequently used manipulators are endl and setw. C++ tokens include keywords, operators, identifiers and constants Every named program component in C++ like variables, functions, arrays, classes etc. must have legal identifier (name) Constants refer to values that do not change during the execution of the program. C++ supports three categories of data types, they are built in, user defined and derived data types. A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. A union is a variable that may hold (at different times) objects of different types and sizes, with the compiler keeping track of size and alignment requirements. An enumeration is a set of named integer constants that specify all the allowable set of values a variable of that type may have A pointer is a variable that contains the address of a variable All basic control structures that are present in C language like if..else,while loop,for loop,break and continue statements are also found in C++ all of them perform the same task as in the C language.

Exercises Short Questions 1. Write any two differences between C and C++. 2. cout is an input statement(TRUE/FALSE) 3. A logical AND we have___________ associativity. 4. ___________ operator is used to access a structure variables. 5. Write the significance of void datatype. 6. List out the various user defined datatypes available in C++.

Anna University Chennai

18

DCS 115

OBJECT ORIENTED PROGRAMMING

Long Questions 1. Explain the various data types available in C++ 2. Explain how structures are created and processed in C++ 3. Discuss pointers in detail Programming Exercises 1. Write a program to read a set of integers from the keyboard and determine whether they are ODD or EVEN 2. Write a program to find the sum of the digits of an number 3. Write a program to generate prime numbers in the range 200-999 4. Write a program to count the number of negative numbers in an array Answers to Have you Understood Questions Section 1.3 1. cin and cout 2. /* comment lines Section 1.4 1. setw(5) 2. endl Section 1.5 1. Keywords,Identifiers,Constants,Operators 2. A constant will not change its value during program execution, but a variable does. Section 1.6 1. Built in data type, User defined datatpe and derived data type. 2. A structure is a collection of one or more variables, possibly of different types, grouped together under a single name for convenient handling. 3. An enumeration is a set of named integer constants that specify all the allowable set of values a variable of that type may have. 4. A pointer is a variable that contains the address of a variable. Section 1.7 1. else.. if ladder structure and switch statement.
19

NOTES

*/

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

2. While loop checks the condition first and then executes the loop on the other hand do while loop checks that condition at the last. We can guarantee that a do while loop will at least once but such guarantee cannot be given for while loop. 3. The break statement provides an early exit from for, while, and do, just as from switch.

Section 1.8 1. a+=b. 2. The conditional expression, written with the ternary operator ?:, provides an alternate way to write simple if statement. References 1. Teach yourself C++ Author: H. Schildt Publisher: Osborne 2000 Object Oriented Programming with C++ Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Problem Solving with C++ (4th edition) Author: Walter Savitch Publisher: Addison Wesley 2002 Computing fundamentals with C++, Object oriented programming & design (2nd edition) Author: Rick Mercer Publisher: MacMillan Press 1995

2.

3.

4.

Anna University Chennai

20

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 2 FUNCTIONS
Function Prototypes Functions with Return Values Call by Value Call by Reference 2.1 Introduction Return by Reference Inline Functions Functions with Default Arguments Function Overloading

Functions are one of the most important features of program development. Functions are the basic building blocks of C++. Functions provide modular structure to a program Functions help to divide a larger program into number of smaller units which is the basis of top down approach. Functions also provide programmers a easy and convenient way of designing programs in which complex computations can be built into functions. To re-use the same part of a program, we can define a function, which takes parameters, and returns a result of various types. This chapter introduces you to create and use your own function. This chapter also discusses various important concepts of functions like call by value and reference, Inline functions and function overloading. 2.2 2.3 Learning Objectives To introduce the functions and its advantages To present the concepts of call by value, call by reference and return by reference To discuss about inline functions To show how to use default arguments To present the concept of function overloading Advantages of Functions The advantages of writing functions are Functions provides Reusability Functions give modular structure to a program Writing functions make programming easy
21 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

2.3.1

Function Prototypes

Typical definition or prototype for a function contains The type of the value it returns An identifier for its name and The list of parameters with their types.

The syntax to write a function is. <return type> function name(argument list) { //Body of the Function. } Example 1: The program given below is a makes use of a simple function that takes a integer parameter.

#include <iostream.h> void show(int); // FUNCTION PROTOTYPE void main() { int a; cout<<Enter the value for A; cin>>a show(a); } void show(int x) { cout<<The value passed to function is << x; } Output of the Program Enter the value for A 20 The value passed to function is 20

Anna University Chennai

22

DCS 115

OBJECT ORIENTED PROGRAMMING

This program make use of a function called show( ) with an integer parameter .The function just displays the value of x. Since the function is not returning anything its return type is made void. 2.3.2 Functions with Return Values.

NOTES

As mentioned earlier a function can take parameters and also can return value. Example 2: This function show() used in this program takes two parameters and returns the sum of the parameters #include <iostream.h> int mul(int,int); // FUNCTION PROTOTYPE void main() { int a,b,c; cout<<Enter two values <<endl; cin>>a>>b; c=mul(a,b); cout<<The Product is <<c; } int show(int x,int y) { int z; z=x * y; return z; } Output of the Program Enter two values 5 6 The Product is 30 The variable a,b are known as actual parameters whose values are copied to the dummy variables x and y. The result of the multiplication is stored in z and this value is copied to c. 2.3.3 Call by Value

By default, functions pass arguments by value, which means that when the function is used, the actual values of arguments are copied into the dummy
23 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

parameters. The main effect is that even if the dummy parameters are modified the corresponding parameter will not change the arguments value. Example 3: The following program makes use of call by value concept to swap the values of two variables. #include<iostream.h> void swap(int,int); void main() { int a,b; cout<<enter two values <<endl; cin>>a>>b; swap(a,b); cout<<Values in the main program\n; cout<<a<<\t<<b; } void swap(int x,int y) { int t; t=x; x=y; y=t; cout<<The values after swapping in swap() function \n <<x<<\t<<y; } Output of the Program enter two values 10 20 The values after swapping in swap() function 20 10 Values in the main program 10 20 If suppose you give 5 and 6 as input to a and b which are copied x and y parameters of the swap function(which swaps the value of x and y).The swapped values will not affect the actual parameters a and b thus the cout statement in the main program will print only 5 and 6

Anna University Chennai

24

DCS 115

OBJECT ORIENTED PROGRAMMING

2.3.4

Call by Reference

NOTES

In certain situations, it is more efficient or convenient to be able to modify the argument(s). To do that, the & symbol specifies that the actual parameter and dummy the argument correspond to the same value. This is called passing an argument by reference. Example 4: The following program makes use of call by reference concept to swap the values of two variables. #include <iostream.h> #include <math.h> void swap(int &x,int &y) { int t; t=x; x=y; y=t; cout<<The values after swapping in swap() function \n <<x<<\t<<y; } void main( ) { int a,b; cout<<enter two values <<endl; cin>>a>>b; swap(a,b); cout<<Values in the main program\n; cout<<a<<b; } Output of the Program enter two values 10 20 The values after swapping in swap() function 20 11 Values in the main program 20 11 In this example the variables x and y will act as alias names for a and b thus any change in x and y will be reflected in a and b.

25

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

2.3.5

Return by Reference

A function can also return by reference. Example 5: The program given below illustrates the return by reference concept. #include<iostream.h> #include<iomanip.h> int & check(int & a,int &b) { if(a>b) return a; else return b; } void main( ) { int x,y; cout<<enter two values <<endl; cin>>x>>y; check(x,y)=0; cout<<After executing check function <<endl; cout<<x <<\t<<y; } Output of the Program enter two values 10 20 After executing check function 10 0 This function returns reference to a or b.The function check returns reference to either x or y based on the condition. Thus whatever value is given as input for x and y the function call assigns the value of x to the reference that is returned thus the cout statement displays the value of x twice. Have you Understood Questions? 1. Mention the advantages of writing functions. 2 Give the syntax to write functions. 3 What do you mean by Call by reference? 4 How will you declare a reference variable in C++?
Anna University Chennai 26

DCS 115

OBJECT ORIENTED PROGRAMMING

2.4

Inline Functions

NOTES

Inline functions are like macros. Inline functions will avoid the time complexity that arises due to context switch over head in a function call. A context switch involves locating the function, moving to it, saving the register status, pushing the arguments in the stack and returning to the calling function. All these overheads can be avoided by making a function inline. Inline functions have some restrictions. Function containing looping structure cannot be made inline. Recursive functions cannot be made inline. A function with many lines of coding cannot be made inline.

The disadvantage of in-line functions is that if they are too large and called to often, the program grows larger. For this reason, in general only short functions are declared as in-line functions. A Function can be made inline by prefixing it with the keyword inline. The Syntax for writing Inline function is given below. inline function-prototype { function body } Example 6: This example program makes use of inline function to determine whether the given number is Odd/Even. #include < iostream.h > #include<iomanip.h> inline int even(int x) { if (x %2==0) return 1; else return 0; } int main( ) { int a; cout<<Enter any number<<endl;
27 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

cin>>a; if(even(a)) cout<<EVEN NUMBER; else cout<<ODD NUMBER; } Output of the Program Enter any number 20 EVEN NUMBER Have you Understood Questions? 1. What do you mean by Inline functions? 2. How will you make a function Inline? 2.5 Functions with Default Arguments

In C++ it is possible to call functions without passing all its arguments. This can be made possible by specifying the default arguments. The default arguments will be specified with some default values. Default parameters will be used when there is a missing parameter in the function call. For Example consider the following function declaration. int add(int x , int y=100,int z=200); Here we can note that the default value to the parameter is assigned as an ordinary variable initialization. Thus all the function calls given below are valid. m=add(15); m=add(10,20); m=add(10,20,30) //two argument missing //one argument missing

The following point has to be noted while writing functions with default arguments. A function can take default arguments only as indicated in the previous example (int y =100 is a default parameter) A default parameter is used only when a parameter is missing. Default parameters should be assigned from right to left.

The following function declarations are wrong


Anna University Chennai 28

DCS 115

OBJECT ORIENTED PROGRAMMING

int add(int x=100,int y,int z) //default parameters should be assigned from left to right int add(int x,int y=100,int z) //default parameters should be assigned from left to right Example 7: The following example illustrates the concept of default arguments in a function #include<iostream.h> #include<iomanip.h> void add(int ,int=5,int=7); // DEFAULT VALUE DECLARED void main() { int a,b,c; cout<<enter three values<<endl; cin>>a>>b>>c; cout<<Output with only 2 parameters <<endl; add(a,b); \\ Third parameter missing hence default parameter used cout<<Output with all 3 parameters <<endl; add(a,b,c); } void add( int x, int y, int z) { int t; t=x+y+z; cout<<t; } Output of the Program enter three values 10 20 30 Output with only 2 parameters 37 Output with all 3 parameters 60 Example 8: The following example makes use of the function called simpleinterest with default arguments
29

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

#include<iostream.h> #include<iomanip.h> float simpleinterset(int ,int=5,float=3.5); // DEFAULT VALUE DECLARED

void main() { int p,n; float r,si; cout<<enter the principal amount<<endl; cin>>p; cout<<enter the number of years<<endl; cin>>n; cout<<enter the rate of interest<<endl; cin>>r; cout<<Output with only 2 parameters <<endl; simpleinterest(p,n); \\Third parameter missing hence default parameter used(i.e float=3.5) cout<<Output with all 3 parameters <<endl; simpleinterest (p,n,r); } float simpleinterest( int x, int y, float z) { float ans; ans=(x*y*z)/100; return ans; } Have you Understood Questions? 1. Default parameters are assigned from ________ to ___________ . 2.6 Function Overloading

Function overloading is one of the most important features available in C++ two or more functions can share the same name as long as either the type of their arguments differs or the number of their arguments differs - or both. When two or more functions share the same name, they are said overloaded. Overloaded functions can help reduce the complexity of a program by allowing related operations to be referred to by the same name. To overload a function,
Anna University Chennai 30

DCS 115

OBJECT ORIENTED PROGRAMMING

simply declare and define all required versions. The compiler will automatically select the correct version based upon the number and/or type of the arguments used to call the function. Function overloading provides the compile time polymorphism feature of OOPS. The Following set of functions are overloaded. (i) float volume(int x); float volume(int x,int y); int interest (int p); int interest (float p); float interest (int p,float r); float interest (int p ,float r,int n); float area(int x,float y); float area(float m,float n);

NOTES

(ii)

(iii)

The following sets of functions are not overloaded. (i) float mul(int x,int y) int mul(int x,int y) int convert(int x) float convert (int j);

(ii)

Remember that the return type alone is not sufficient to allow function overloading. If two functions differ only in the type of data they return, the compiler will not always be able to select the proper one to call. Example 9: The following example illustrates the overloading of sum( ) function. #include<iostream.h> #include<iomanip.h> void sum(int,int); void sum(int,int,int); void main() { int a ,b, c ; cout<<Enter three values <<endl; cin>>a>>b>>c; cout<<Calling the function with two parameters<<endl;
31 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

sum(a,b); cout<<Calling the function with three parameters<<endl; sum(a,b,c); } void sum(int x,int y) { int z; z=x+y; cout<<z; } void sum(int x,int y,int z) { int r; r=x+y+z; cout<<r; } Output of the Program enter three values 10 20 30 Calling the function with two parameters 30 Calling the function with three parameters 60 The compiler automatically calls the correct version of the function based upon the type of data used as an argument. Overloaded functions can also differ in the number of arguments. Example 10: This example overloads the function called area. #include<iostream.h> #include<iomanip.h> int area(int side); float area(float radius); int area(int l,int b) void main() { int s; float r,

Anna University Chennai

32

DCS 115

OBJECT ORIENTED PROGRAMMING

int len,bre; cout<<Calculating Area of Square<<endl; cout<<Enter side<<endl; cin>>s; area(s); cout<<Calculating Area of Circle<<endl;. cout<<Enter Radius<<endl; cin>>r; area(r) cout<<Calculating Area of Rectangle<<endl; cout<<Enter Length and Breath<<endl; cin>>len>>bre; area(len,bre); } int area(int side); { cout<<Area of Square is <<side * side; } int area(float radius); { cout<<Area of Circle is <<3.14 * radius*radius; } int area(int l,int b); { cout<<Area of Rectangle is <<l *b; } Have you Understood Questions? 1. What do you mean by function overloading? 2. Is the following set of function overloaded int mul(int m,int n) float mul(int k,int j)

NOTES

33

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Summary 1. Functions provide modular structure to C++ program Functions help to divide a larger program into number of smaller units which is the basis of top down approach. 2. In C++ functions can be called by value, called by reference and can return by reference 3. By default, functions pass arguments by value, which means that when the function is used, the actual values of arguments are copied into the dummy parameters. 4. In call by reference, the & symbol specifies that the actual parameter and dummy the argument correspond to the same value. 5. Inline functions are like macros. Inline functions will avoid the time complexity that arises due to context switch over head in a function call. 6. In C++ it is possible to call functions without passing all its arguments. This can be made possible by specifying the default arguments 7. In C++ two or more functions can share the same name as long as either the type of their arguments differs or the number of their arguments differs - or both. When two or more functions share the same name, they are said overloaded. Exercises Short Questions 1. 2. 3. 4. 5. How does functions reduce complexity of a program What do you mean by function overloading? Explain its advantages. List some advantages of Inline functions In call by reference you use ___________ symbol Inline functions in C++ are similar to _________ of C.

Long Questions 1. Explain the concept of call by value, call by reference and return by reference in detail. 2. Mention the rules associated with passing of default arguments. Give example 3. Explain function overloading with examples. Programming Exercises 1. Create a function to compute simple interest. Supply default arguments to the function 2. Create an overloaded function called myabs() to find absolute value for a number.( absolute value for a number is the positive value of that number)
Anna University Chennai 34

DCS 115

OBJECT ORIENTED PROGRAMMING

Answers to Have you Understood Questions Section 2.3 1. The advantages of writing functions are (1) Functions provides Reusability (2) Functions give modular structure to a program (3) Writing functions make programming easy 2. The syntax to write a function is. <return type> function name(argument list) { //BODY OF THE FUNTION. } 3. In certain situations, it is more effcient or convenient to be able to modify the argument(s). To do that, the & symbol specifies that the actual parameter and dummy the argument correspond to the same value. This is called passing an argument by reference. 4. By referencing the & symbol before the variable declaration. Section 2.4 1. Inline functions are like macros. Inline functions will avoid the time complexity that arises due to context switch over head in a function call. 2. By prefixing the function declaration with inline keyword Section 2.5 1. Right to left Section 2.6 1. In C++ two or more functions can share the same name as long as either the type of their arguments differs or the number of their arguments differs or both. When two or more functions share the same name, they are said overloaded. 2. No

NOTES

35

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

References 1. Teach yourself C++ Author: H. Schildt Publisher: Osborne 2000 Object Oriented Programming with C++ Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Problem Solving with C++ (4th edition) Author: Walter Savitch Publisher: Addison Wesley 2002 Computing fundamentals with C++, Object oriented programming & design (2nd edition) Author: Rick Mercer Publisher: MacMillan Press 1995

2.

3.

4.

Anna University Chennai

36

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 3 CLASSES AND OBJECTS IN C++


Structure of the Unit 3.1 Structures and Classes Copy Constructers Destructors Passing Objects to Functions Returning Objects from Functions Static Data Members Static Member Functions Const Members Functions Friend Functions Friendly Function for Two Classes Classes and Objects Defining the Member Functions Creating Objects Accessing Class Members. Member Functions with Parameters Inline Functions outside Classes. Constructors Constructors That Take Parameters Constructer Overloading

Introduction In the previous chapters, you have followed the modular approach to C++ programming. The power of C++ lies in writing object oriented programs. In object oriented programming the data members and the functions which act upon those data are combined into a single entity called Object. Object provides a systematic way of accessing the data members. This chapter introduces you to write object oriented C++ programs using classes and objects. This chapter then discusses details regarding Constructers and Destructors. Further this chapter introduces static data members, static functions and const functions. At the end this chapter provides necessary details regarding friend functions and classes. 3.2 Learning Objectives To introduce the Classes and Objects To discuss creating member function inside and outside class definitions To present the concept of Constructors, Copy Constructors and Constructor Overloading To present the concept of Destructors
37 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

3.3

To show how to pass and return objects from function To discuss Static data members and Static functions To introduce Constant member functions To introduce Friend functions and Friendly classes Structures and Classes

Classes and structures are syntactically and functionally identical, C++ structures and classes have their own members. These members include variables (including other structures and classes), functions (specific identifiers or overloaded operators) known as methods, constructors and destructors. Classes and Structures are declared with class and struct keywords respectively. Declaration of the members are done within the definition of classes and structures. For example struct book { int pages; char *author; float price }; class book { public: int pages; char *author; float price }; From these declarations you can note that except the public keyword in class, both the declarations are identical. Till this point structures and classes are identical. But class is superior user defined data type that incorporates some additional features than structures. Classes and structures differ in the following aspects. By default, the members of structures are public while that for class is private Structures doesnt provide something like data hiding which is provided by the classes

Classes have the following advantages when compared to structures Classes supports data hiding but Structures doesnt provide data hiding Structures contains only data while class bind both data and member functions
38

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

Since class is specially designed user defined data type in C++ to bind data and code, this book focus only on classes. 3.4 Classes and Objects Class is another user defined data type in C++. A class is the definition of a data structure and the associated operations that can be done on it .Classes in C++ are also called as Abstract Data Type (ADT) .Classes bind the data with its associated code. In C++, a class is declared using the class keyword. The syntax of a class declaration is similar to that of a structure. Its general form is, class class-name { // private functions and variables public: // public functions and variables } object-list; In a class declaration the object-list is optional. Functions and variables declared inside the class declaration are said to be members of the class. By default, all member functions and variables are private to that class. This means that they are accessible only by the members of that class. To declare public class members, the public keyword is used, followed by a colon. All functions and variables declared after the public specifier are accessible both by other members of the class and by any part of the program that contains the class. For Example consider the class given below class number { int a,b; public: void get_ab(); void put_ab() }; This class has two private variable, called a and b, and two public functions get_ab( ) and put_ab( ). Notice that the functions are declared within a class using their prototype forms. The functions that are declared to be part of a class are called member functions.

NOTES

39

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

3.4.1

Defining the Member Functions

Member functions can be declared either inside/outside the class. If the member function is declared inside the class it is said to be inline functions. When the function is declared outside the class it should follow the syntax given below. <return type> classname :: functionname(argument list) { //body of the function. } For example the function get_ab(),put_ab() of the number class can be written as. void number :: get_ab() { cin>>a; cin>>b; } void number :: put_ab() { cout<<a; cout<<b; } 3.4.2 Creating Objects

The declaration of object in C++ is similar to declaration of variables .To create an object, use the class name as type specifier.The Syntax is <class name> objectname . For example, void main( ) { number ob1, ob2;//these are object of type number // ... program code } Remember that an object declaration creates a physical entity of that type. That is, an object occupies memory space, but a type definition does not. 3.4.3 Accessing Class Members.

Once an object of a class has been created, the program can reference its public
Anna University Chennai 40

DCS 115

OBJECT ORIENTED PROGRAMMING

members by using the dot operator in much the same way that structure members are accessed. The syntax for accessing the object is given below. <object name>.functionname(arguments); The statement given below invokes the get_ab() and put_ab() member functions of the number class. ob1.get_ab(); ob1.put_ab(); Example 1: The following code creates a class called number with member functions get_ab(),add() and mul(). #include<iostream.h> class number { private: int a,b; public: void get_ab() { cout<<Enter values for a and b \n; cin>>a; cin>>b; } void add(); void mul(); }; void number :: add() { int c; c=a+b; cout<<THE SUM IS <<c; } void number :: mul() { int d; d=a*b; cout<<THE PRODUCT IS <<d; }

NOTES

41

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

void main() {
number ob1; ob1.get_ab(); ob1.add(); ob1.mul(); }

Output of the Program Enter values for a and b 5 6 THE SUM IS 11 THE PRODUCT IS 30 This program creates a class called number with two private data members and three public member functions. The function get_ab() is an inline function.The functions add() and mul() are written outside the class. The Program creates one object called ob1 through which the member functions are accessed. 3.4.4 Member Functions with Parameters

It is possible to pass one or more arguments to a member function. Simply add the appropriate parameters to the member functions declaration and definition. Then, when you declare an object, specify the arguments. The program given below makes use of parameterized member functions. Example 2: This program is the modified version of example 1,the function get_ab() is modified by adding two parameters. #include<iostream.h> #include<iomanip.h> class number { private: int a,b; public: void get_ab(int x ,int y) // member function with parameters { a=x; b=y;
Anna University Chennai 42

DCS 115

OBJECT ORIENTED PROGRAMMING

} void add() { int c; c=a+b; cout<<THE SUM IS <<c<<endl; } void mul() { int c; c=a*b; cout<<THE PRODUCT IS <<c; } }; void main() { number ob1; int d1,d2; cout<<ENTER TWO DATA<<endl; cin>>d1>>d2; ob1.get_ab(d1,d2); // d1 value is copied to x and d2 value is copied to y ob1.add(); ob1.mul(); } Output of the Program ENTER TWO DATA 10 20 THE SUM IS 30 THE PRODUCT IS 200 3.4.5 Inline Functions outside Classes. A member function that is declared outside can be made inline just by prefixing it with the keyword inline. Example 3: The following is an example for an inline function written outside the class. #include<iostream.h> class point { private: int x,y;
43

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

public: void getpoints(); void putpoints(); }; inline void point :: getpoints() { cout<<Enter 2 points\n cin>>x>>y; } inline void point :: putpoints() { cout<<The points are\n; cout<<x<<\t<<y; } void main() { point p; p.getpoints(); p.putpoints(); } Output of the Program Enter 2 points 10 20 The points are 11 20 Have you Understood Questions? 1. 2. 3. 3.5 What is a class and what is an object? How will you make function written outside the class as inline. Write the syntax to create an object for the class Constructors

Generally every object we create will require some sort of initialization. C++ allows a constructor function to be included in a class declaration. A classs constructor is called each time an object of that class is created. Thus, any initialization to be performed on an object can be done automatically by the constructor function. A constructor function has the following characteristics. It should have the same name as that of the class. It should not have any return type even void however they can take
44

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

arguments. Constructers can take default arguments Constructers can be dynamically initialized. Constructer function cannot be made virtual It should be always declared in the public section of the class.

NOTES

Example 4: The following program makes use of a constructor. #include <iostream.h > class number { int a; public: number( ); //constructor void show( ); }; number::number( ) { cout << In constructor\n; a=100; } void number::show( ) { cout << a; } void main( ) { number ob; // automatic call to constructor ob.show( ); } Output of the Program In constructor 100 In this simple example the constructor is called when the object is created, and the constructor initializes the private variable a to 100 .For a global object, its constructor is called once, when the program first begins execution. For local objects, the constructor is called each time the declaration statement is executed.
45 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

3.5.1 Constructors That Take Parameters It is possible to pass one or more arguments to a constructor function. Simply add the appropriate parameters to the constructor functions declaration and definition. Then, when you declare an object, specify the arguments. Example 5: The following program makes use of a parameterized constructor. # include < iostream.h > class number { int a; public:
number(int x); //constructor

void show( ); }; number::number(int x) { cout << In constructor\n; a=x; } void number::show( ) { cout <<Value of a is << a<<\n; } int main( ) { number ob(4); ob.show( ); return 0; } Output of the Program In constructor Value of a is 4 In this example the object ob is parameterized. The value 4, specified in the parentheses following ob, is the argument that is passed to number( )s parameter x that is used to initialise a. Actually, the syntax is shorthand for this longer form: number ob = number(4);
Anna University Chennai 46

DCS 115

OBJECT ORIENTED PROGRAMMING

Although the previous example has used a constant value, you can pass an objects constructor any valid expression, including variables. 3.5.2 Constructer Overloading

NOTES

Similar to the function overloading concept in C++, you can also overload constructers. Constructer overloading helps us to keep multiple constructers in the class, such that each constructer can perform different methods of initialization. Here is an example for constructer overloading. Example 6: The following program illustrates the constructor overloading concept. The constructor function number () is overloaded with two, one and no parameters # include < iostream.h > class number { int a,b; public: number() { cout<<Default constructer; x=y=0; } number(int x); number(int x,int y); void show( ); }; number::number(int x) { cout << In one parameter constructor\n; a=x; b=0; } number::number(int x,int y) { cout << In two parameter constructor\n; a=x; b=y; }

47

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

void number::show( ) { cout << a<<\n<<b; } int main( ) { number ob(); //invokes default constructer ob.show( ); number ob1(5); //invokes constructer with one parameter ob1.show( ); number ob2(5,10); //invokes constructer with two parameters ob2.show( ); return 0; } Output of the Program Default constructer 0 0 In one parameter constructor 5 0 In two parameter constructor 5 10 3.5.3 Copy Constructers

Copy constructer is used to copy the value of one object to another. The copy constructor takes a single argument of the same type as the class. It creates a new object, which is an (exact) copy of the passed object. This is done by copying all member variables from the passed object into the new object. As mentioned earlier the purpose of copy constructer is to declare and initialize an object from another object. An example for copy constructer is given below. Example 7: The following program makes use of copy constructors # include < iostream.h > class number
Anna University Chennai 48

DCS 115

OBJECT ORIENTED PROGRAMMING

{ int a; public: number(int x); //constructor number(number & x) //copy constructer void show( ); }; number::number(int x) { cout << In constructor\n; a=x; } number :: number(number& x) { cout<<Copy Constructor\n; a=x.a } void number::show( ) { cout <<Value of a is << a<<\n; } int main( ) { number ob(4); ob.show( ); //displays 4 number ob1(ob); //invokes copy constructer ob1.show(); //displays 4 return 0; } Output of the Program In constructor Value of a is 4 Copy Constructor Value of a is 4 Always the Copy constructer takes reference variable as a parameter. In this example the copy constructer copies the value of the object ob to object ob1. Have you Understood Questions? 1. 2. What is a constructer? Is it possible to overload constructer?
49

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

3. 3.6

What is purpose of copy constructer? Destructors

The complement of a constructor is the destructor. This function is called when an object is destroyed. For example, an object that allocates memory when it is created will want to free that memory when it is destroyed. The name of a destructor is the name of its class preceded by a ~. The destructor function has the following characteristics. A destructor function never takes any arguments. A destructor function will not return any values. Destructors cannot be overloaded Destructors can be made virtual.

The following is the example of a destructor. Example 8: The following program illustrates the use of destructors. # include <iostream.h > class number { int a; public: number( ); // constructor ~number( ); //destructor void show( ); }; number::number( ) { cout << In constructor\n; a=100; } number::~number( ) { cout << In Destructor...\n; } void number :: show() { cout<<a is <<a<<\n; } void main()
Anna University Chennai 50

DCS 115

OBJECT ORIENTED PROGRAMMING

{ number ob; ob.show(); } Output of the Program In constructor A is 100 In Destructor... A classs destructor is called when an object is destroyed. Local objects are destroyed when they go out of scope. Global objects are destroyed when the program ends. Have you Understood Questions? 1. 2. 3.7 3.7.1 What is a destructor? Is it possible to overload destructor? MORE ABOUT CLASSES Passing Objects to Functions

NOTES

Objects can be passed to functions as arguments in just the same way that other types of data are passed. Simply declare the functions parameter as a class type and then use an object of that class as an argument when calling the function. As with other types of data, by default all objects are passed by value to a function.

Example 9: In the following program an object is passed as parameter to the member function product. class number { int i; public: number(int n) { i = n; } int product(number o1,number o2); }; int number :: product(number o1,number o2) {
51 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

return o1.i( )* o2.i( ); }

int main( ) { number a(5), b(2); cout << a.product(a,b)<< \n; //OUTPUT 10 cout << b.product(a,b) << \n; //OUTPUT 10 return 0; } Output of the Program 10 10 The default method of passing of parameters in C++ is pass by value (including objects).In this example the function product takes two objects as arguments and return their product. 3.7.2 Returning Objects from Functions

Functions can return objects. First, declare the function as returning a class type. Second, return an object of that type using the normal return statement. Remember that when an object is returned by a function, a temporary object is automatically created which holds the return value. It is this object that is actually returned by the function. After the value is returned, this object is destroyed. Example 10: The following program illustrates the concept of returning an object from a function. This example add objects of the class money. #include<iostream.h> class money { int rs; int ps; money() { rs=0; ps=0; }
Anna University Chennai 52

DCS 115

OBJECT ORIENTED PROGRAMMING

money(int r,int p) { rs=r; ps=p; } money add(money m1,money m2); void display(); } money money :: add(money m1,money m2) { money temp; temp.ps=m1.ps+m2.ps; if(temp.ps>99) { temp.rs++; temp.ps-=99 } temp.rs+=m1.rs+m2.rs; return temp; } void money :: display() { cout<<Total Rupees <<rs; cout<<\n Total Paise <<ps; } void main() { money m1(10,55); money m2(11,55); money m3; m3.add(m1,m2); m3.display(); } Output of the Program Total Rupees 22 Total Paise 10 Have you Understood Questions? 1. Objects are passed in call by __________ method

NOTES

53

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

3.8

Static Data Members

A variable can be declared as static by prefixing it with a key word static. A static variable in C++ will work in the same way as the C language static variable. The other name for static variable is class variable. A static member is part of a class, but not part of an object of a class, so theres only one instance of them however many objects of that class are created. This is useful if, for instance, you want to keep a count of how many objects are created. A static data member must be defined outside the class definition. Static variable will have the following properties: It is always initialized to a default value. A static variable is common to the entire class, that is, only one copy of the static variable exists. All the objects will share the static variable.

Example 11: The example given below will count the number of objects created for the class one. #include<iostream.h> class one { private: static int count; public: void incr() { count ++; } void display( ) { cout <<count<< objects; } }; int one :: count ; //Static data member definition void main() { one 01, 02, 03; 01. incr (); 02. incr ();
Anna University Chennai 54

DCS 115

OBJECT ORIENTED PROGRAMMING

03. incr (); 03. display (); } Output of the Program 3 objects In this example a variable count is declared as a static data member. It will be initialized to zero. Every time when the function incr( ) is called the variable is incremented by one irrespective of the object. 3.8.1 Static Member Functions

NOTES

A member function can be declared as static by prefixing it with the keyword static. A static function will have the following rules. A static function can access only static variables. A static function will be called using the class name. A static function cannot access non-static variables. A static function cannot call non static functions. A static function is common to the entire class.

Example 12: The following program illustrates the concept of static member functions. #include<iostream.h> class one { private: int a; static int count; public: void set() { a=5; count=5; } static void incr() { a++; //ERROR a is non static variable count++; cout<<a;
55 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

cout<<count; } int one :: count; void main() { one obj1, obj2, obj3; obj1.set (); obj2.set (); obj3.set (); one::incr(); // calling a static function. } Note: The program has some compilation errors hence it will not run Have you Understood Questions? 1. 2. 3. 4. What is the default value for static integer value? How will you make a variable static? A static function can access only static variables (TRUE/FALSE) Assume that c1 is a class and fn() is a static function then how will you call the function f1() Const Members Functions

3.9

Class member functions may be declared as const. When this is done, that method cannot modify the object that invokes it. Also, a const function/method may not invoke a non-const member function of the same object. However a const method might call non-const methods of other classes or of other objects of the same class as itself. Further, a const class can be called from either const or non-const objects. To specify a member function as const, use the form shown in the following example: class ex1 { private: int x; public: int fun() const; // const member function }; The purpose of declaring a member functions as const is to prevent it from
Anna University Chennai 56

DCS 115

OBJECT ORIENTED PROGRAMMING

modifying the object that invokes it. Have you Understood Questions? 1. 3.10 A constant object is required to invoke a constant class (TRUE/FALSE) Friend Functions

NOTES

There will be time when you want a function to have access to the private members of a class without that function actually being a member of that class.C++ supports friend functions to achieve this purpose. A friend function is not a member of a class but still has access to its private elements. Friend functions are useful with operator overloading and the creation of certain types of I/O functions. Friend Functions posses the following features. The function that is declared as friend will not fall in the scope of the class it was declared. A friend declaration can be placed in either the private or the public part of a class declaration Like a member function, a friend function is explicitly declared in the declaration of the class of which it is a friend A friend function can access private data members of that class. A friend function will be called without the object. Usually friend function takes object as an argument.

The Syntax for creating a friend function is given below. class sample { private: public: friend void callme( ); }; In the main program the friend function can be called as a ordinary function without any objects. void main() { sample s; 57 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
} Example 13:

callme( );

The following is an example for friend function #include<iostream.h> class one { private: int a,b; public: one() { a=20; b=30; } friend float avg(one obj); }; float avg(one obj) { float r; r=(obj.a+obj.b)/2; return r; } void main() { one e; float m; m=avg(e); cout<< The Average is <<m; } Output of the Program The Average is 25.0 In this example the function avg( ) is declared as friend to the class one. As mentioned earlier this friend function takes object as a parameter of type the class one. Note that the definition of the function avg( ) is written like a ordinary function this is because the friend function will not fall in the scope of the class where it is defined. Finally the function is invoked without the help of the object.
Anna University Chennai 58

DCS 115

OBJECT ORIENTED PROGRAMMING

3.10.1 Friendly Function for Two Classes In C++ it is possible to declare member function of one class as a friend function of other class in this case we say that the two classes are friendly to each other and this concept is called as friend class. To create friendly classes you need to create a function that is friend to both the classes. Further you need to do forward declaration of the class that you are going to define later. Forward declaration is a concept in which we declare a class before defining it. Forward declaration intimates the compiler that the class declared is defined in the later part of the program. Here is an example for forward declaration. class test2; //Forward Declaration class test1 { }; class test2 //Definition of the class that has the forward declaration. { } Example 14: The following example creates two friendly classes.

NOTES

class c2; //Forward Declaration class c1 { private: int x; public: c1() { cin>>x;
59 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

} friend float avg(c1 01,c2 02); }; class c2 { private: int y; public: c2() { cin>>y; } friend float avg(ci 01,c2 02); };

float avg (c1 01,c2 02) { int ans; ans= (01.x +02.y) / 2; return ans; } void main() { c1 a; c2 b; float xyz; xyz= avg(a,b); cout<<xyz; } In this example the function avg( ) is declared as friend to the classes c1 and c2. Since the class c2 is written after class c1 we have to forward declaration for c1. The friend function avg( ) computes the average of the variables x and y declared in classes c1 and c2 respectively. Since avg( ) is a friend function it is called without the help of the object Have you Understood Questions? 1. 2. 3. In which situation you will declare a function as friend ? How will you call a friend function ? What is forward declaration?

Anna University Chennai

60

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
Summary Class is an user defined data type in C++. Classes in C++ are also called as Abstract Data Type (ADT) .Classes bind the data with its associated code. Member functions can be declared either inside/outside the class. If the member function is declared inside the class it is said to be inline functions. In C++ class variables are called as objects. Objects are run time entities of an object oriented system. A constructer is a special member function that has the same name as the class. A classs constructor is called each time an object of that class is created. Constructers will not have return type but can take parameters, hence constructers can be overloaded. Copy constructer is used to copy the value of one object to another. The complement of a constructor is the destructor. This function is called when an object is destroyed. A static member is part of a class, but not part of an object of a class, so theres only one instance of them however many objects of that class are created. A static member function can access only static variables and they are called using the class name. Class member functions may be declared as const. When this is done, that method cannot modify the object that invokes it. A friend function is not a member of a class but still has access to its private elements. Forward declaration is a concept in which we declare a class before defining it. Forward declaration intimates the compiler that the class declared is defined in the later part of the program

Exercises Short Questions 1. 2. 3. 4. 5. 6. List out the advantages of classes over structures When we create a new class a new built in data type is created (TRUE/ FALSE) Mention the properties of constructers and destructors. Destructors can be made virtual TRUE/FALSE. Explain Copy constructers with example A constructer can take parameter but it cannot have______________
61 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

7. 8. 9. 10. 11.

List out any three properties of static member functions. A static member function can access only_________ data members In which situation you will declare a member function as constant member function. Is friend function violating OOPS principle of data hiding? Discuss. By default friend functions will have this pointer (TRUE/FALSE)

Long Questions 1. 2. 3. 4. Explain how objects can be passed and returned from a function with an example Explain the concept of constructer overloaing Explain the concept of Friend functions with example. Explain briefly regarding static data members and static functions.

Programming Exercises 1. 2. Create a class called calculator and implement all basic functions of the calculator as member functions. Create a class called Product with prod_name, prod_id, cost, quantity as data members create necessary members functions constructers and destructors for the class Write a program to add two weights (Weights are represented in Kilograms and Grams) use passing and returning objects concept. Write a friend function to add objects of two complex numbers.

3. 4.

Answers to Have you Understood Questions Section 3.4 1. Class is another user defined data type in C++. Classes in C++ are also called as Abstract Data Type (ADT) .Classes binds the data with its associated code. Objects are run time entities of a class Just by prefixing the keyword inline before the function prototype. <class name> object; Eg. number obj

2. 3.

Section 3.5 1. Constructers are special member functions that have the same as the class. They are called when we create an object for a class.
62

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

2. Yes 3. Copy constructer is used to copy the value of one object to another. Section 3.6 1. The complement of a constructor is the destructor. This function is called when an object is destroyed. 2. No. Section 3.7 1. Value Section 3.8 1. 2. 3. 4. 0 Just by prefixing with the keyword static before variable declaration True. c1::fn()

NOTES

Section 3.9 1. False Section 3.10 1. 2. 3. When we want a function to have access to the private members of a class without that function actually being a member of that class. Friend functions are called like an ordinary member function without the help of the object. Forward declaration is a concept in which we declare a class before defining it. Forward declaration intimates the compiler that the class declared is defined in the later part of the program.

References 1. Teach yourself C++ Author: H. Schildt Publisher: Osborne 2000 Object Oriented Programming with C++
63 Anna University Chennai

2.

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
3.

Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Problem Solving with C++ (4th edition) Author: Walter Savitch Publisher: Addison Wesley 2002 Computing fundamentals with C++, Object oriented programming & design (2nd edition) Author: Rick Mercer Publisher: MacMillan Press 1995 The C++ Programming Language (3rd. edition) Author : Stroustrup, B., Publisher : Addison- Wesley, 1997.

4.

5.

Anna University Chennai

64

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 4 OPERATOR OVERLOADING AND TYPE CONVERSIONS


4.1 Operator Overloading Type Conversions Defining Operator Overloading Implicit Type Conversion Overloading Binary Operator Explicit Type Conversion Overloading Unary Operator Basic to Class Type Overloading Prefix and Postfix Increment/Decrement Operators Class to Basic Type Overloading new and delete Operators One Class to another Class Type Operator Overloading Using Friend Functions Introduction

Operator overloading refers giving special meaning to an existing operator. Operator overloading is similar to function overloading. In fact, operator overloading is really just a type of function overloading. However, some additional rules apply. This chapter introduces you to operator overloading that deals with overloading of both unary and binary operators. The second part of the chapter provides necessary details regarding type conversions or type casting. Type conversion or typecasting refers to changing an entity of one data type into another. This chapter focuses on implicit and explicit type conversions. 4.2 Learning Objectives To introduce the concept of Operator overloading To define operator overloading function To understand the steps involved in overloading binary operators
65 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

4.3

To understand the steps involved in overloading unary operators To show how to overload unary prefix and postfix operators To discuss overloading operators using friend functions To present the concept of Type casting To discuss implicit and explicit type casting. Operator Overloading

As mentioned earlier operator overloading refers giving special meaning to an existing operator. When an operator is overloaded, that operator loses none of its original meaning. Instead, it gains additional meaning relative to the class for which it is defined. An operator is always overloaded relatively to a user defined type, such as a class. To overload an operator, you create an operator function. Most often an operator function is a member or a friend of the class for which it is defined. Almost all operators in C++ can be overloaded, except the following few operators. 4.3.1 Class member access operators (. , .*) Scope Resolution operator ( :: ) Size operator( sizeof) Conditional operator ( ? :). Defining Operator Overloading

The general form of a member operator function is shown here: return-type class-name::operator#(arg-list) { // operation to be performed } The return type of an operator function is often the class for which it is defined ( however, operator function is free to return any type). The operator being overloaded is substituted for #. For example, if the operator + is being overloaded, the operator function name would be operator +. The contents of arg-list vary depending upon how the operator function is implemented and the type of operator being overloaded. There are two important restrictions to remember when you are overloading an operator: The precedence of the operator cannot be change.
66

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

4.3.2

The number of operands that an operator takes cannot be altered. Overloading Binary Operator

NOTES

When a member operator function overloads a binary operator, the function will have only one parameter. This parameter will receive the object that is on the right side of the operator. The object on the left side is the object that generates the call to the operator function and is passed implicitly by this pointer. Example 1: The following program overloads the + operator such that it adds two objects of the type complex. #include <iostream.h> class complex { int real; float imag; public: complex() { real=imag=0; } complex (int r,float i) { real = r; imag=i; } //overload + operator for complex class complex operator +(complex); void display() { cout<<The Result is ; cout<<real << +j <<imag ; } }; complex complex :: operator + (complex c1) { complex temp; temp.real=real +c1.real; temp.imag=imag + c1.imag; return temp; }
67 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

void main() { complex c1,c2,c3; int a; float b; cout<<ENTER REAL AND IMAG PART OF COMPLEX NUMBER1<<endl; cin>>a>>b; c1=complex(a,b); cout<<ENTER REAL AND IMAG PART OF COMPLEX NUMBER2<<endl; cin>>a>>b; c2=complex(a,b); //adds two complex objects invokes operator + (complex) function c3=c1 + c2 ; c3.display(); } Output of the Program ENTER REAL AND IMAG PART OF COMPLEX NUMBER1 5 7.1 ENTER REAL AND IMAG PART OF COMPLEX NUMBER2 3 8.3 The Result is 8 + j 15.3 Example 2: The program given below is the modified version of the example 10 program in Chapter3. The member function add() present in that program is replaced by the operator overloading function. #include<iostream.h> class money { int rs; int ps; money() { rs=0; ps=0; } money(int r,int p)

Anna University Chennai

68

DCS 115

OBJECT ORIENTED PROGRAMMING

{ rs=r; ps=p; } money operator +(money); void display(); } money money :: operator +(money m1) { money temp; temp.ps=m1.ps+ps; if(temp.ps>99) { temp.rs++; temp.ps-=99 } temp.rs+=m1.rs+rs; return temp; } void money :: display() { cout<<Total Rupees <<rs; cout<<\n Total Paise <<ps; } void main() { money m1(10,55); money m2(11,55); money m3; m3=m1+m2; m3.display(); } Output of the Program Total Rupees 22 Total Paise 10 4.3.3 Overloading Unary Operator

NOTES

Overloading a unary operator is similar to overloading a binary operator except that there is one operand to deal with. When you overload a unary operator using a member function, the function has no parameters. Since, there is only one
69 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

operand, it is this operand that generates the call to the operator function. There is no need for another parameter. Example 3: The following program overloads the unary operator that negates the object of point class #include <iostream.h> class point { int x, y; public: point( ) { x = 0; y = 0; } point(int i, int j) { x = i; y = j; } point operator-( ); void display() { cout<<x <<\t<<y; } }; // Overload - operator for point class point point::operator-( ) { x=-x; y=-y; } int main( ) { point o1(10, 10); int x, y; -o1; //Negate the object o1.display(); } Output of the Program -10 -10
70

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

4.3.4

Overloading Prefix and Postfix Increment/Decrement Operators

NOTES

When overloading the prefix ++ operator you write the member function as void operator ++( ) Similarly when overloading the postfix ++ operator we will write the member function as void operator ++( ) Hence there is an ambiguity because both the member function takes the same form the same problem exist for the pre and post fix decrement operators. To resolve this you have to pass a dummy integer argument for the postfix operator. void operator ++( ); void operator ( ) ; void operator ++(int); void operator ( int ) ; Note: The int parameter in the postfix operator is a dummy variable Example 4: The program given below overloads unary prefix ++ operator to increment the object of type point class #include <iostream.h> class point { int x, y; public: point( ) { x = 0; y = 0; } point(int i, int j) { x = i; y = j; } point operator++( ); void display()
71 Anna University Chennai

//UNARY PREFIX INCREMENT //UNARY PREFIX DECREMENT //UNARY POSTFIX INCREMENT //UNARY POSTFIX DECREMENT

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

{ cout<<The Object is Incremented to \n; cout<<x<<\n; cout<<y; } }; point point::operator++( ) // Overload prefix ++ operator for point class { ++x; ++y; } int main( ) { point o1(10, 10); ++o1; //increment an object o1.display(); } Output of the Program The Object is Incremented to 11 11 Example 5: The program given below overloads unary postfix operator to decrement the object of type point class #include <iostream.h> class point { int x, y; public: point( ) { x = 0; y = 0; } point(int i, int j) { x = i; y = j; } point operator( int ); void display()

Anna University Chennai

72

DCS 115

OBJECT ORIENTED PROGRAMMING

{ cout<<The Object is Decremented to \n; cout<<x<<\t; cout<<y; } }; point point::operator( int a) // Overload postfix operator for point class { x; y; } int main( ) { point o1(10, 10); o1; //decrement an object o1.display(); } Output of the Program The Object is Decremented to 9 9 4.3.5 Overloading new and delete Operators

NOTES

Most large C++ programs make use of dynamically allocated memory. C++ supports dynamic allocation and deallocation of memory using new and delete operators. Like other operators (except the few operators that cannot be overloaded) C++ allows these two operators to be overloaded. By using the overloaded version of new and delete operators there will be a simple and natural way to allocate and dellocate an object from a memory pool and initialize it properly. Example 6: The following example demonstrates the overloading of new and delete operators. #include<iostream.h> #include<cstdlib.h> class TestClass
73 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

{ int x,y; public: TestClass() { x = y = 0; } TestClass(int a, int b) { x = a; y = b; } void show() { cout << x << \t ; cout << y << endl; } void *operator new(size_t size); void operator delete(void *p); }; // overloaded new operator void *TestClass::operator new(size_t size) { void *p; cout << In overloaded new.\n; p = malloc(size); if(!p) { cout<<Unable to allocate<<endl; return; } return p; } // delete operator overloaded void MyClass::operator delete(void *p) {

Anna University Chennai

74

DCS 115

OBJECT ORIENTED PROGRAMMING

cout << In overloaded delete.\n; free(p); } 4.3.6 Operator Overloading Using Friend Functions

NOTES

It is possible to overload an operator relative to a class by using a friend rather than a member function. A friend function does not have a this pointer. In the case of a binary operator, this means that a friend operator function is passed both operands explicitly. For unary operators, the single operand is passed. Note: We cannot use a friend to overload the assignment operator. The assignment operator can be overloaded only by a member operator function. Example 7: The following program overloads + operator using friend function. #include <iostream.h> class point { int x, y; public: point( ) { x = 0; y = 0; } point(int i, int j) { x = i; y = j; } void display() { cout << X IS : << x << , Y IS : << y <<\n; } friend point operator+(point ob1, point ob2); }; // Overload + using a friend. point operator+(point ob1, point ob2) { point temp; temp.x = ob1.x + ob2.x;
75 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

temp.y = ob1.y + ob2.y; return temp; } int main( ) { point o1(10, 10), o2(5, 3), o3; o3 = o1 + o2; //add to objects // this calls operator+( ) o3.display(); return 0; } Output of the Program X IS : 15 ,Y IS : 13 Note that the left operand is passed to the first parameter and the right operand is passed to the second parameter Have you Understood Questions? 1. 2. 3. 4. 4.4 When we overload a operator will its meaning change ? Give the general form of operator function Write examples for unary and binary operators Which operator cannot overloaded using friend function ? TYPE CONVERSIONS

Definition Type conversion or typecasting refers to changing an entity of one data type into another. This is done to take advantage of certain features of type hierarchies. For instance, values from a more limited set, such as integers, can be stored in a more compact format and later converted to a different format enabling operations not previously possible, such as division with several decimal places worth of accuracy. Type conversion allows programs to treat objects of one type as one of their ancestor types to simplify interacting with them. 4.4.1 Implicit Type Conversion

Implicit type conversion is an automatic type conversion by the compiler. The type conversions are automatic as long as the data types involved are built-in types.

Anna University Chennai

76

DCS 115

OBJECT ORIENTED PROGRAMMING

Example int y; float x=123.45; y = x; In this example the float variable x is automatically gets converted to int. Thus the fractional part of y gets truncated. 4.4.2 Explicit Type Conversion Automatic type conversion for user defined data types is not supported by the compiler hence the conversion routines are ought to be specified explicitly. Three types of situations might arise in the data conversion between incompatible types. Conversion from basic type to class type. Conversion from class type to basic type Conversion from one class type to another class type.

NOTES

Basic to Class Type This is done by using constructors in the respective classes. In these types the = operator is overloaded. Example 8: The following program converts integer to the class type length class length { int cm,m; public: length(int n) //Constructor { m=n/100; cm=m%100; } } void main() { int n; cin >> n; length obj = n; //Integer to class type
77 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

} The constructor used for type conversions take a single argument whose type is to be converted. Class to Basic Type Overloaded casting operator is used to convert data from a class type to a basic data type.

Syntax: operator typename() { statements..... } This function converts a class type to specified type name. For example operator int() converts the class object to integer data type. Conditions for a casting operator function It must be a class member. It must not specify a return type. It must not have any arguments. Example 9: The following example cast the object of type time to basic data types (int and float)

class time { int min,sec; public: time(int n) { min = n/60; sec=n%60; }


Anna University Chennai 78

DCS 115

OBJECT ORIENTED PROGRAMMING

operator int() //Casting Operator { int x; x= min * 60 + sec; return sec; } operator float() //Casting Operator { float y; y = min + sec/60; return y; } }; void main() { time t1(160); int n = t1; //Conversion float x = t1; //Conversion } One Class to another Class Type The Constructors helped us to define the conversion from a basic data type to class type and the overloaded casting operator helped to define the conversion from a class type to basic data type. Now to convert from one class type to another class type these both help us to do. Example 10: The following program converts the class type length1 to type length2 class length2; //forward declaration class length1 { int m,cm; public: length1(int n) { m=n/100; cm=n%100; } operator length2() //from length1 type to length2 type

NOTES

79

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

{ int x= m*100 + cm; length2 tempobj(x); return tempobj; } } class length2 { int cm; public: length2(int n) { cm=n; } operator length1() //from length2 type to length1 type { length1 tempobj(cm); return tempobj; } } void main() { int x= 125; length2 obj1(x); length1 obj2= obj1; } Have you Understood Questions? 1. What is type casting? 2. Which operator you have to overload to convert a basic data type to user defined data type Summary Operator overloading refers giving special meaning to an existing operator. When an operator is overloaded, that operator loses none of its original meaning. Instead, it gains additional meaning relative to the class for which it is defined. We cannot overload Class member access operators, Scope Resolution operator, Size operator( sizeof) , Conditional operator ( ? :). When a member operator function overloads a binary operator, the function will have only one parameter.
80

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

When you overload a unary operator using a member function, the function has no parameters. To overload unary postfix operators a dummy integer is passed as a parameter to the operator function It is possible to overload an operator relative to a class by using a friend rather than a member function We cannot use a friend to overload the assignment operator. Type conversion or typecasting refers to changing an entity of one data type into another Implicit type conversion is an automatic type conversion by the compiler. The type conversions are automatic as long as the data types involved are built-in types. Explicit type conversion is necessary for user defined data types.

NOTES

Exercises Short Questions 1. 2. 3. 4. List out the operators that cannot be overloaded in C++> Write the various rules for overloading operators. Write the advantage of overloading operators using friend functions. What do you mean by implicit type conversion?

Long Questions 1. Explain how prefix and postfix operators are overloaded 2. How will you overload new and delete operators? Give example 3. Explain Explicit type conversion methods with example.

Programming Exercises 1. Write a program to overload binary operator + such that it is capable of adding two objects of distance class .The distance is expressed as foot and inches. 2. Write a program to overload ++ operator to increment time object. Time is expressed in hour, minute and second. Answers to Have you Understood Questions Section 4.3 1. No

81

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

2. return-type class-name::operator#(arg-list) { // operation to be performed } 3. Unary operator Eg !. Binary operator Eg. + 4. =(assignment operator) Section 4.4 1. Type conversion or typecasting refers to changing an entity of one data type into another. 2. =(assignment operator) References 1. Teach yourself C++ Author: H. Schildt Publisher: Osbornen 2000 Object Oriented Programming with C++ Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Problem Solving with C++ (4th edition) Author: Walter Savitch Publisher: Addison Wesley 2002 Computing fundamentals with C++, Object oriented programming & design (2nd edition) Author: Rick Mercer Publisher: MacMillan Press 1995 The C++ Programming Language (3rd. edition) Author : Stroustrup, B., Publisher : Addison- Wesley, 1997.

2.

3.

4.

5.

Anna University Chennai

82

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 5 INHERITANCE
Overview Of Inheritance Single Inheritance Access Control Inheritance and Access Control Inheritance in Private Mode Using Protected Members Multiple Inheritance Multilevel Inheritance Hierarchical Inheritance Hybrid Inheritance Constructers and Destructors in Derived Classes Parameterized Constructers in Derived Classes

5.1

Introduction

This chapter explores one of the most powerful features of C++ language, the inheritance. C++ strongly supports the concept of reusability with the help of inheritance. Inheritance is one of the primary features of any object oriented language. In this chapter you will go through the various forms of inheritance and you will learn how to implement them in C++ programs further this chapter will introduce you the access specifiers and you will learn how to apply them in your programs. 5.2 Learning Objectives To introduce inheritance concept To present the various access control mechanisms available in C++ To discuss single inheritance and its implementation To discuss multiple inheritance and its implementation To discuss multilevel inheritance and its implementation To discuss hierarchical inheritance and its implementation

83

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

To discuss hybrid inheritance and its implementation To show how constructors and destructors gets executed in inheritance.

5.3 Overview Of Inheritance Inheritance is a feature by which new classes are derived from the existing classes. Inheritance allows re-using code without having to rewrite from scratch. The parent class(Original existing class) is said to be the base class the new made class from it is called a derived class A class that is derived from parent class will posses all the properties of the base class apart from that it also has its own unique properties. However the derived class will not inherit constructers, destructors, friend functions and assignment operators further derived classes cannot remove any data member present in the base class.C++ supports various types of inheritance scheme. They are Single inheritance Multiple inheritance Multilevel inheritance Hierarchical inheritance Hybrid inheritance

Have you Understood Questions? 1. What is Inheritance? 2. Mention the various inheritance schemes supported in C++. 5.4 Single Inheritance When a class is derived from a single base class it is said to be single inheritance. It can be thought of as a specialization of an existing class.

Base Class

Derived class
Fig.5.1 Single Inheritance The syntax for implementing inheritance is class derivedclassname : access mode baseclassname
Anna University Chennai 84

DCS 115

OBJECT ORIENTED PROGRAMMING

The access mode may be public, protected or private. Example class base { }; class derived : public base { }; In this example the class derived inherits the properties of the class base. The inheritance is made in the public mode. Example 1 The following code is a simple example for single inheritance. In this example the derived class (number2) inherits the base class (number1) in public mode #include<iostream.h> class number1 { int a; public: number1( ) { a=0; } void get_a() { cout<<Enter the value for a \n cin>>a; } void show_a() {
85

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

cout<<a is <<a; } }; class number2: public number1 { private: int b; public: number2( ) { b=0; } void get_b() { cout<<Enter the value for b \n cin>>b; } void show_b() { cout<<b is <<b; } }; void main ( ) { number2 obj; obj. get_a ( ); obj. get_b ( ); obj.show_a( ); obj.show_b( ); } Output of the Program Enter the value for a 10 Enter the value for b 20 a is 10 b is 20 Here the inheritance is made in the public visibility mode. In the main program we create the object for derived class and access all public functions present in the base class. The derived class number2 will have the following features.

Anna University Chennai

86

DCS 115

OBJECT ORIENTED PROGRAMMING

From the class number2 Private Variables

NOTES

Public Functions number2( ) //constructer void get_b() void show_b()

int b

From the class number1 Private Variables

Public Functions void get_a() void show_a( )

None.

Have you Understood Questions? 1. Draw the scheme for single inheritance 2. Write the syntax for implementing single inheritance. 5.5 Access Control An access specifier in C++ determines which data member, which member function can be used by other classes. The three access specifiers supported in C++ are The private access specifier The public access specifier The protected access specifier

Only objects of the same class can have access rights to a member function or data member declared as private. A data member or a method declared as public can be accessed by all classes and their objects. Data members, methods that are declared protected are accessible by that class and the inherited subclasses The program given below uses all C++ access specifiers #include<iostream.h>

87

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

class Base { private: int privateInt ; protected: int protectedInt; public: int publicvar; Base() { privateInt =10; protectedInt=20; publicvar=30; } void display() { cout<< privateInt; cout<< protectedInt; cout<< publicvar; } }; class Derived :public Base { public: void change() { privetInt++ //Wrong! Private variables cannot be accessed protectedInt++; //OK publicvar++; //OK } } void main() {

Anna University Chennai

88

DCS 115

OBJECT ORIENTED PROGRAMMING

Derived obj; obj. privetInt=50 ; //Wrong! Private variables cannot be accessed obj. protectedInt=50; // Wrong! Protected variables cannot be accessed obj.publicInt=50; //OK } Note: The program has some compilation errors hence it will not run. 5.5.1 Visibility and Access Rights in C++

NOTES

The Table 5.1 lists the visibility and access rights in C++. ACCESS RIGHTS FOR THE DIFFERENT SCOPES CLASS\ACCESS RIGHTS same class subclass Other classes PRIVATE PROTECTED PUBLIC SCOPE SCOPE SCOPE yes no no yes yes no yes yes yes

Table 5.1 Access Rights in C++ 5.5.2 Inheritance and Access Control The protection keyword after the : operator in the derived class determines the access by derived class to base class members. For example consider the following scheme of inheritance. 1. class derived : private base All public members of the base class become private to the derived class,i.e. only members of the derived class can access them. All private members of the base class are private to the base class, i.e. nothing can access them, not even members of the derived class. All protected members become also private to the derived class. 2. class derived : protected base All public members of the base class become protected, i.e. only the derived class (and further derived classes) can access them. All private base class members are
89 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

private to base class, i.e. nothing can access them. All protected members of the base class stay protected, i.e. only the derived class (and further derived classes) can access them. 3. class derived : public base All public members of the base class are public in the derived class, i.e.anything can access them. All private members of the base are private to the base class, i.e. nothing can access them. All protected members of the base class stay protected, i.e. only the derived class (and further derived classes) can access them 5.5.3 Inheritance in Private Mode

We know that when the access specifier is private public members of the base become private members of the derived class, but these are still accessible by member functions of the derived class. NOTE: The program given below will not compile ,it has some errors Example 2: The program given below is an example for inheritance in private mode. #include <iostream.h> class base { int x; public: void setx(int n) { x = n; } void showx( ) { cout << x << \n; } }; // Inherit base as private class derived : private base { int y; public: void sety(int n) {
Anna University Chennai 90

DCS 115

OBJECT ORIENTED PROGRAMMING

y = n; } void showy( ) { cout << y << \n; } }; int main( ) { derived ob; ob.setx(10); // ERROR now private to derived class ob.sety(20); // access member of derived class - OK ob.showx( ); // ERROR now private to derived class ob.showy( ); // access member of derived class - OK return 0; }. Note: The program given in example 2 contains some errors as indicated in the comments, hence the program will not run. As the comments in this program illustrates, both showx( ) and setx() become private to derived and are not accessible outside it. Note that showx( ) and setx( ) are still public within base, no matter how they are inherited by some derived class. This means that an object of type base could access these functions anywhere. 5.5.4 Using Protected Members

NOTES

As you know from the preceding section, a derived class does not have access to the private members of the base class. However, there will be times when you want to keep a member of a base class private but still allow a derived class access to it. To accomplish this, C++ includes the protected access specifier. The protected access specifier is equivalent to the private specifier with the sole exception that protected members of a base class are accessible to members of any class derived from that base. Outside the base or derived classes, protected members are not accessible. The protected access specifier can occur any where in the class declaration, although typically it occurs after the (default) private members are declared and before the public members. The full general form of a class declaration is shown here:
91 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

class class-name { // private members protected: //optional // protected members public: //public members }; Example 3: The following program illustrates a single inheritance concept with protected variables #include<iostream.h> class base { protected: int a; //private to base but accessible from derived public: void get_a ( ) { cout<<Enter the Value for a \n; cin>>a; } }; class derived : public base { int b; public: void get_b() { cout<<Enter the Value for b \n; cin>>b; } void product() { int c; c= a * b // variable a is protected member of class base cout<<The Product is <<c; } }; void main()

Anna University Chennai

92

DCS 115

OBJECT ORIENTED PROGRAMMING

{ derived obj; obj.get_a(); obj.get_b(); obj.product(); } Output of the Program Enter the Value for a 10 Enter the Value for b 20 The Product is 200 Have you Understood Questions? 1. If a base class is inherited in private mode, how its public members appears for the derived class 2. If a base class is inherited in public mode, all the members of the class appears as public members to the derived class (TRUE/FALSE) 3. What is the special access specifier used for inheritance? 4. List the access specifiers available in C++. 5.6 Multiple Inheritance C++ allows a class to get derived from multiple base classes. A derived class can directly inherit more than one base class. In this situation, two or more base class is combined to create the derived class. Multiple inheritance is never necessary (some object oriented languages, e.g. java, dont even support multiple inheritance) and should be avoided. However, sometimes it makes programming easier. The multiple inheritance diagram is depicted below.

NOTES

Fig. 5.2 Multiple Inheritance

93

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Here the class D inherits the properties of classes A, B and C. The syntax for creating a derived class with multiple inheritance is class derived classname : access mode base1, access mode base2,..access mode base n { //body of the derived class } Example 4: The following code contains the C++ classes for the multiple inheritance diagram given in fig 5.3
EXPERIENCE DETAILS SALARY DETAILS EDUCATION DETAILS

PROMOTION

Fig. 5.3 Multiple Inheritance (promotion details) #include<iostream.h> #include<iomanip.h> #include<string.h> class Expdet { protected: char *name; int tot_exp; public: void expr( ) { cout<<Enter your name<<endl; cin>>name; cout<<Enter Total Experience<<endl; cin>>tot_exp; } }; class Saldet {
Anna University Chennai 94

DCS 115

OBJECT ORIENTED PROGRAMMING

protected: int salary; public: void salary( ) { cout<<Enter your Salary<<endl; cin >>salary; } };

NOTES

class Edudet { protected: char *degree; public: void eduqua( ) { cout<<Enter your Degree<<endl; cin>>degree; } }; class Promotion : public Expdet ,public Saldet, public Edudet { public: void promote( ) { if(tot_exp> 10 && sal>=20000 && (strcmp(degree,PG)= =0)) cout<< PROMOTED FOR HIGHER GRADE; else cout<<CANNOT BE PROMOTED ; } }; void main( ) { Promotion obj; obj . expr( ); obj . salary( ); obj . eduqua( ); obj . promote( ); }

95

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Output of the Program Enter your name John Enter Total Experience 25 Enter your Salary 23000 Enter your Degree PG PROMOTED FOR HIGHER GRADE Have you Understood Questions? 1. What is multiple inheritance? 2. Multiple inheritance is supported in _________ and not supported in__________ 5.7 Multilevel Inheritance

Multilevel inheritance is one form of multiple inheritance. In this scheme the derived class is made from two or more base class. Here a derived class can be used as a base class for another derived class, creating a multilevel class hierarchy. In this case, the original base class is said to be an indirect base class of the second derived class.

PERSON

EMPLOYEE

MANAGER
Fig.5.4 Multilevel Inheritance Thus this scheme can be extended to any level ( i.e generalization to specialization).Let us write the program for multilevel inheritance

Anna University Chennai

96

DCS 115

OBJECT ORIENTED PROGRAMMING

Example 5: The following code contains the C++ classes for the multilevel inheritance diagram given in fig 5.4 #include<iostream.h> #include<iomanip.h> #include<string.h> class person { protected: int age; char *name; public: void get1( ) }; class emp : public person { protected: int basic,hra; public: void get2() }; class manager : public emp { private: int deptcode; public: void get3( ); void display( ); }; void person :: get1( ) { cout<<Enter your Age<<endl; cin >> age; cout<<Enter your name<<endl; cin>> name; } void emp :: get2( ) { cout<<Enter your Basic and HRA<<endl; cin>>basic>>hra; }

NOTES

97

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

void manager :: get3() { cout<<Enter your Dept Code<<endl; cin >> deptcode; } void manager :: display( ) { cout<<Name is <<name; cout<<Age is <<age; cout<<Basic and HRA <<basic<<\t<<hra; cout<<Dept Code <<deptode; } void main( ) { manager obj; obj.get1( ); obj.get2( ); obj.get3( ); obj.display( ); } Output of the Program Enter your Age 28 Enter your name John Enter your Basic and HRA 20000 1500 Enter your Dept Code 200 Name is John Age is 28 Basic and HRA 20000 1500 Dept Code 200 The class manager is inherited from the class emp which in turn inherited from class person .Thus the class emp and manager will posses the following features. Class emp Protected Variables

Public Functions

Anna University Chennai

98

DCS 115

OBJECT ORIENTED PROGRAMMING

void get1() (From person class) void get2() Class manager

name, age (From person class) basic,hra

NOTES

Public Functions void get1() (From person class) void get2() (From emp class) void get3() void display() Have you Understood Questions?

Protected variables name, age (From person class) basic,hra (From emp class) deptcode(private variable)

1. Multilevel inheritance is special form of Multiple inheritance (TRUE/ FALSE) 5.8 Hierarchical Inheritance

The hierarchical inheritance structure is given below .This type is helpful when we have class hierarchies. In this scheme the base class will include all the features that are common to the subclasses.

Fig.5.5 Hierarchical inheritance In hierarchical inheritance it is necessary to create object for all the derived classes at the lower level because each derived class will have its own unique feature. Example 6: A simple program is written to implement the hierarchical inheritance structure given in the above figure. #include<iostream.h> #include<string.h> class A {
99 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

protected: int x, y; public: void get ( ) { cout<<Enter two values<<endl; cin>> x>>y; } };

class B : public A { private: int m; public: void add( ) { m= x + y; cout<<The Sum is <<m; } }; class C : public A { private: int n; public: void mul( ) { n= x * y; cout << The Product is <<n; } }; class D : public A { private: float l; public: void division( ) { l = x / y; cout <<The Quotient is << l; }
Anna University Chennai 100

DCS 115

OBJECT ORIENTED PROGRAMMING

};
void main( ) { B obj1; C obj2; D obj3; B .get( ); B .add( ); C .get( ); C .mul( ); D .get( ); D .division( ); }

NOTES

Output of the Program Enter two values 12 6 The Sum is 18 The Product is 72 The Quotient is 2.0 Here we can note that objects were created for all the subclasses to access their member functions. Have you Understood Questions? 1. Hierarchical inheritance is useful when we have _____________ of classes Hybrid Inheritance

5.9

A hybrid inheritance scheme is the combination of all the inheritance schemes discussed earlier. Consider for a example , calculating net pay for an employee, apart from the normal pay he may also get additional pay by working overtime, thus the net pay will be the sum of normal pay plus overtime pay. This example can be modeled as hybrid inheritance scheme in C++

101

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Emp_det

Normal pay

Additional pay

Net pay

Fig.5.6 Hybrid Inheritance Example 7: The C++ classes for the fig 5.6 are given below. #include<iostream.h> class emp_det { protected: int emp_id; public: void get_id() { cout<<ENTER EMPID<<endl; cin>>emp_id; } void disp_id() { cout<< EMPID IS <<emp_id<<endl; } }; class norm_pay :public emp_det { protected: float bpay; public: void get_bpay() { cout<<ENTER BASIC PAY<<endl; cin>>bpay;
Anna University Chennai 102

DCS 115

OBJECT ORIENTED PROGRAMMING

} void disp_bpay() { cout<< BASIC PAY IS = <<bpay<<endl; } }; class add_pay { protected: int hrs; int rp; int ap; public: void get_addpay() { cout<<ENTER OVERTIME HOURS<<endl; cin>>hrs; co ut<<ENTER HOW MUCH RUPEES PER HOUR<<endl; cin>>rp } void disp_addpay() { ap=hrs * rp; cout<<TOTAL OVERTIME HOURS<<hrs<<endl; cout<<ADDITIONAL PAY = << ap <<endl; } }; class net_pay :public norm_pay,public add_pay { int netpay; public: void display() { netpay=ap+bpay; cout<<NET PAY IS <<netpay; } }; void main() { net_pay obj; obj.get_id(); obj.get_bpay();
103

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

obj.get_addpay(); obj.disp_id(); obj.disp_bpay(); obj.disp_addpay(); obj.display(); } Output of the Program ENTER EMPID 1101 ENTER BASIC PAY 10000 ENTER OVERTIME HOURS 10 ENTER HOW MUCH RUPEES PER HOUR 50 EMPID IS 1101 BASIC PAY IS = 10000 TOTAL OVERTIME HOURS 10 ADDITIONAL PAY = 500 NET PAY IS 10500 Have you Understood Questions? 1. Hybrid inheritance scheme is the combination of (a) Multiple (b) Multilevel (c) both a and b 5.10 Constructers and Destructors in Derived Classes

It is possible for the base class, the derived class, or both to have constructor and/ or destructor functions. When a base class and a derived class both have constructor and destructor functions, the constructor functions are executed in order of derivation. The destructor functions are executed in reverse order. That is, the base constructor is executed before the constructor in the derived class. The reverse is true for destructor functions: the destructor in the derived class is executed before the base class destructor. Example 8: This example illustrates the order in which the constructors and destructors get executed in an inheritance program

Anna University Chennai

104

DCS 115

OBJECT ORIENTED PROGRAMMING

class A { public: A( ) { cout<<INSIDE A; } ~A ( ) { cout<<EXIT A; } }; class B : public A { public: B() { cout<<INSIDE B; } ~B() { cout<<EXIT B; } }; class C : public B { public: C( ) { cout<<INSIDE C; } ~ C( ) { cout<<EXIT C; } }; void main() { C obj; }

NOTES

105

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Output of the Program INSIDE A INSIDE B INSIDE C EXIT C EXIT B EXIT A 5.10.1 Parameterized Constructers in Derived Classes C++ supports a unique way of initializing class objects when a hierarchy of classes are created using inheritance. Constructers in an inheritance program can also be written using the syntax given below. constructer (arglist): initialization-section { //body of the constructer } Note that we have used a colon : immediately after the constructer name to assign initial values. An example is given below. Example 9: The following is the example of parameterized constructors in an inheritance program #include <iostream.h> #include<iomanip.h> class A { int a; public: A (int x ) { a=x; cout<<INSIDE A; cout<< a is <<a<<endl; } ~A ( ) { cout<<EXIT A; }

Anna University Chennai

106

DCS 115

OBJECT ORIENTED PROGRAMMING

}; class B { int b; public: B(int y) : b(y) { cout<<INSIDE B; cout<< b is <<b<<endl; } ~B() { cout<<EXIT B; } }; class C : public A,public B { int m,n public: C(int p,int q,int r,int s ) :A(p),B(q*2),m(r),n(s) { cout<<INSIDE C; cout<< m is <<m<< n is <<n<<endl; } ~ C( ) { cout<<EXIT C; } }; void main() { C obj(10,20,30,40); } Output of the Program INSIDE A a is 10 INSIDE B B is 40 INSIDE C m is 30 n is 40
107

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

EXIT C EXIT B EXIT A In this program the object for the class C is created, in the constructer of class C we have initialized the values for the member variables m and n using the statements m(r) and n(s) which is given in the initialization section of the constructer C. Similarly we have also initialized the values of the base class constructers. The statement A(p) will initialize the value of a in the base class A and the statement B(q*2) will initialize the value of b to q multiplied by 2 in the base class B. Have you Understood Questions? 1. 2. Summary Inheritance is a feature by which new classes are derived from the existing classes. The parent class(Original existing class) is said to be the base class the new made class from it is called a derived class When a class is derived from a single base class it is said to be single inheritance. It can be thought of as a specialization of an existing class. A derived class can directly inherit more than one base class this concept is said o be multiple inheritance Multilevel inheritance is one form of multiple inheritance. In this scheme the derived class is made from two or more base class When the properties of one class are inherited by two or more classes then that inheritance scheme is said to be hierarchical inheritance. Hybrid inheritance scheme is the combination many simple inheritance schemes. A derived class can inherit a base class in public or protected or private mode. The protected access specifier is equivalent to the private specifier with the sole exception that protected members of a base class are accessible to members of any class derived from that base. It is possible for the base class, the derived class, or both to have constructor and/or destructor functions. When a base class and a derived class both have constructor and destructor functions, the constructor functions are executed in order of derivation. The destructor functions are executed in reverse order. Write the order in which constructers are executed in inheritance Write the order in which destructors are executed in inheritance

Anna University Chennai

108

DCS 115

OBJECT ORIENTED PROGRAMMING

Exercises Short Questions 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Mention the different scheme of inheritance supported by C++ Write the syntax of creating a derived class. The derived class is the _______________ of the generalized base class All the public members of the base class will become ______________ for the derived class if we inherit in protected mode Write the syntax for creating multiple inheritance _________________ inheritance scheme is involved ,if a derived class D inherits properties of the base classes A and B. List out some advantages of multilevel inheritance What do you mean by hybrid inheritance? Constructers are not inherited in derived classes (TRUE/FALSE) Destructors in inheritance are called in _______________ order of the inheritance

NOTES

Long Questions 1. 2. 3. 4. Discuss the various types of inheritance available in C++ Give a brief note on hybrid inheritance with an example Explain Constructers and destructors in inheritance. Explain how parameters are passed to constructors in inherited program.

Programming Exercises 1. Create a base class called vehicle and add relevant data members and functions to it. Create derived classes that directly inherit the base class called two wheeler and four wheeler add relevant data members and functions to them. Write a main program and create objects for the derived class and access the member functions Implement the inheritance scheme given below.
BOOK DETAILS

2.

AUTHOR DETAILS

PUBLISHER DETAILS
109 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

3.

Implement the inheritance scheme given below with a C++ program

Device

Input device
4.

Output device

Create a class called employee with necessary data members. Create two derived classes called regular-emp and temporary-emp with necessary data members. Calculate the net pay for both these categories and display the details. Implement the inheritance scheme given below with a C++ program
Vehicle

5.

Two Wheeler

Four Wheeler

Cars

Trucks

Answers to Have you Understood Questions


Sect ion 5.3

1. 2.

Inheritance is a feature by which new classes are derived from the existing classes. Single inherit ance ,Multiple inheritance,Mult ilevel inheritance,Hierarchical inheritance ,Hybrid inheritance

Section 5.4 1.

Base Class

Derived class
Anna University Chennai 110

DCS 115

OBJECT ORIENTED PROGRAMMING

2. class derived classname : access mode base classname Section 5.5 1. 2. 3. 4. private FALSE Protected private, protected and public

NOTES

Section 5.6 1. 2. If a derived class directly inherits from more than one base class.then this scheme of inheritance is said to be multiple inheritance. C++,Java

Section 5.7 1. TRUE Section 5.8 1. Hierarchy

Section 5.9 1. C Section 5.10 1. The constructor functions are executed in order of derivation. 2. The destructors are executed from derived to base.

111

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

References 1. Teach yourself C++ Author: H. Schildt Publisher: Osborne 2000 Object Oriented Programming with C++ Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Problem Solving with C++ (4th edition) Author: Walter Savitch Publisher: Addison Wesley 2002 Computing fundamentals with C++, Object oriented programming & design (2nd edition) Author: Rick Mercer Publisher: MacMillan Press 1995 The C++ Programming Language (3rd. edition) Author : Stroustrup, B., Publisher : Addison- Wesley, 1997. Thinking in C++ Author: Bruce Eckel Publisher : Prentice Hall 2000

2.

3.

4.

5.

6.

Anna University Chennai

112

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 6

POLYMORPHISM
6.1 Binding Virtual Functions Virtual Destructors Introduction Virtual Base Classes Pure Virtual Function Abstract Classes

Polymorphism is another important feature of object oriented programming. The word Poly means many, and Morphism means structure or forms, thus in C++ polymorphism refers to an object that possess many form. Polymorphism can be classified into compile time polymorphism and runtime polymorphism. You have learned about compile time polymorphism in Chapter 2 and Chapter 4. Compile time polymorphism in C++ can achieved using function and operator overloading. In addition to compile time polymorphism (function and operator overloading) C++ also provides run time polymorphism with virtual functions and abstract classes. These can be used to generate common interfaces to different classes. In this chapter we will discuss details regarding run time polymorphism. This chapter covers all the fundamental aspects of run time polymorphism. 6.2 6.3 Learning Objectives To introduce the concept of biding To present the concept of virtual functions To present the concept of virtual destructors To introduce pure virtual functions. To discuss details regarding virtual base classes To introduce the concept of abstract classes Binding

The process of associating or binding a particular function/method code to an object is called binding, i.e. binding specifies exactly which code is called, when a function is called. Usually, functions are called statically, i.e. the compiler knows
113 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

at compile time exactly, which code is associated with an object. This is called static binding or early binding. However, sometimes the compiler cannot know at compile time, which function is meant. In this case, the binding has to happen at run time. This is called dynamic binding or late binding. Early binding achieves compile time polymorphism and late biding achieves run time polymorphism. In C++ dynamic binding can be achieved by creating object pointers to the base class. When you create object pointers to base class we get the following advantages It makes the program flexible We can create one array to store objects of both base and derived classes

Pointers to base classes can be assigned addresses of derived classes. When such a pointer is used to access member methods, the compiler does not know, which method to call. It can be either the function from the base class or potentially an overloaded function in the derived class. Example 1: The following program creates a object pointer to the base class and access functions of both base and derived class. #include<iostream.h> class base { public: void display() { cout<<I AM IN BASE; } }; class derived : public base { public: void display() { cout<<I AM IN DERIVED; }
Anna University Chennai 114

DCS 115

OBJECT ORIENTED PROGRAMMING

}; void main() { base b,*ptr; derived d; //To call display function in class base ptr= &b; ptr->display(); //To call display function in class derived ptr=&d; ptr->display(); //This will invoke the display function of base not derived } Output of the Program I AM IN BASE I AM IN BASE To overcome the problem encountered earlier virtual functions are used. 6.3.1 Virtual Functions.

NOTES

A virtual function is simply declared by putting the keyword virtual before the function declaration. Overloading virtual functions is called as overriding. The argument list and return-type of the function in derived classes must be the same as in the base class otherwise it is only overloaded, not overridden. Any pointer to a class that contains virtual functions is provided with additional information about what it points to. When a virtual function is called through such a pointer, then the pointer knows what object it points to. This is dynamic binding. Example 2: The following program is the modified version of example 1, here the function display() is declared as virtual. #include<iostream.h> class base { public: virtual void display() {
115 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

cout<<I AM IN BASE; } }; class derived : public base { public: void display() { cout<<I AM IN DERIVED; } }; void main() { base b,*ptr; derived d; ptr= &b; //To call display function in class base ptr->display();//To call display function in class derived ptr=&d; ptr->display(); //This will invoke the display function of derived } Output of the Program I AM IN BASE I AM IN DERIVED A function declared virtual in base class is always virtual. The keyword virtual is not required in the derived class. Some important points about virtual functions: Overridden virtual functions must have the same argument list and return type. The different behavior of a virtual function and a non-virtual function occurs only, if the object is accessed through a pointer with type of a base class. Even if the virtual function is overridden, the derived class has still access to the virtual function. It can call it by using the scope-operator (::). The prototype of the virtual function in the base class and the derived class must be the same. A virtual function must be a member function of the class. It should not be a friend function. Virtual functions cannot be made static. Constructors cannot be made virtual; however destructors can be made virtual.
116

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

A virtual function will be usually called with the help of a pointer. A virtual function in the base class must be declared even when no definitions can be made possible. Each object with virtual function(s) is provided with a Function Lookup Table. This table contains information about the virtual functions and is used to determine, which function is to be called. However, there is only one table for each class and each object of this class gets a pointer to this table. If a virtual function is overridden, the pointer in the table points to the derived class function. If it is not overridden, it points to the base class version. Have you Understood Questions? 1. Virtual functions achieves ____________ form of polymorphism 2. When binding happens at run time we call it as ____________ 3. List the advantages of creating object pointers to base classes. 6.4 Virtual Destructors

NOTES

Constructers and destructors are not inherited. Constructors always create one particular type and hence it makes no sense to inherit them. Therefore they cannot be made virtual. Destructors are used when an object is deleted. If the derived class allocates some resources that outside the base class methods, it needs its own destructor. However, as explained before, a pointer to a base class can be used to point to a derived class. To ensure that the correct destructor is called, the destructor should be virtual otherwise it might happen that some resource is not deallocated. For this reason, destructors should always be declared virtual. Have you Understood Questions? 1. Constrcuters are inherited(TRUE /FALSE) 2. Destructors are not inherited (TRUE/FALSE) 6.5 Virtual Base Classes

Suppose you have two derived classes B and C that have a common base class A, and you also have another class D that inherits from B and C. You can declare the base class A as virtual to ensure that B and C share the same sub object of A. In the following example, an object of class D has two distinct sub objects of class A, one through class B1 and another through class B2. You can use the keyword virtual in front of the base class specifies in the base lists of classes B1 and B2 to indicate that only one sub object of type A, shared by class B1 and class B2, exists.

117

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
A

B1

B2

D
Fig. 6.1 Virtual Base Classes The C++ classes for the fig 6.1 were class A { }; class B1 :virtual public A { }; class B2: virtual public A { }; class D:public B1,public B2 { } NOTE: The keywords virtual and public can be used in either order. For Example virtual public A is equivalent to public virtual A

Anna University Chennai

118

DCS 115

OBJECT ORIENTED PROGRAMMING

Have you Understood Questions? 1. What happens if base class is declared virtual? 2. In which order the keywords virtual and public must appear in the derived class? 6.6 Pure Virtual Function

NOTES

Sometimes when a virtual function is declared in the base class there is no meaningful operation for it to perform. This situation is common because often a base class does not define a complete class by itself. Instead, it simply supplies a core set of member functions and variables to which the derived class supplies the remainder. When there is no meaningful action for a base class virtual function to perform, the implication is that any derived class must override this function. To ensure that this will occur, C++ supports pure virtual functions. A pure virtual function has no definition relative to the base class. Only the function prototype is included. To make a pure virtual function, use this general form: virtual type func-name(parameter-list) = 0; For Example virtual void show()=0; The key part of this declaration is the setting of the function equal to 0. This tells the compiler that no body exists for this function relative to the base class. When a virtual function is made pure, it forces any derived class to override it. If a derived class does not, a compile-time error results. Thus, making a virtual function pure is a way to guaranty that a derived class will provide its own redefinition. Have you Understood Questions? 1. How will you declare a pure virtual function? 6.7 Abstract Classes An abstract class is a class that is designed to be specifically used as a base class. For an abstract class no objects can be created. Objects can only be generated from derived classes. An abstract class contains atleast one pure virtual function. As mentioned earlier a pure virtual function is declared by adding = 0 to the function declaration. Any (non-virtual) class that is derived from an abstract class must implement all pure virtual functions of the base class. Otherwise it is a virtual class itself. The following is the example of an abstract class.

119

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

class shape { public: virtual void area()=0; }; Once the abstract class is created the class inheriting it should override all the pure virtual functions. For example class square :public shape { public: void area() { cin>>side; int s=2 * side; cout<<AREA IS <<s; } }; Have you Understood Questions? 1. Summary The process of associating or binding a particular function/method code to a name is called binding. Early binding achieves compile time polymorphism and late biding achieves run time polymorphism. Virtual functions are used to implement run time polymorphism. A virtual function is simply declared by putting the keyword virtual before the function declaration. Overloading virtual functions is called as overriding. Each object with virtual function(s) is provided with a Function Lookup Table. This table contains information about the virtual functions and is used to determine, which function is to be called. You can declare the base class as virtual to ensure that the subclasses share the same sub object of the base class A pure virtual function has no definition relative to the base class. Only the function prototype is included always a pure virtual function is equated to zero. An abstract class is a class that is designed to be specifically used as a base class.
120

Objects cannot be created for abstract class (TRUE/FALSE)

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

Exercises Short Questions 1. Differentiate early and late binding concepts 2. The binding that is associated with function overloading is _____________________ 3. What is the purpose of function look up table ? 4. Write short notes on Virtual destructors 5. Why we need pure virtual functions? How it is declared? 6. Overloading of virtual functions is called as ________________ Long Questions 1. Explain virtual functions with a example. Write the rules associated with virtual functions. 2. Write a not on Virtual Destructors 3. Explain Abstract classes and its features with example Programming Exercises 1. Implement the inheritance scheme given below with a C++ program
Device

NOTES

Input device

Output device

Input/Output device

1.

Create a virtual base class called shape with a virtual function area (). Create derived classes rect, square and circle and override the function area() and compute the area of the objects.

Answers to Have you Understood Questions Section 6.3 1. Run time 2. Dynamic binding 3. (a)It makes the program flexible (b) We can create one array to store objects of both base and derived classes

121

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Section 6.4 1. False 2. True Section 6.5 1. 2. If we declare the base class as virtual to ensure that all the sub classes share the same object of the base class They can appear in either order.

Section 6.6 1. By equating the function prototype to zero. Section 6.7 1. TRUE. References 1. Teach yourself C++ Author: H. Schildt Publisher: Osborne 2000 Object Oriented Programming with C++ Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Problem Solving with C++ (4th edition) Author: Walter Savitch Publisher: Addison Wesley 2002 Computing fundamentals with C++, Object oriented programming & de sign (2nd edition) Author: Rick Mercer Publisher: MacMillan Press 1995 The C++ Programming Language (3rd. edition) Author : Stroustrup, B., Publisher : Addison- Wesley, 1997. Thinking in C++ Author: Bruce Eckel Publisher : Prentice Hall 2000
122

2.

3.

4.

5.

6.

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 7 FILES
7.1 File Stream Operations Binary File I/O Binary Sequential Input And Output Operations Random Access Files Introduction Input And Output Operations With Files Reading And Writing Objects In A File Error Handling In File Operations

We all know C++ I/O operates on streams hence it is very important to know about streams supported by C++. Regarding streams this chapter starts the discussions from knowing the hierarchy of C++ I/O classes. You will be learning handling sequential files, random access files and binary files in detail. This chapter introduces you to write programs in C++ to handle the above mentioned files. Finally the chapter also discusses the error handling mechanisms supported by c++ when working with files. 7.2 7.3 Learning Objectives To introduce file stream operations To introduce file I/O To discuss sequential input and output operations To present the concept of random access files To show how input output operations are performed on binary files To introduce error handling mechanisms in files. File Stream Operations

C++ I/O system operates on streams. A stream is a common, logical interface to various devices of a computer system. A stream either produces or consumes information, and is linked to a physical device by the C++ I/O system. All streams behave in the same manner.
123 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

There are two types of streams: text and binary. A text stream is used with characters. When a text stream is being used, some character translations may take place (e.g. newline to carriage-return/linefeed combination). A binary stream uses binary format for representing data in the memory. A binary stream can be used with any type of data. No character translation will occur. Thus always the binary file contains exact data sent by the stream. C++ contains several predefined streams that are automatically opened. These are cin, cout, cerr and clog. By default, cin is linked to the keyboard, while the others are linked to the screen. The difference between cout, cerr and clog is, that cout is used for normal output, cerr and clog are used for error messages. The I/O system of C++ has many classes and file handling functions. All these classes are derived from the base class ios.The hierarchy of C++ I/O classes are given below.

IOS

ISTREAM

STREAMBUF

OSTREAM

IOSTREAM

IFSTREAM

FSTREAM

OFSTREAM

Fig.7.1. Hierarchy of C++ I/O classes Have you Understood Questions? 1. What is a stream ? 2. What are the two types of streams? 7.4 File I/O File I/O and console I/O are closely related. To perform file I/O, you must include <fstream> in your program. It defines several classes, including ifstream, ofstream and fstream. These classes are derived from ios, so ifstream, ofstream and fstream
Anna University Chennai 124

DCS 115

OBJECT ORIENTED PROGRAMMING

have access to all operations defined by ios. In C++, a file is opened by linking it to a stream. There are three types of streams: input, output and input/output. Before you can open a file, you must first obtain a stream. To create an input stream, declare an object of type ifstream. To create an output stream, declare an object of type ofstream. To create an input/output stream, declare an object of type fstream.

NOTES

Examples ofstream out(emp.dat); //Opens emp.dat file in output mode ifstream in(emp.dat); //Opens emp.dat file in input mode fstream fin(emp.dat); //Opens emp.dat file in input/output mode The prototype of each member function is given below. void ifstream::open(const char * filename,openmode) void ifstream::open(const char * filename,openmode) void ifstream::open(const char * filename,openmode)

Here filename is the name of the file to be processed, the filename also includes the path specifier. The value of the mode specifies how the file has to be opened.C++ supports the following file opening modes ios::app ios::ate ios::binary ios::in ios::out ios::trunk

Note that the file opening modes can be combined using | symbol. For example ofstream out(emp.dat ,ios::out | ios::trunk) ios::app: causes all output to that file to be appended to the end. Only with files capable of output. ios::ate: causes a seek to the end of the file to occur when the file is opened. ios::out: specify that the file is capable of output. ios::in: specify that the file is capable of input. ios::binary: causes the file to be opened in binary mode. By default, all files are opened in text mode. In text mode, various character translations might take place, such as carriage return/linefeed sequences being
125 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

converted into newlines. However, when a file is opened in binary mode, no such character translations will occur ios::trunc: causes the contents of a pre-existing file by the same name to be destroyed and the file to be truncated to zero length. When you create an output ios::trunc: causes the contents of a pre-existing file by the same name to be destroyed and the file to be truncated to zero length. When you create an output stream using ofstream, any pre-existing file is automatically truncated.

Once the file is opened we can read from or write into the file based on the mode you have opened. After processing the file it has to be closed. To close a file we have to use the member function called close, for example in.close() //this will close file pointed by the stream in. The close function will not take any parameters and will not return any value. Example 1: The following program writes name and rollno into a file called student. #include<iostream.h> #include<fstream.h> int main() { ofstream out(Student); //open the file student in output mode char name[30]; int rollno; cout<<ENTER YOUR NAME<<endl; cin>>name; cout<<ENTER YOUR ROLL NO<<endl; cin>>rollno; out<<name <<\t ; // write name to the file student out<<rollno; // write rollno to the file student out.close(); } Output of the Program ENTER YOUR NAME AHAMED ENTER YOUR ROLL NO 1101

Anna University Chennai

126

DCS 115

OBJECT ORIENTED PROGRAMMING

To view the outputs from file go to command prompt and type the command given below. c:\tc\bin>type student (press enter key) AHAMED 1101

NOTES

In this example we have opened the file student in output mode. Since the openmode parameter to open( ) defaults to a value appropriate to the type of stream being opened, there is no need to specify its value in the preceding example. Example 2: The following example reads the content of the file student. #include<iostream.h> #include<fstream.h> int main() { ifstream in(Student); //open the file student in input mode char name[30]; int rollno; in>>name; // read name from the file student in>>rollno; // read rollno from the file student cout<<NAME IS <<name<<endl; cout<<ROLL NO IS <<rollno ; in.close(); } Output of the Program NAME IS AHAMED ROLL NO 1101 In the preceding examples we are working with one file at a time. Now lets learn now let us learn how to work with multiple files. Example 3: This example works with more than one file. #include<iostream.h> #include<fstream.h> #include<iomanip.h> int main()
127 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

{ ofstream out; out.open(book); out<<C++; out<<JAVA; out.close(); out.open(author); out<<H.SCHILDT; out<<BALAGURUSAMY; out.close(); out.open(publisher); out<<OSBORNE; out<<TATA MCGRAW; out.close(); ifstream in; char disp[100]; //create a buffer to store the data read from the file in.open(book); cout<<BOOK DETAILS <<endl; while(in) //iterate till end of file { getline(in,disp); //read a line from the file and put in the buffer cout<<disp; } in.close(); cout<<AUTHOR DETAILS<<endl; in.open(author); while(in) //iterate till end of file { getline(in,disp); //read a line from the file and put in the buffer cout<<disp; } in.close(); cout<<PUBLISHER DETAILS<<endl; in.open(publisher); while(in) //iterate till end of file { getline(in,disp); //read a line from the file and put in the buffer

Anna University Chennai

128

DCS 115

OBJECT ORIENTED PROGRAMMING

cout<<disp; } in.close(); return 0; } Output of the Program BOOK DETAILS C++ JAVA AUTHOR DETAILS H.SCHILDT BALAGURUSAMY

NOTES

PUBLISHER DETAILS OSBORNE TATA MCGRAW Here three files book, author, publisher are opened in output mode and the contents are written and then same files are opened in input mode, the contents are read from the file and displayed. In this example we have used the getline function, which is used to read a line from the file pointed by the stream and store in a buffer .The second parameter in the getline function indicates buffer name. Have you Understood Questions? 1. List some classes available in fstream header file? 2. if we want have a input and output operations on a file which type of object we create? 3. Write any two file opening modes? 7.5 Sequential Input And Output Operations Sequential input and output operations are performed on sequential files. A sequential file is one in which every record is accessed serially, in the order in which they are written hence to process any ith record all the previous i-1 records has to be processed. In C++ every sequential file (including Random access file) will be associated with two file pointers. They are

129

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

get() pointer put() pointer

The get pointer is an input pointer; it is used to read the content of the file. The get pointer will point content of the file to be read. When the file is opened in input mode the get pointer will point the first location of the file. The put pointer is an output pointer; it is used to write content to the file. The put pointer will point to location where the content has to be written. When the file is opened in output mode the put pointer will point the first location of the file. However when the file is opened in append mode (ios::app) the put pointer will point the last location of the file. Example 4: This example program uses put pointer to write content to the sequential file. #include<iostream.h> #include<fstream.h> int main() { fstream out(test,ios::out); //opens test file in output mode cout<<ENTER A STRING AT END PRESS #<<endl; do { cin.get(ch); out.put(ch); //write a character to the file } while (ch! =#) out.close(); } Output of the Program ENTER A STRING AT END PRESS# ANNA UNIVERSITY# c:\tc\bin>type test ANNA UNIVERSITY# Example 5: This is an example program that uses get pointer to read content from the sequential file.

Anna University Chennai

130

DCS 115

OBJECT ORIENTED PROGRAMMING

#include<iostream.h> #include<fstream.h> int main() { fstream in (test,ios::in); //opens test file in input mode char ch; cout<<READING CONTENT FROM THE FILE.<<endl; while (in) { in.get(ch); //get a character to the file cout<<ch; } in.close(); } Output of the Program READING CONTENT FROM THE FILE. ANNA UNIVERSITY# Have you Understood Questions? 1. What is sequential file ? 2. write the 2 pointers associated with sequential file ? 7.6 Random Access Files Random access file is one that allows accessing records randomly in any order hence any ith record can be accessed directly. In order to perform random access to a file C++ supports the following functions in addition to get() and put() pointers seekg() seekp() tellg() tellp() Moves get pointer to specified position Moves put pointer to specified position Returns the position of get pointer Returns the position of get pointer

NOTES

The tell pointer is use to give the current position of the file. The functions tellg() and tellp() have the following prototype position tellg() position tellp()

Here position is the integer value that is capable of holding the largest value that defines the file position.
131 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

The functions seekg() and seekp() have the following prototype istream &seekg(offset,seekdirection); ostream &seekp(offset,seekdirection); From the prototype we can note that both the functions have the same form. The first parameter offset specifies the number of bytes the file pointer has to move from the specified position. The second parameter seekdirection may take any one of the following values. ios::beg ios::cur ios::end seek from the beginning seek from the current position seek from end.

Consider the following examples Table 7.1 File Pointer Positioning SEEK in.seekg(0,ios::beg) in.seekg(0,ios::end) in.seekg(10,ios::cur) in.seekg(-k,ios::end) out.seekp(k,ios::beg) out.seekp(-k,ios:;end) POSITION OF THE FILE POINTER Moves the get pointer to the beginning of file pointed by the stream in Moves the get pointer to the end of file pointed by stream in Moves the get pointer 10 bytes ahead from the current position of the file pointed by stream in Moves the get pointer m bytes before from the end of the file pointed by stream in Moves the put pointer k bytes ahead from the beginning of the file pointed by stream out Moves the put pointer k bytes before the end of the file pointed by stream out

Example 6: The following program opens a random access file in input and output mode and it will allow accessing the specified character in the file.

Anna University Chennai

132

DCS 115

OBJECT ORIENTED PROGRAMMING

#include<iostream.h> #include<fstream.h> int main() { fstream in(test,ios::in | ios :: out); //opens test file in input/output mode char ch; int pos; cout<<ENTER A STRING AT END PRESS #<<endl; do { cin.get(ch); in.put(ch); //write a character to the file } while (ch! =#); in.seekg(0) ; // Goto the beginning of the file; cout<<READING CONTENT FROM THE FILE<<endl; while (in) { out.get(ch); //get a character to the file cout<<ch; } cout<<ENTER THE POSITION OF THE FILE TO READ; cin>>pos; in.seekg(pos,ios::beg); //MOVES THE GET POINTER TO THE POSITION while (in) { out.get(ch); //get a character to the file cout<<ch; } in.close(); } Output of the Program ENTER A STRING AT END PRESS# ANNA UNIVERSITY# READING CONTENT FROM THE FILE ANNA UNIVERSITY# ENTER THE POSITION OF THE FILE TO READ 2 N Have you Understood Questions? 1. What is a random access fle? 2. Write the two seek pointers available in random access files. 3. What do you mean by out.seekp(k,ios::beg) ?
133

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

7.7 Input and Output Operations with Binary Files As mentioned earlier a binary file stores the content in binary format and a binary file can be used to represent any kind of data. Similar to the get and put functions of the text file we have read and write functions in a binary file. The syntax of read and write functions is given below. istream &read(char *buf, streamsize num); ostream &write(const char *buf, streamsize num); The read( ) function reads num bytes from the stream and puts them in the buffer pointed to by buf. The write( ) function writes num bytes to the associated stream from the buffer pointed by buf. The streamsize type is some form of integer. An object of type streamsize is capable of holding the largest number of bytes that will be transferred in any I/O operation. Example 7: This program writes an integer number into a binary file. #include<iostream.h> #include<fstream.h> int main() { ofstream out; out.open(number,ios::binary); //opens a binary file int k=55; out.write((char *)&k,sizeof(k)); //writes integer to the file out.close(); return 0; } In this example a binary file stream is created by specifying ios::binary in the open statement. To write an integer to the file we have used write function, the first parameter to the function is the address of the variable k and the second is the length in bytes. Note: The address of the variable must be casted to the type char *. Example 8: This program reads an integer number from the binary file.

Anna University Chennai

134

DCS 115

OBJECT ORIENTED PROGRAMMING

#include<iostream.h> #include<fstream.h> int main() { ifstream in; in.open(number,ios::binary); //opens a binary file int k; in.read((char *) &k,sizeof(k)); cout<<k; out.close(); return 0; } Output of the Program 55 7.7.1 Reading and Writing Objects in a Binary File

NOTES

We can write a object to a binary file as we do with the primitive data type like int, float etc. Similarly we can also read an object from the binary file. We will still use the read() and write() functions to perform read and write operations. The program given below illustrates reading and writing an object from the binary file. Example 9: #include<iostream.h> #include<fstream.h> class book { char bname[40]; float cost; char aname[40]; int pubid; public: void getdetails(); void printdetails(); }; void book :: getdetails() { cout<<ENTER BOOK NAME<<endl; cin>>bname; cout<<ENTER AUTHOR NAME<<endl;
135 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

cin>>aname cout<<ENTER COST OF THE BOOK<<endl; cin>>cost; cout<<ENTER PUBLISHER ID<<endl; cin>>pubid; } void book :: printdetails() { cout<<BOOK NAME IS <<bname<<endl; cout<<AUTHOR NAME IS<<aname<<endl; cout<<COST OF THE BOOK IS <<cost<<endl; cout<<PUBLISHER ID IS <<pubid<<endl; } int main() { fstream fin; fin.open(book,ios::in||ios::out); int i; book ptr[2]; for(i=0;i<2;i++) { ptr[i].getdetails(); fin.write((char *) &ptr[i],sizeof(ptr[i])); } fin.seekg(0); cout<<PRINTING BOOK DETAILS<<endl; for(i=0;i<2;i++) { fin.read((char *) &ptr[i],sizeof(ptr[i])); ptr[i].printdetails(); } fin.close(); return 0; } Output of the Program ENTER BOOK NAME C++ ENTER AUTHOR NAME Balagurusamy ENTER COST OF THE BOOK

Anna University Chennai

136

DCS 115

OBJECT ORIENTED PROGRAMMING

200 ENTER PUBLISHER ID 101 ENTER BOOK NAME JAVA ENTER AUTHOR NAME H.SCHILDT ENTER COST OF THE BOOK 400 ENTER PUBLISHER ID 102 Output of the Program (Contd..) PRINTING BOOK DETAILS BOOK NAME IS C++ AUTHOR NAME IS Balagurusamy COST OF THE BOOK IS 200 PUBLISHER ID IS 101 BOOK NAME IS JAVA AUTHOR NAME IS H.SCHILDT COST OF THE BOOK IS 400 PUBLISHER ID IS 102 This program creates an array of objects for the class book. The first for loop in the main program reads the details of 2 books. Note that we still use the write() function with the same syntax to write the object to the file. The second for loop reads the content from the file and displays the details. Have you Understood Questions? 1. 7.8 How will you perform read/write operations in binary files? ERROR HANDLING IN FILE OPERATIONS

NOTES

When we are working with files a number of errors may occur. The most common errors that may occur while working with files are listed below Attempting to perform read or write operation on a file that does not exist. Attempting to process the file even after the last byte file of the file is reached. Attempting to write information to a file when opened in read mode. Attempting to store information in file, when there is no disk space for storing more data. Attempting to create a new file with a file name that already exits.
137 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

To overcome from these errors The C++ I/O system maintains status information about the outcome of each I/O operation. The current I/O status of an I/O stream is described in an object of type iostate, which is an enumeration data type defined by ios that includes the members listed in the Table 7.2: Table 7.2 Error bits in iostate ERROR FLAG NAME goodbit failbit eofbit MEANING No errors occurred A non fatal I/O error has occurred End of file has been encountered

There are two ways in which you can obtain the I/O status information. First, we call the rdstate( ) function, which is a member of ios. It has this prototype: iostate rdstate( ); It returns the current status of the error flags. rdstate( ) returns goodbit when no error has occurred. Otherwise, an error flag is returned. The other way you can determine whether an error has occurred is by using one of these ios member functions: bool bad( ); bool eof( ); bool fail( ); bool good( ); The eof( ) function returns true if end of file is reached. The bad( ) function returns true if badbit is set. The fail( ) function returns true if failbit is set. The good( ) function returns true if there are no errors. Otherwise, they return false. We can use all these functions in our file-handling program to minimize the errors. The Example 10 illustrates the usage error bits in file handling. Example 10: This program given below contains all error handling mechanisms. #include<iostream.h> int main() { ifstream in; in.open(text);

Anna University Chennai

138

DCS 115

OBJECT ORIENTED PROGRAMMING

char ch; if(!in) { cout<<CANNOT OPEN FILE<<endl; return 0; } if(in.bad()) { cout<<FATAL ERROR IN FILE<<endl; } cout<<READING CONTENT FROM THE FILE<<endl; while (in) { in.get(ch); //get a character to the file cout<<ch; } in.close(); } This program initially checks whether the file pointed by the stream in exits, if so it will check whether there is any fatal error by using the faction bad().If there is no error the entire content of the file is read and displayed. Have you Understood Questions? 1. 2. Summary A stream is a common, logical interface to various devices of a computer system. A text stream is used with characters. A binary stream can be used with any type of data. No character translation will occur. File I/O in C++ has many classes that include ifstream, ofstream and fstream all these classes are derived from ios. There are many file opening modes that include input,output,appending etc., A sequential file is one in which every record is accessed serially. In C++ every sequential file (including Random access file) will be associated with two file pointers namely get() and put(). The get pointer is an input pointer; it is used to read the content of the file. The put pointer is an output pointer; it is used to write content to the file.
139

NOTES

Which function we use to detect end of file? When will the fail bit set ?

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Random access file is one that allows accessing records randomly in any order The tell function is use to give the current position of the file. The seek function is used to move the file pointer to the specified position. The read and write functions are used perform I/O operations in a binary file. The C++ I/O system maintains status information about the outcome of each I/O operation. The eof( ) function returns true if end of file is reached. The bad( ) function returns true if badbit is set. The fail( ) function returns true if failbit is set. The good( ) function returns true if there are no errors.

Exercises Short Questions 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Draw the hierarchy of C++ IO streams Mention the advantage of using binary files List out the various file opening modes ifstream in(emp.dat); opens the file in ____________________ mode __________ symbol is used to combine file opening modes Mention the use of get() and put() pointers Write the syntax of seekg and seep function. Mention the members of the iostate object To close a file we will call _______________ function. ios :: end is used to position the file pointer at the _________ of the file.

Long Questions 1. Explain random access files also explain how the file pointer is manipulated 2. Write short notes on reading and writing objects in binary files. 3. Explain in detail about error handling functions in files 4. Write short motes on sequential file organization Programming Exercises 1. 2. Write a program to create a file called emp.dat and write employee details into that file Create a file called number.txt and write some numbers to the file. Create files called odd.txt and even.txt and write all the odd numbers to file odd.txt and even numbers to the file even.txt.

Anna University Chennai

140

DCS 115

OBJECT ORIENTED PROGRAMMING

3.

4.

Create a class called sales with your own data members and functions. Create object for the class and write the object to the binary file called sales.dat. Modify program 1 by including all error handling facilities.

NOTES

Answers to Have you Understood Questions Section 7.3 1. A stream is a common, logical interface to various devices of a computer system 2. (1) Binary stream (2) Text stream Section 7.4 1. ifstream, ofstream and fstream. 2. To create an input/output stream we create an object of type fstream. 3. ios::in , ios::out, ios::trunk Section 7.5 1. A sequential file is one in which every record is accessed serially 2. (1) get (2) put pointers Section 7.6 1. Random access file is one that allows accessing records randomly in any order 2. seekg and seep 3. Moves the put pointer k bytes ahead from the beginning of the file pointed by stream out Section 7.7 1. Using read() and write() functions Section 7.8 1. By using eof() function. 2. When a non fatal I/O error has occurred

141

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

References 1. Teach yourself C++ Author: H. Schildt Publisher: Osborne 2000 Object Oriented Programming with C++ Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Problem Solving with C++ (4th edition) Author: Walter Savitch Publisher: Addison Wesley 2002 Computing fundamentals with C++, Object oriented programming & design (2nd edition) Author: Rick Mercer Publisher: MacMillan Press 1995 The C++ Programming Language (3rd. edition) Author : Stroustrup, B., Publisher : Addison- Wesley, 1997. Thinking in C++ Author: Bruce Eckel Publisher : Prentice Hall 2000

2.

3.

4.

5.

6.

Anna University Chennai

142

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 8 TEMPLATES
Function Templates Class Templates Function Templates with Multiple Parameters Class Templates with Multiple Parameters C++ Function Templates Overloading Member Function Templates

8.1 Introduction Generic programming is an approach where generic types are used as parameters. Generic data types are those that can act like a place holders for other data types. In C++ generic programming is done with the help of templates. Template is one of the important features available in C++. Using templates it is possible to create generic classes and generic functions hence templates provides support for generic programming. C++ templates are those that can handle different data types without separate code for each of them. In generic functions or generic classes, the type of data that is operated upon is specified as a parameter. This allows us to use one function or class with several different types of data without having to explicitly recode a specific version for each type of data type. Thus, templates allow you to create reusable code. 8.2 Learning Objectives To introduce the concept of function templates To show how function templates can be used with multiple parameters To discuss function templates overloading To introduce the concept of class templates To discuss class templates with multiple parameters To present the concept of member function templates.
143 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

8.3 Function Templates In many situations, we want to write the same functions for different data types. For an example consider multiplication of two variables. The variable can be integer, float or double. The requirement will be to return the corresponding return type based on the input type. Instead of writing an overloaded function to solve the above problem we can create a C++ function template. When we use C++ function templates, only one function signature needs to be created. The C++ compiler will automatically generate the required functions for handling the individual data types. Thus function templates make programming easy. A function template or generic function defines a general set of operations that will be applied to various types of data. A function template has the type of data that it will operate upon passed to it as a parameter. Using this mechanism, the same general procedure can be applied to a wide range of data; hence templates are also called as parameterized functions or classes. A function template is created by using the keyword template. The general form of a template function definition is as template <class T> returntype functionname(parameter list) { // body of function } Here the type T acts as a placeholder name for the data type used by the function, the variable T belongs to generic data type. The compiler will automatically replace this placeholder with an actual data type when it creates a specific version of the function. Example 1: The following example declares add() function that will add two values of any given data type. //FUNCTION TEMPLATES #include <iostream.h> template <class T> void add(T &a,T &b) { T c; c= a+b; cout<<THE SUM IS: <<c<<endl; }

Anna University Chennai

144

DCS 115

OBJECT ORIENTED PROGRAMMING

int main() { int a=10,b=20; add(a,b); float c=12.5,d=13.8; add(c,d); } In this example the keyword template is used to create template function add(). Here the variable T is used as a placeholder name for the data type .The function add() performs the addition of two numbers. In the main program the function add is called with two different set of data types i.e. int and float. Since add() is a template function the complier creates two version of add() function one to perform addition of integers and another to perform addition of two floats. Example 2: This example of function templates takes input parameters and return values. //FUNCTION TEMPLATES WITH RETURN VALUES #include <iostream.h> template <class T> T small(T &a,T &b) { if(a>b) return b; else return a; } int main() { int a,b; cout<<ENTER TWO INTEGERS<<endl; cin>>a>>b; cout<<SMALLEST INTEGER IS <<small(a,b); double m,n; cout<<ENTER TWO REAL NUMBERS<<endl; cin>>m>>n; cout<<SMALLEST REAL NUMBER IS <<small(m,n); return 0; }

NOTES

145

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

8.3.1

Function Templates with Multiple Parameters

A template function can take multiple parameters that may vary in their data types. The list of parameters that are passed to the template function are separated using commas. The general form of the template function with multiple parameters is given below. template <class T1,class T2,.> returntype functionname(parameter list of types T1,T2) { // body of function } Example 3: The following code snippet gives details regarding the function template with multiple parameters. //FUNCTION TEMPLATES WITH MULTIPLE PARAMETERS #include<iostream.h> template <class T1,class T2> void power(T1 &a,T2 &b) { T1 p=1; int i; for(i=1;i<=b;i++) { p=p*a; } cout<<a<< RAISED TO THE POWER <<b<< IS = <<p<<\n; }

void main() { power(3.5,5) power(5,5); } In this example the generic function power() raise a base a to the power b. Here we can note that this function takes two parameters. In the main program the first line power (3.5.5) will raise the float value 3.5 to the integral power 5 i.e. it computes 3.55. The second line power(5,5)will raise the integer value 5 to the
Anna University Chennai 146

DCS 115

OBJECT ORIENTED PROGRAMMING

power 5 i.e. it computes 55.Thus we can see that it is possible to have a template function with multiple parameters. Example 4: This example creates a generic function with multiple parameters that performs recursive binary search on a linear array. //Generic functions to perform Binary Search #include<iostream.h> template <class T1,class T2> bsearch( T1 &a[], T2 &e, int start, int end) { int mid; if(start>end) return -1; mid=(start+end)/2; if(e==a[mid]) return mid; else if(e<a[mid]) return bsearch(a,e,start,mid-1); else return bsearch(a,e,mid+1,end); } void main() { int n,pos; int a[100],element; cout<<Enter the array limit\n; cin>>n; cout<<Enter the array elements; for(i=0;i<n;i++) cin>>a[i]; cout<<Enter the element to be searched cin>>element; pos=bsearch(a,element,0,n); if(pos==-1) cout<<Element not found; else cout<<Element is found in position<<pos+1; }

NOTES

147

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

8.3.2

C++ Function Templates Overloading

You can overload a template function as you do with the normal C++ function. If you call the name of an overloaded function template, the compiler will try to deduce its template arguments and check its explicitly declared template arguments. If successful, it will instantiate a function template specialization. Errors will be generated if no match is found. Example 5: This example performs function templates overloading. //TEMPLATE FUNCTION OVERLOADING #include<iostream.h> template <class T1,class T2> T add(T1 &a,T2 &b) { T c; c=a+b; return c; } template <class T1,class T2,class T3> T add(T1 &a,T2 &b,T3 &c) { T d; d=a+b+c; return d; } void main() { int x; x=add(12,13); float y; y=add(12.5,10.2.15.8); cout<<SUM OF TWO INTEGERS<<x; cout<<SUM OF THREE FLOATS<<y; } Two overloaded set of the template function add() exists in this program. If the add() function is invoked with two parameters then the template function having two parameters is invoked, if the add() function is called with three parameters then the template function having three parameters is invoked.
Anna University Chennai 148

DCS 115

OBJECT ORIENTED PROGRAMMING

You can also overload a template function with a non template function. Always a non template function takes precedence over template functions. Consider the example given below. Example 6: This example performs overloading of template function with a non template function. //TEMPLATE FUNCTION OVERLOADING #include<iostream.h> template <class T> void square(T &x) { cout<<TEMPLATE FUNCTION; cout<<SQUARE VALUE IS <<x * x; } void square(int x) { cout<<NON TEMPLATE FUNCTION; cout<<SQUARE VALUE IS <<x * x } void main() { int a=10; square(a); //INVOKES NON TEMPLATE FUNCTION float b=12.5; square(b); //INVOKES TEMPLATE FUNCTION } The output of the program will be Thus we can note that when the function square is called with an integer parameter it invokes the non template function whereas when the same function is invoked with a float parameter it calls the template function. Have you understood? 1. 2. 3. 4. What do you mean by Generic programming? What do you mean by function templates? Write the syntax for creating function templates. How overloaded function template is called?

NOTES

149

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

8.4

Class Templates

C++ Class Templates are used where we have multiple copies of code for different data types with the same logic. For example we create a template for an queue class that would enable us to create queue to hold data items of different data types like int, float, double etc., Templates can be used to define generic classes. A class template definition looks like a regular class definition, except it is prefixed by the keyword template. A parameter should be included inside angular brackets. The parameter inside the angular brackets, can be either the keyword class or typename. This is followed by the class body declaration with the member data and member functions. The syntax to declare the class template is given below //C++ class template template <class T> class classname { //member variable declarations of type T and other types //member function declarations }; Example 7: The following is a simple example of class templates //SIMPLE C++ CLASS TEMPLATE #include<iostream.h> template <class T> class calc { T a,b; public: calc(T x,T y) { a=x; b=y; } void add() { cout<<SUM IS << a+b; } T mul() { return a*b;
Anna University Chennai 150

DCS 115

OBJECT ORIENTED PROGRAMMING

} }; void main() { calc<int> obj(10,10); obj.add(); int c; c=obj.mul(); cout<<PRODUCT IS <<c; } This class template is designed to perform simple addition and multiplication for all data types. You can note that this template class resembles ordinary c++ class except the template declaration. Just look at the line that creates the object calc<int> obj(10,10); The int parameter within the angular brackets specifies that object obj will be working on integer parameters. You can note that the member functions are called in the same way as you do with the ordinary classes. Example 8: The program given below creates a generic stack and performs all basic stack operations. //GENERIC STACK #include<iostream.h> #include<iomanip.h> #define SIZE 10 template <class T> class template_stack { T stack[SIZE]; int top; int status,data,choice; template_stack() { top=-1; } int push(int data) { if(isFull())
151

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

return -1; stack[top]=data; top++; return 1; } int pop() { int d; if(isEmpty()) return -1; d=stack[top]; top; return d; } int peek() { if(isEmpty()) return -1; return stack[top]; } int isEmpty() { if(top==-1) return 1; else return 0; } int isFull() { if(top==SIZE-1) return 1; else return 0; } int size() { return top+1; } } void main() { template_stack<int> stk; int status;

Anna University Chennai

152

DCS 115

OBJECT ORIENTED PROGRAMMING

do { cout<<1PUSH; cout<<2POP; cout<<3PEEK; cout<<4->SIZE cout<<5EXIT; cout<<Enter Ur Choice\n; cin>>ch; switch(ch) { case 1: cout<<Enter the data to insert); cin>>data; status=stk.push(data); if(status==-1) cout<<Full Stack<<endl; else cout<<data<< Successfully Inserted; break; case 2: status=stk.pop(); if(status==-1) cout<<Empty Stack<<endl; else cout<< Data Popped is <<status; break; case 3: status=stk.peek(); if(status==-1) cout<<Empty Stack<<endl; else cout<<The Top Element in the Stack is<<status; break; case 4: cout<<The Size of the Stack is <<stk.size(); break; case 5: cout<<Bye; exit(0); default: cout<<Invalid Choice<<endl; } }while(1); }
153

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

8.4.1

Class Templates with Multiple Parameters

Like function templates a class template can also take multiple parameters. Thus it is possible to use more than one generic data type in a class template. The list of parameters that are passed to the class template are separated using commas. The general form of the is given below template <class T1,class T2,.> class classname { //body of the class } Example 9: The following code is an example for class templates with multiple parameters #include<iostream.h> #include<iomanip.h> template <class T1,class T2> class disp { T1 x; T2 y; public: disp(T1 a,T2 b) { x=a; y=b } void print() { for(int i=0;i<x;i++) cout<<y<<\t; } } void main() { disp<int,char> obj(5,a); obj.print(); disp<int,float> obj(5,1.1); obj.print(); }
Anna University Chennai 154

DCS 115

OBJECT ORIENTED PROGRAMMING

8.4.2

Member Function Templates

NOTES

So far in our class templates discussions we have used only inline functions in the class but it is still possible to write a member function definition outside the template class. The syntax is template <class T> returntype classname<T> :: functionname(parameter list) { //body of the function } Example 10: The program given in the previous example is modified using member function templates. #include<iostream.h> #include<iomanip.h> template <class T1,class T2> class disp { T1 x; T2 y; public: disp(T1 a, T2 b); void print(); }; template <class T1,class T2> disp<T> :: disp(T1 a,T2 b) { x=a; y=b; } template <class T1,class T2> void disp<T> :: print() { for(int i=0;i<x;i++) cout<<y<<endl; } void main() { disp<int,char> obj(5,a); obj.print();
155 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
}

disp<int,float> obj(5,1.1); obj.print();

Have you understood? 1. When you will create a class template? 2. Write the syntax for creating class templates. Summary Generic programming is an approach where generic types are used as parameters. In C++ generic programming is done with the help of templates. A function template or generic function defines a general set of operations that will be applied to various types of data. A template function can take multiple parameters that may vary in their data types. You can overload a template function as you do with the normal C++ function. C++ Class Templates are used where we have multiple copies of code for different data types with the same logic Templates can be used to define generic classes. Like function templates a class template can also take multiple parameters. Thus it is possible to use more than one generic data type in a class template. Exercises Short Questions 1. How templates provide reusability of code? 2. How templates function differs from function overloading? 3. Function templates can return values (True/False) 4. Write the syntax for a template function taking multiple parameters 5. Explain Generic classes 6. Is it possible to use more than one generic data type in a class template? Long Questions 1. Explain overloading template function with example. 2. Explain class templates with an example Programming Exercises 1. Create a function template to perform bubble sort for generic type 2. Create a overloaded function template to compute area of different objects 3. Create a class template to implement Queue ADT 4. Create a class template called Complex and add member functions called add() , substract() and multiply() to perform the basic arithmetic operations on it.
Anna University Chennai 156

DCS 115

OBJECT ORIENTED PROGRAMMING

5. Create a class template called Rational add perform basic arithmetic operations (Note: Rational number will be in the form a/b (b <> 0) ) Answers to Have you Understood Questions Section 8.3 1. Generic programming is an approach where generic types are used as parameters. In C++ generic programming is done with the help of templates. 2. A function template or generic function defines a general set of operations that will be applied to various types of data. 3. The syntax is template <class T> ret-type-name(parameter list) { // body of function } 6. The function template is overloaded, the compiler will try to deduce its template arguments and check its explicitly declared template arguments. If successful, it will instantiate a function template specialization. Errors will be generated if no match is found. Section 8.4 1. C++ Class Templates are used where we have multiple copies of code for different data types with the same logic 2. The syntax is template <class T> class classname { //member variable declarations of type T and other types //member function declarations };

NOTES

157

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

References 1. Teach yourself C++ Author: H. Schildt Publisher: Osborne 2000 Object Oriented Programming with C++ Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Problem Solving with C++ (4th edition) Author: Walter Savitch Publisher: Addison Wesley 2002 Computing fundamentals with C++, Object oriented programming & design (2nd edition) Author: Rick Mercer Publisher: MacMillan Press 1995 The C++ Programming Language (3rd. edition) Author : Stroustrup, B., Publisher : Addison- Wesley, 1997. Thinking in C++ Author: Bruce Eckel Publisher : Prentice Hall 2000

2.

3.

4.

5.

6.

Anna University Chennai

158

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 9
EXCEPTION HANDLING
Exception Types Multiple Catch Statements Exception Handling Mechanism Catching All Exceptions Functions Generating Exceptions Catching All Exceptions Throwing Mechanisms Specifying (Restricting) Exceptions Catching Mechanisms Rethrowing Exceptions

9.1 Introduction Generally programmers may commit some errors. Errors can be classified in two categories. They are Compile time errors and Run time errors. Compile time errors usually comprise of syntax errors such as a missing semicolon, unbalanced parenthesis etc., they can be easily detected when we compile our program but Runtime errors are relatively difficult to detect and rectify it. To solve this C++ provides a build-in error handling mechanism that is called exception handling. Using the C++ exception handling mechanism we can easily identify and respond to run time errors. This chapter briefly explores the various exception handling mechanisms available in C++. 9.2 Learning Objectives To discuss the different types of exceptions To introduce exception handling mechanism available in C++ To discuss how to handle exceptions generated by a function To present throwing mechanisms To present catching mechanisms To discuss creating catches for a single try To show how to catch all exceptions To discuss about restricting exceptions
159 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

To discuss about rethrowing exceptions

9.3 Exception Types Exceptions can be classified into two categories. They are Synchronous Exception Asynchronous Exception.

Exceptions that are within the control of the program are called synchronous exceptions for example referring to an index of array, out of the range index. Exceptions that are beyond the control of program is said to be asynchronous exceptions for example memory overflow interrupt. C++ exception handling mechanism works only for synchronous exception. To handle synchronous exceptions we have to follow the following steps Identify the problem(error) Report the error Receive the error Rectify the error.

The first step to handle exceptions is to identify the block of code that may cause error. After identifying it report the error to the error handling routine by throwing it. The error handling routine will receive and process the error. Have you understood? 1. Give some examples for compile time errors. 2. What are the two categories of exceptions? 3. Mention the steps to handle synchronous exceptions. 9.4 Exception Handling Mechanism C++ exception handling mechanism is built upon three important keywords. They are try catch throw The program statements that we suspect that they may cause runtime are put in the guarded section called try block. If the exception occurs in the try block it is thrown to the catch block. The catch block catches the thrown exception and handles it appropriately. The general form of the try catch structure is
Anna University Chennai 160

DCS 115

OBJECT ORIENTED PROGRAMMING

try { //try block } catch(type1 arg) { //catch block } When any statement present in the try block causes an exception (i.e error) the program control leaves the try block without executing further statements and switches to the catch block. The catch block will have the necessary program statements to handle the error. In C++, exceptions are treated as objects. Hence when an exception is created and thrown the corresponding catch block (the catch that has the type which matches with the object) will catch the exception and handle it otherwise, the exception will be left unhandled and an abnormal program termination may occur. The general form of a throw statement is throw exception; throw must be executed either from within the try block or from any function that the code within the block calls (directly or indirectly). Example 1: The following is a simple example with try catch block. #include<iostream.h> int main() { int i,j; cout << Starts here\n; i=10; j=0; try { // start a try block cout << Inside try block\n; if(j==0) { throw j; // throw an error
161

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

cout << This will not be printed \n; } cout<<RESULT IS <<i/j; } catch( int a) { // catch an error cout << The Number Caught is : ; cout << a << \n; } cout << Ends here; return 0; }

When the program enters the try block it is said to be in the guarded section. In this program when the value of j is zero an exception is created and thrown note that the statements after throw statement in try block is not executed. Once the exception is thrown the catch block catches the value (here zero) and handles it. After that the program continues it normal execution. Thus we can see that in C++ the exceptions are handled using the following steps. Control reaches the try statement by normal sequential execution. The guarded section within the try block is executed If no exception is thrown during execution of the guarded section, the catch clauses that follow the try block are not executed. If an exception is thrown during execution of the guarded section or in any routine the guarded section calls (either directly or indirectly), an exception object is created from the object created by the throw operand. The catch handler that matches the exception object is selected and it is executed. When there is no matching catch handler the exception will be left unhandled and an abnormal program termination may occur.

Have you understood? 1. Give the general form of try catch block. 2. When will the catch block gets executed ? 3. Give the general form of throw statement 9.5 Functions Generating Exceptions

C++ allows functions to generate exceptions. However these functions cannot be called as an ordinary function. To call a function generating exception, you have to enclose the function call with a try catch block.

Anna University Chennai

162

DCS 115

OBJECT ORIENTED PROGRAMMING

Example 2: The function compute() given in this example generates and throws exceptions. #include<iostream.h> #include<iomanip.h> void compute(int a,int b) { int c; if(b==0) throw b; c=a/b; cout<<RESULT OF THE DIVISION<<c; } void main() { int x,y; cout<<ENTER TWO NUMBERS<<endl; cin>>x>y; try { compute(x/y); } catch(int k) { cout<<DIVIDE BY ZERO EXCEPTION<<endl; } } Here we can note that the call to the function compute() is enclosed within the try catch block. If the value of the dividend b is zero the function generates an exception, which is handled in the catch block kept in the main program. Have you understood? 1. How will you call a function that generates exception? 9.6 Throwing Mechanisms An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block. A throw expression accepts one parameter, which is passed as an argument to the exception handler. The throw statement will have the following form
163

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

throw (exception) throw exception throw If an exception is thrown during execution of the guarded section or in any routine the guarded section calls (either directly or indirectly), an exception object is created from the object created by the throw operand. Now, the compiler looks for a catch clause that can handle an exception of the type thrown or a catch handler that can handle any type of exception. The catch handlers are examined in order of their appearance following the try block. If no appropriate handler is found, the next enclosing try block is examined. This process continues until the outermost enclosing try block is examined. Have you understood? 1. Mention the different form of throw statement 2. How catch handlers are examined in a try block. 9.7 Catching Mechanisms The general form of the catch statement is catch(type arg) { //catch block } The catch statement used is determined by the type of the exception. That is, if the data type specified by a catch, matches that of the exception, that catch statement is executed (all other are bypassed). When an exception is caught, arg will receive its value. If you dont need access to the exception itself, specify only type in the catch clause (arg is optional). Any type of data can be caught, including classes that you create Have you understood? 1. Give the general form of catch block. 9.8 Multiple Catch Statements A try can have multiple catches, if there are multiple catches for a try, only one of the matching catch is selected and that corresponding catch block is executed. The syntax for try with a multiple catch is given below.

Anna University Chennai

164

DCS 115

OBJECT ORIENTED PROGRAMMING

try { any statements if (some condition) throw value1; else if (some other condition) throw value2; ... ... ... else if (some last condition) throw valueN; }catch (type1 name) { any statements } catch (type2 name) { any statements } ... ... ... catch (typeN name) { any statements } Throw generates the exception specified by the corresponding value. This value can be of any type and multiple throw statements might occur. When an exception is thrown, it is caught by the corresponding catch statement, which then processes the exception. If there are more than one catch statement associated with a try. The type of the exception determines which catch statement is used. When an exception is caught, name (the argument of the catch statement) will receive the thrown value. This thrown value determines which catch block will be executed. Sometimes the arguments of several catch statements match the type of an exception, in that case the first matching catch handler block is selected and executed. A simple example for try with multiple catches is given below.
165

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Example 3: The following example has a single try with multiple catches. #include<iostream.h> #include<iomanip.h> void multiple_catch(int value) { try { if (value==0) //throw an int value throw 1; else if (value==1) //throw a char throw a; else //throw float throw 1.1; } catch(char c) { cout<<Character value is thrown <<c; } catch(int i) { cout<<Integer value is thrown<<i; } catch(float f) { cout<<Float value is thrown<<f; } } void main() { cout<<Main Program<<endl; multiple_catch(0); multiple_catch(1); multiple_catch(5); }

Anna University Chennai

166

DCS 115

OBJECT ORIENTED PROGRAMMING

Have you understood? 1. A try can many catch (True/False) 2. If a try has multiple catches, how many catch block gets executed. 9.9 Catching All Exceptions In some circumstances, it might be useful to catch all exceptions, instead of just a certain type. This situation may occur when we to write a program to handle all possible exceptions. To achieve this C++ supports a unique catch statement (catch with three dots) that can catch all exceptions. The syntax for the catch statement is try { //statements }catch (...) { do something } Example 4: The following code snippet contains the catch statement that can catch all exceptions. #include<iostream.h> #include<iomanip.h> void multiple_catch(int value) { try { if (value==0) //throw an int value throw 1; else if (value==1) //throw a char throw a; else //throw float throw 1.1;
167

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

} catch( ) { cout<<Exception is Caught!!! <<endl; } } void main() { cout<<Main Program<<endl; multiple_catch(0); multiple_catch(1); multiple_catch(5); } Have you understood? 1. Write the syntax of the catch handler that can catch all exceptions

9.10 Specifying (Restricting) Exceptions The type of exceptions that a function can throw can be restricted to certain types. To accomplish these restrictions, a throw clause must be added to the function definition. The throw clause specifies the possible list of types a function can throw. The syntax is given below. returntype func-name(arg-list) throw(type-list) { //body of the function } Only the types in the comma separated type-list can be thrown by the function. Throwing any other type will cause abnormal program termination. Example 5: This example program restricts exceptions for the function multiple_catch().
Anna University Chennai 168

DCS 115

OBJECT ORIENTED PROGRAMMING

#include<iostream.h> #include<iomanip.h> void multiple_catch(int value) throw (int,char,double) { try { if (value==0) //throw an int value throw 1; else if (value==1) //throw a char throw a; else //throw float throw 1.1; } catch(char c) { cout<<Character value is thrown <<c; } catch(int i) { cout<<Integer value is thrown<<i; } catch(float f) { cout<<Float value is thrown<<f; } } void main() { cout<<Main Program<<endl; multiple_catch(0); multiple_catch(1); multiple_catch(5); } Have you understood? 1. How will you restrict functions that generates exceptions?
169

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

9.11 Rethrowing Exceptions Sometimes an exception handler may not wish to process the exception instead it wishes to throw the exception. If an exception needs to be rethrown from within an exception handler, this can be done by calling throw statement without any parameter. The syntax is try { . . } catch (char c) { throw; //rethrow same exception } Exceptions can be rethrown only within the catch block. When we rethrow an exception the same catch statement will not catch it again. Have you understood? 1. Write the syntax of rethrowing exceptions. 2. Is it possible to rethrow an exception outside catch block ? Summary Errors cane be classified in two categories they are Compile time errors and Run time errors. Exceptions can be classified as Synchronous and Asynchronous exceptions. C++ exception handling mechanism is built upon three important keywords. They are try, catch and throw. When any statement present in the try block causes an exception (i.e error) the program control leaves the try block without executing further statements and switches to the catch block.
170

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

In C++, exceptions are treated as objects Throw statement must be executed either from within the try block or from any function that the code within the block calls (directly or indirectly). C++ allows functions to generate exceptions If an exception is thrown during execution of the guarded section or in any routine the guarded section calls (either directly or indirectly), an exception object is created from the object created by the throw operand. The catch handlers are examined in order of their appearance following the try block. The catch statement used is determined by the type of the exception A try can have multiple catches, if there are multiple catches for a try, only one of the matching catch is selected and that corresponding catch block is executed. C++ supports a unique catch statement (catch with three dots) that can catch all exceptions. The type of exceptions that a function can throw can be restricted to certain types. To accomplish these restrictions, a throw clause must be added to the function definition. The throw clause specifies the possible list of types a function can throw. If an exception needs to be rethrown from within an exception handler, this can be done by calling throw statement without any parameter.

NOTES

Exercises Short Questions 1. 2. 3. 4. 5. 6. How does compile time errors differs form run time errors Memory overflow is an example for ___________ What do you mean by asynchronous exceptions Write the three keywords used to handle exceptions Explain guarded section The number of try and catch statements in a c++ program should be the same (True/False) 7. How will you catch all exceptions? 8. Is it possible to restrict exceptions generated from a function?
171 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Long Questions 1. Explain the exception handling statements in detail 2. Explain the different form of throw statement. 3. Discuss restricting exception generated by a function Programming Exercises 1. Write a program to read array from a keyboard. Accept the index from the user and retrieve the element present in that index. Include exception handling facilities. 2. Create your own program to handle divide by zero exceptions Answers to Have you Understood Questions Section 9.3 1. Syntax errors such as a missing semicolon, unbalanced parenthesis etc., 2. Exceptions can be classified as Synchronous and Asynchronous exceptions. 3. To handle synchronous exceptions the following steps are involved Identify the problem(error) Report the error Receive the error Rectify the error. Section 9.4 1. The general form of the try catch structure is try { //try block } catch(type1 arg) { //catch block } When any statement present in the try block causes an exception (i.e error) the program control leaves the try block without executing further statements and switches to the catch block.

2.

Anna University Chennai

172

DCS 115

OBJECT ORIENTED PROGRAMMING

3. throw exception. Section 9.5 1. By enclosing the function call in try catch block. Section 9.6 1. The different form are (1) throw (exception) (2) throw exception (3) throw 2. The catch handlers are examined in order of their appearance following the try block. If no appropriate handler is found, the next enclosing try block is examined. This process continues until the outermost enclosing try block is examined.

NOTES

Section 9.7 1. The general form of the catch statement is catch(type arg) { //catch block }

Section 9.8 1. True 2. one Section 9.9 1. try { //statements }catch (...) { do something } Section 9.10 1. The type of exceptions that a function can throw can be restricted to certain types. To accomplish these restrictions, a throw clause must be added to the function definition. The throw clause specifies the possible list of types a function can throw.
173 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Section 9.11 1. The syntax is try { . . } catch (char c) { throw; //rethrow same exception 2. } No

References 1. Teach yourself C++ Author: H. Schildt Publisher: Osborne 2000 Object Oriented Programming with C++ Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Problem Solving with C++ (4th edition) Author: Walter Savitch Publisher: Addison Wesley 2002 Computing fundamentals with C++, Object oriented programming & design (2nd edition) Author: Rick Mercer Publisher: MacMillan Press 1995 The C++ Programming Language (3rd. edition) Author : Stroustrup, B., Publisher : Addison- Wesley, 1997. Thinking in C++ Author: Bruce Eckel Publisher : Prentice Hall 2000

2.

3.

4.

5.

6.

Anna University Chennai

174

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 10 INTRODUCTION TO JAVA PROGRAMMING


10.1 Java Features Operators Java Virtual Machine Expressions Writing Java Source Code Data Types Java Tokens Variables Declaration Keywords Constants Identifiers Java Statements Literals Command Line Arguments Introduction

Java is an object oriented language developed by Sun Microsystems. Around 1990 James Gosling, Bill Joy and others at Sun Microsystems began developing a language called Oak. Oak language was primarily developed to control microprocessors embedded in consumer items like PDAs for this language should be a platform independent, reliable and compact language. But however due to the sudden explosion of Internet and similar technologies, Sun Microsystems changed their project objectives and renamed the Oak language into Java. In 1994 the project team developed a web browser called HotJava capable of locating and running applets, a java program that can run on a web browser.
175 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

The earlier versions of java were not so powerful but now Java has became a common language to develop applications like on line web stores, transactions processing, database interfaces etc., java has also become quite common on small platforms such as cell phones and PDAs. Java is now used in several hundred cell phone models. This chapter explores the various fundamental programming concepts of Java. 10.2 Learning Objectives 10.3 To understand the various features of Java To introduce Java Virtual Machine To show how to write, compile and execute Java programs. To present the tokens of Java language To discuss expressions and data types present in Java To understand statements of Java.

Java Features

Java is a high level language looks much similar to C, C++ but it offers many unique features that are not available in most of modern programming language. Java language has the following features. Compiled and Interpreted Platform Independence Object Oriented Robust Security Automatic Memory Management Dynamic Binding High Performance Multithreaded Some features in C/C++ eliminated

Compiled and Interpreted Java compiler converts the source code into intermediate byte code instructions. Java Interpreter converts these bytes codes into machine executable statements. Thus we can say java is both compiled and interpreted language. The two steps of compilation and interpretation allow for extensive code checking and improved security
Anna University Chennai 176

DCS 115

OBJECT ORIENTED PROGRAMMING

Platform Independence Java programs are capable of running on all platforms hence java programs possess Write-Once-Run-Anywhere feature Object Oriented Java is purely an object oriented language. In Java no coding outside of class definitions is allowed, including the main() function. Java supports an extensive class library available in the core language packages. Robust Java is a robust language. It provides the following facilities to ensure reliable code Built in Exception Handling Strong type checking both at compile and runtime. Local variables must be initialized Security Java is a highly secured language. Java programs will run only within the Java Virtual Machine (JVM) sandbox thus threats from malicious programs is minimized. Java does not support pointers hence direct memory access is not allowed. Java supports a built in security manager that determines what resources a class can access such as reading and writing to the local disk. Automatic Memory Management Java supports automatic memory management. Java Virtual machine (JVM) performs garbage collection automatically to claim the memory occupied by unused objects. Dynamic Binding Java is a dynamic language. The linking of data and methods occurs only at run time. In java new classes can be loaded even when the program is on execution. High Performance Interpretation of bytecodes slowed performance in early versions, but advanced virtual machines with adaptive and just-in-time compilation and other techniques now typically provide improved performance.
177

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Multithreaded In java it possible to write programs to handle multiple tasks simultaneously. To write such programs you have to create light weight processes called Threads in java. The threads thus created can be executed simultaneously. Multithreaded programs are useful when you write programs for networking and multimedia. Some Features in C/C++ Eliminated Some features in C/C++ are eliminated in java. They are listed below. No Pointers No Preprocessor Directives No Multiple Inheritance in Classes No template Classes Have you understood? 1. Explain how java program gets executed. 2. Justify the statement Java programs are secure 3. List out the features that are eliminated in Java but available in C++. 10.4 Java Virtual Machine

You have learnt that java is a platform independent and architectural neutral language. These features are provided by the java run time environment called Java Virtual Machine (JVM).When a java program is compiled it will not produce a machine code instead it produces an intermediate byte code for the JVM. When you run the java program the byte code produced for the JVM will be interpreted by the java run time interpreter. This interpreter converts the byte code to the executable machine code for the machine that runs the java program. The process of compilation and execution is shown below.

Anna University Chennai

178

DCS 115

OBJECT ORIENTED PROGRAMMING

JAVA PROGRAM

NOTES

JAVA COMPILER

BYTE CODE

Compilation Process
BYTE CODE

JAVA INTERPRETOR

MACHINE CODE

Execution Process The byte code produced by the java compiler for the JVM is common to all platforms hence byte code is platform independent. 10.4.1 Writing Java Source Code Writing java source code is similar to writing a source code in C++ but with some variations. Writing Java source code is dealt in detail in subsequent chapters. Now lets start our discussion by writing a simple java program.The following is a simple java program. The source code is written in the file named Welcome.java 1. 2. 3. 4. 5. class Welcome { public static void main(String args[]) { // The following line is used to display a line of text System.out.println(Welcome to Java world ); 6. } 7. } To compile this program you have to use the javac compiler. The syntax to compile is
179 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

javac filename.java

To compile this program you have to type javac welcome.java in the command prompt. This will create a class called welcome.class which contains the byte code representation of the program. To run the java program you have to use the java interpretor. The syntax to run is

java classname

The First line of this program has the class declaration, as mentioned earlier every code written in java should be kept inside a class definition. The third line declares the main() method in java. The main() method in java should be declared public and static .Usually the return type of the main method is void. In java main() method should be declared public because main() method should be made accessible to all other classes main() method is declared static because the main() method belongs to the class not to a specific object System.out.println() is a statement used to display some text to the user. It is similar to cout statement in C++.

Example 1: The code listed below performs addition of two integer numbers. class sum { public static void main(String args[]) { int i=10,j=25; k=i+j; System.out.println(THE SUM IS +k); } } In this example you have declared two integer variables i and j .The + operator used in the System.out.println() is concatenation operator.
Anna University Chennai 180

DCS 115

OBJECT ORIENTED PROGRAMMING

Have you understood? 1. What is a byte code? 2. How will you compile and run your Java program? 3. Mention the statement used to display a message 10.5 Java Tokens

NOTES

As mentioned in chapter 1 tokens are the basic lexical elements of any programming language In Java every statement is made up of smallest individual elements called tokens. Tokens in java include the following Keywords Identifiers Literals Operators

10.5.1 Keywords The list is of keywords available in java are given below. Every keyword will perform a specific operation in java. As mentioned in chapter 1 keywords cannot be redefined by a programmer; further keywords cannot be used as identifier name.

Abstract Assert Boolean Break Byte Case Catch Char class const

continue default do double else enum extends final finally float

For Goto If implements Import instanceof Int Interface Long Native

new package private protected public return short static strictfp super

switch synchronized this throw throws transient try void volatile while

In Java the keyword const, goto are not used The keyword assert is added in version 1.4 The keyword enum is added in version 5.0

181

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

10.5.2

Identifiers

Every named program componentclass, package, function or variable must have a legal identifier (or name). An identifier in java has the following rules An identifier can contain alphanumeric characters, but it should begin with an alphabet. Identifiers are case sensitive(i.e. upper and lower cases are different) Underscore and dollor sign are two special character allowed. The following are legal identifiers Find_3 Message abc$ A23C

The following are the invalid identifiers 33pages bob@gmail 10.5.3 Literals

A literal is a program element that represents an exact (fixed) value of a certain type. Java language supports the following type of literals 10.5.4 Integer Literals (Ex. 123) Floating point Literals(Ex. 88.223) Character Literals (Ex. . , a , \n) String Literals (Ex. Hello World) Boolean Literals (Ex. True,false) Operators

Java is a language that is rich in operators. The list of operators supported in java is given below. Simple Assignment Operator = + Simple assignment operator Additive operator (also used for String concatenation) Subtraction operator
182

Arithmetic Operators

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

* / %

Multiplication operator Division operator Remainder operator

NOTES

Unary Operators + ++ ! Unary plus operator; indicates positive value (numbers are positive without this, however) Unary minus operator; negates an expression Increment operator; increments a value by 1 Decrement operator; decrements a value by 1 Logical compliment operator; inverts the value of a boolean

Equality and Relational Operators == != > >= < <= Equal to Not equal to Greater than Greater than or equal to Less than Less than or equal to

Conditional Operators && || ?: Conditional-AND Conditional-OR Ternary (shorthand for if-then-else statement)

Type Comparison Operator instanceof Compares an object to a specified type

Bitwise and Bit Shift Operators ~ << >> >>> & ^ | Unary bitwise complement Signed left shift Signed right sift Unsigned right shift Bitwise AND Bitwise exclusive OR Bitwise inclusive OR

The operator precedence table is given below in the Table 10.1.

183

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
postfix unary

Operator Precedence Operators Precedence


expr++ expr ++expr expr +expr -expr ~ ! */% +<< >> >>> < > <= >= instanceof == != & ^ | && || ?: = += -= *= /= %= &= ^= |= <<= >>= >>>=

multiplicative additive shift relational equality bitwise AND bitwise exclusive OR bitwise inclusive OR logical AND logical OR ternary assignment

Table 10.1 Operators and Precedence in Java Have you understood? 1. List the Java tokens 2. Which of the following is not a Java keyword (a) abstract (b)class (c) method (d) strictfp 3. Write the rules for naming an identifier. 4. Write any two bitwise operator 5. Logical AND has higher priority over logical OR (True/False) 10.6 Expressions Java is an expression based language. In Java expressions are used to implement some computation. Expressions in java can be either a simple expression or a complex expression. A simple expression may be a value assigned to variable complicated expression is composed of an operator applied to one or more operands, all of which are also expressions. In Java expressions takes the general form variable=expression;
Anna University Chennai 184

DCS 115

OBJECT ORIENTED PROGRAMMING

For Example x=a+b; y=a*(b+c)/(m+n)*f a+=b Have you understood? 1. What is an expression? 10.7 Data Types Java supports the following list of data types. They are boolean 1-bit. May take on the values true and false only. true and false are defined constants of the language and are not the same as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value. Booleans may not be cast into any other type of variable nor may any other variable be cast into a boolean. byte 1 signed byte (twos complement). Covers values from -128 to 127. short 2 bytes, signed (twos complement), -32,768 to 32,767 int 4 bytes, signed (twos complement). -2,147,483,648 to 2,147,483,647. Like all numeric types ints may be cast into other numeric types (byte, short, long, float, double). When lossy casts are done (e.g. int to byte) the conversion is done modulo the length of the smaller type. long 8 bytes signed (twos complement). Ranges from -9, 223, 372, 036, 854, 775, 808 to +9, 223, 372, 036, 854, 775, 807. float 4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Like all numeric types floats may be cast into other numeric types (byte, short, long, int, double). When lossy casts to integer types are done (e.g. float to short) the fractional part is truncated and the conversion is done modulo the length of the smaller type.
185

NOTES
//Simple expression //Complex expression //Similar to a=a+b.

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

double 8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). char 2 bytes, unsigned, Unicode, 0 to 65,535 10.7.1 Variables Declaration

The syntax of declaring a variable in java is similar to that of C, C++. Variables are the names of storage location. The following are the examples of variable declaration int i; int i,j int i=3,j=7; 10.7.2 Constants Constants refer to values that do not change during the execution of the program. Examples for constants are 1998 25.789 Hello World a Integer constant Floating point constant String constant Character constant //declares a integer variable i //declares two integer variables i and j //declares and initialize the values i and j

Apart from these types of constants java also supports backslash character constants. The Table 10.2 lists all the backslash constants. BACKSLASH CONSTANT PURPOSE \b Backspace \f Form feed \n New Line \r Carriage return \t Horizontal tab \\ Backslash Table 10.2 Backslash Constants Have you understood? 1. 2. 3. 4. 5. Mention the range for a byte How floating point numbers are represented in Java? What is the size for double data type? How Characters are represented in Java? Write any two backslash constants.

Anna University Chennai

186

DCS 115

OBJECT ORIENTED PROGRAMMING

10.8 Java Statements The statements inside your source files are generally executed from top to bottom, in the order that they appear. Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling your program to conditionally execute particular blocks of code. Java supports decision-making statements like (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) the syntax and usage of these control structures are similar to C++.Refer section 1.7 for further details. Here are some simple java programs that make use of these control structures. Example 2: The Program given below compares two numbers and finds the greater of the two numbers. class big { public static void main(String args[]) { int i=30,j=25; if(i>j) System.out.println(I IS BIG); else if(i==j) System.out.println(I AND J ARE EQUAL); else System.out.println(J IS BIG); } } Example 3: The Code listed below makes use of a switch case construct. class switch_ex { public static void main(String args[]) { char ch; System.out.println(COUNTRIES AND THEIR CAPITALS); System.out.println(I-INDIA,U-USA,J-JAPAN,F-FRANCE); try { ch=(char)System.in.read();
187

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

switch(ch) { case I: System.out.println(INDIA-NEWDELHI); break; case U: System.out.println(USA-WASHINGTON DC); break; case J: System.out.println(JAPAN-TOKOYO); break; case F: System.out.println(FRANCE-PARIS); break; default: System.out.println(INVALID CHOICE); } }catch(Exception err) { System.out.println(ERROR); } } } In this example you are reading character input from the keyboard for this you are using the statement System.in.read().as you know try and catch statements are used for exception handling. Now let us write some program using looping statements. The first looping structure discussed is the while loop. This program prints the multiplication table for the number 5. Example 4: The Program given below prints the multiplication table for 5 using while loop. class while_test { public static void main(String args[]) { int i=1; while(i<=10) { System.out.println(i + * 5 = +i*5); i++; } } }

Anna University Chennai

188

DCS 115

OBJECT ORIENTED PROGRAMMING

Example 5: The Program given below is the do... while version of the previous example class dowhile_test { public static void main(String args[]) { int i=1; do { System.out.println(i + * 5 = +i*5); }while(i<=10); } } Example 6: The Program listed below makes use of a for loop to print the multiplication table for 5. class for_test { public static void main(String args[]) { for(i=1;i<10;i++) { System.out.println (i + * 5 = +i*5); } } } Have you understood? 1. Write the syntax for if statement in java. 2. Write the syntax for a for loop. 3. What is the purpose of break and continue statement? 10.9 Command Line Arguments In Java it is possible to provide input to a program as command line arguments. The String args[] argument in the main method is used to supply command line arguments to the program. Java programs accept only strings as command line arguments. However you can convert these arguments into the desired data types using the wrapper classes.
189

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Thus using wrapper classes you can convert the string to the corresponding simpler type. The signature for the Integer wrapper class is static int parseInt(String s) For example Integer.parseInt(10) will convert the string 10 to integer 10. The Integer wrapper class has a static method called parseInt to perform this job. Similarly the signature of the Double wrapper class is static int parseDouble(String s) For example Double.parseDouble(153.18) will convert the string 153.18 to double 153.18. The Double wrapper class has a static method called parseDouble to perform this job. Similar methods are available for all the simple types. The command line arguments passed to program are stored in the String array args[] . The first element is referenced as args[0] , the next element as args[1] and so on. Command line arguments are supplied to the program when you run the program. For example when you run the program named hello.java C:\jdk1.5.0\bin> java hello 123 abc 12.88 args[0] contains 123 args[1] contains abc args[2] contains 12.88 Example 7: The following example accepts two command line arguments and computes the sum of two numbers. class sum {

Anna University Chennai

190

DCS 115

OBJECT ORIENTED PROGRAMMING

public static void main(String args[]) { double i,j,s; i=Double.parseDouble(args[0]); j=Double.parseDouble(args[1]); s=i+j; System.out.println(The sum is +s); } } Output of the Program

NOTES

Example 8: The following example accepts a number n as command line argument and generates n Fibonacci numbers. class fib { public static void main(String args[]) { int n; int a=0,b=1,c; n=Integer.parseInt(args[0]); for(int i=0;i<n;i++) { c=a+b; System.out.println(The next number is +c);
191 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
} } }

a=b; b=c;

Output of the Program

Example 9: The following example prints number of command line arguments passed. class count { public static void main(String args[]) { int n; n=args.length; System.out.println(The count is +n); } } Have you understood? 1. How command line arguments are passed to the program 2. How will you convert string 50 to integer 3. How will you find length of command line arguments

Anna University Chennai

192

DCS 115

OBJECT ORIENTED PROGRAMMING

Summary Java is a high level language looks much similar to C, C++ but it offers many unique features that are not available in most of modern programming language. Java compiler converts the source code into intermediate byte code instructions Java Interpreter converts these bytes codes into machine executable statements Java programs are capable of running on all platforms hence java programs possess Write-Once-Run-Anywhere feature Java programs will run only within the Java Virtual Machine (JVM) sandbox Java is a dynamic language. The linking of data and methods occurs only at run time. When a java program is compiled it will not produce a machine code instead it produces an intermediate byte code for the JVM. When you run the java program the byte code produced for the JVM will be interpreted by the java run time interpreter. Java tokens include keyword, identifiers, literals and operators. In Java expressions are used to implement some computation. Expressions in java can be either a simple expression or a complex expression. Float and Double data types were represented in IEEE 754 format Characters are represented as unsigned Unicode values In Java Constants refer to values that do not change during the execution of the program Java supports decision-making statements like (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) the syntax and usage of these control structures are similar to C++. Exercises Short Questions 1. 2. 3. 4. 5. 6. 7. 8. 9. What is JVM? Write the signature of main() method Why main() method is declared as static? The type comparison operator in java is ____________ When Boolean data type is used? \\ is used as ___________ Mention the range for char data type How will you make a early exit from a loop in Java? What is a wrapper class?

NOTES

193

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Long Questions 1. Explain the various features of Java in detail 2. Write short notes on JVM 3. Write the syntax and explain the various Java control and looping statements Programming Exercises 1. Write a program to print the first n Amstrong numbers (accept n as command line argument) 2. Write a Java program to compute the sum of the series 1! +2! +3! +. +n! 3. Write a Java program to find the sum of digits of a number 4. Write a Java program to find area of a triangle Answers to Have you Understood Questions Section 10.3 1. Java compiler converts the source code into intermediate byte code instructions Java Interpreter converts these bytes codes into machine executable statements 2. Java programs will run only within the Java Virtual Machine (JVM) sandbox thus threats from malicious programs is minimized. Java does not support pointers hence direct memory access is not allowed. Java supports a built in security manager that determines what resources a class can access such as reading and writing to the local disk. Thus we can say java programs are secure. 3. (1) Pointers (2) Preprocessor directives (3) Multiple inheritance (3) Tempalte classes Section 10.4 1. When a java program is compiled it will not produce a machine code instead it produces an intermediate byte code for the JVM. 2. To compile you have to use javac compiler,to run you have to use java inter preter. 3. System.out.println() Section 10.5 1. Java tokens include keyword, identifiers, literals and operators. 2. c

Anna University Chennai

194

DCS 115

OBJECT ORIENTED PROGRAMMING

3.

(1)An identifier can contain alphanumeric characters, but it should begin with an alphabet (2) Identifiers are case sensitive(i.e. upper and lower cases are different) (3)Underscore and dollor sign are two special character allowed. 4. ~ (bitwise compliment) , & (bitwise AND) 5. TRUE. Section 10.6 1. In Java expressions are used to implement some computation. Expressions in java can be either a simple expression or a complex expression. Section 10.7 1. 2. 3. 4. 5. Values from -128 to 127. In IEEE 754 format 8 bytes. Characters are represented as unsigned Unicode values \b (backspace) ,\f (form feed)

NOTES

Section 10.8 1. The if-else statement is used for making decisions. The syntax is if ( expression) statement1 else statement2 2. The for statement syntax is given below for (expr1; expr2; expr3) { statements; } 3. The break statement provides an early exit from for, while, and do, just as from switch. Continue causes the next iteration of the enclosing for, while, or do loop to begin

Section 10.9 1. The String args[] argument in the main method is used to supply command line arguments to the program. 2. Integer.parseInt(50) 3. By using args.length (args is the string array)
195 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

References 1. Java 2 Certification Guide Author: Jamie Jaworski Publisher: New Riders 2000 http:\\www.sun.com Thinking in Java Author: Bruce Eckel Publisher : Prentice Hall 2000 Programming with Java Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Java 2: The Complete Reference Author : Patrick Naughton & Herbert Schildt Publisher : Tata Mcgraw Hill 2000

2. 3.

4.

5.

Anna University Chennai

196

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 11 OBJECT OREINTED CONCEPTS IN JAVA


Classes Objects Adding Variables to Classes Adding Methods to Classes Constructors Access Specifiers Default Access Method Overloading Constructer Overloading Static Data Members Static Methods Inheritance Super Keyword Multilevel Inheritance Method Overriding Uses of Super Keyword Abstract Methods and Classes Final Keyword Finalizer Methods

11.1 Introduction Java is purely an object oriented language. In Java no coding outside of class definitions is allowed, including the main() function. Java supports all the primary concepts of object orientation like encapsulation, abstraction, inheritance and polymorphism. This chapter introduces you to implement all the object oriented features supported by java. This chapter provides the necessary background to understand the advanced concepts presented in the subsequent chapters. 11.2 Learning Objectives To introduce classes and objects in Java To discuss about adding methods to classes To introduce the concept of constructors To discuss the various access specifiers available in Java. To present the constructor and method overloading features To discuss static data members and methods. To understand the concept of inheritance To learn the importance of super keyword
197 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

11.3

To show how method overriding is done in Java To introduce abstract classes and methods To introduce final keyword To discuss about finalizer method Classes

Classes are the basic building blocks of Java programs. Classes are called as Abstract Data Type (ADT) .Classes describes the structure of the object. Java classes consist of both attributes and behaviors. Attributes represent the data that is unique to an instance of a class, while behaviors are methods that operate on the data to perform useful tasks. Class Syntax The syntax to declare a class in Java is: [public ] [ ( abstract | final ) ] class <classname> [ extends ParentClass ] [ implements interfaces ] { // variables and methods declaration }

A class can have public or default (no modifier) visibility. 1 2 3 4 It can be either abstract, final or with no modifier. It must have the class keyword, and class must be followed by a legal identifier. It may optionally extend one parent class. By default, it will extend java.lang.Object. It may optionally implement any number of interfaces separated by commas.

Here is an example of a GUI class. GUI is a class that extends the parent class called Frame and implements two interfaces namely ActionListener and ItemListener. public class GUI extends Frame implements ActionListener, ItemListener { //declarations of variables and methods } 11.3.1 Objects Objects are the run time instance of a class. Classes describe objects. Many objects can be instantiated from one class. Objects of different classes can be created, used, and destroyed in the course of executing a program.

Anna University Chennai

198

DCS 115

OBJECT ORIENTED PROGRAMMING

Objects in java are created using the new operator. For example to create an object for the GUI class we follow the given syntax. GUI obj=new GUI(); //declare and instantiate OR GUI obj; Obj=new GUI(); //declare //instantiate

NOTES

11.3.2 Adding Variables to Classes A class can contain variables. The variables added to the class are called instance variables. Variables are declared in the java classes as mentioned below. class product { int prod_id; String prod_name; double price; } 11.3.3 Adding Methods to Classes Methods in Java determine the messages an object can receive. Methods in Java can be created only as part of a class. A method can be called only for an object, You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, for example: objectName.methodName(arg1, arg2, arg3) The signature of a method comprises the method name and parameter list. The combined name and parameter list for each method in a class must be unique. The Syntax to declare a method in java is [modifiers] return_type <method_name> (parameter_list) [throws_clause ] { //method body } Return Type: The return type is either a valid Java type (primitive or class) or void if no value is returned. If the method declares a return type, every exit path out of the method must have a return statement. Method Name: The method name must be a valid Java identifier Parameter List: The parentheses following the method name contain zero or more type/identifier pairs that make up the parameter list. Each parameter is separated by a comma. Also, there can be zero parameters.
199 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

There are a number of optional modifiers that you can use when declaring a method. They are listed in the Table 11.1: Table 11.1 List of Modifiers in Java Modifier Visibility Description Can be one of the values: public, protected, or private. Determines what classes can invoke the method. The method can be invoked on the class instead of an instance of the class. The method is not implemented. The class must be extended and the method must be implemented in the subclass. The method cannot be overridden in a subclass. The method is implemented in another language. The method requires that a monitor (lock) be obtained by calling code before the method is executed. A list of exceptions thrown from this method.

static abstract

final native synchronized

throws

Now, consider the product class created previously, we can add two methods getDetails() and displayDetails() to the class. class product { int prod_id; double price; void getDetails(int a,String b,double c) { prod_id=a; price=c; } void displayDetails() { System.out.println(Product id is +prod_id); System.out.println(Price is +price); } }
Anna University Chennai 200

DCS 115

OBJECT ORIENTED PROGRAMMING

Example 1: The following java program performs the basic calculator functions. class Calculator { int n1,n2,res; void setData(int x1,int x2) { n1=x1; n2=x2; } void add() { res=n1+n2; System.out.println(The Sum is : +res); } void sub() { res=n1-n2; System.out.println(The Difference is : +res); } int mul() { res=n1*n2; return res; } double div() { return n1/n2; } } class Mainprg { public static void main(String args[]) { Calculator cal=new Calculator(); cal.setData(20,10); cal.add(); cal.sub(); int y=cal.mul(); System.out.println(The Product is : +y); double d=cal.div(); System.out.println(The divided value is :+d);
201

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

} } Have you understood? 1. 2. 3. 4. 5. What is a class? All classes in java extend __________ What is an object? Write the syntax of method declaration. Explain abstract keyword.

11.4 Constructors Constructors are special type of methods that are invoked when we create objects for the classes. Constructers will have the same name as that of the class. Constructors and methods differ in two important aspects of the signatures. They are Modifiers Return types Like methods, constructors can have any of the access modifiers: public, protected, private, or none (often called friendly). However constructors cannot be made abstract, final, native, static, or synchronized. Methods can have any valid return type, or no return type, in which case the return type is given as void. Constructors cannot take any return type, even void. Example 2: The Calculator class created in example 1 is modified, the setData() method is replaced with a constructer. class Calculator { int n1,n2,res; Calculator (int x1,int x2) //Constructor { n1=x1; n2=x2; } void add() { res=n1+n2;
Anna University Chennai 202

DCS 115

OBJECT ORIENTED PROGRAMMING

System.out.println(The Sum is : +res); } void sub() { res=n1-n2; System.out.println(The Difference is : +res); } int mul() { res=n1*n2; return res; } double div() { return n1/n2; } } class Mainprg { public static void main(String args[]) { Calculator cal=new Calculator(20,10); //Calls the constructer cal.add(); cal.sub(); int y=cal.mul(); System.out.println(The Product is : +y); double d=cal.div(); System.out.println(The divided value is :+d); } } Have you understood? 1. What is constructer? 2. Differentiate constructors from other methods. 11.5 Access Specifiers

NOTES

An access specifier in java determines which data member, which method can be used by other classes. Java supports three access specifiers and a default access specifier. Access specifiers are also known as access modifiers. The three access specifiers supported in Java are The private access specifier
203 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

The public access specifier The protected access specifier Only objects of the same class can have access rights to a method or data member declared as private. A method or a data member can be declared as private by prefixing it with the keyword private. For example private int sum; // private variable private void method1() //private method declaration { //method body } A data member or a method declared as public can be accessed by all classes and their objects. To declare a data member or a method as public prefix the declaration with the keyword public. For example public double area //public variable public void calculate() //public method { //method body } Data members, methods that are declared protected are accessible by that class and the inherited subclasses. Methods and variables can be declared as protected by prefixing the declaration with the protected keyword. protected String msg; //protected variable protected int search() //protected method { //method body } 11.5.1 Default Access If none of the above mentioned access specifiers are specified to a method or a variable, then the scope is considered to be friendly, this is the default access scheme in Java. A class, method, variable with a friendly scope is accessible to all the classes of the package. packages are discussed in chapter 15. Have you understood? 1. Write the three access specifiers available in Java . 2. What is the default access in Java ?

Anna University Chennai

204

DCS 115

OBJECT ORIENTED PROGRAMMING

11.6 Method Overloading Overloading is one of the important polymorphic features of the Object Oriented System. Like C++ functions we can also overload Java methods. In Java two or more methods can share the same name as long as either the type of their arguments differs or the number of their arguments differs - or both. When two or more methods share the same name, they are said overloaded. Example 3: The coding listed below overloads the method sum() class numbers { void sum(int x,int y) { int z=x+y; System.out.println(Sum of addition of two numbers : +z); } void sum(int x,int y,int z) { int r=x+y+z; System.out.println(Sum of addition of three numbers : +z); } } class test { public static void main(String args[]) { test t=new test(); t.sum(10,20); //Call the method sum with two parameters t.sum(10,20,30); //Call the method sum with three parameters } } In this program the method sum is overloaded. From the main method when we call the sum method the corresponding the overloaded version of the sum method is called. 11.6.1 Constructer Overloading In Java, similar to the concept of method overloading we have constructer overloading. In constructer overloading we have multiple constructers that differ
205

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

either in type of their arguments or the number of their arguments or both. The constructer that takes no parameter is called default constructer. Below is the example of constructer overloading. Example 4: The program given below makes use of constructer overloading concept. class dimension { int x1,y1; dimension() //default constructor { x1=0; y1=0; } dimension(int a) { x1=a; y1=0; } dimension(int a,int b) { x1=a; y1=b; } void display() { System.out.println( x1 is :+x1); System.out.println( y1 is :+y1); } } class Mainprg { public static void main(String args[]) { dimension d1=new dimension(10,50); //Calls constructer with two parameter dimension d2=new dimension(10); //Calls constructer with one parameter dimension d3=new dimension(); //Calls default constructer d1.display(); d2.display(); d3.display(); } }

Anna University Chennai

206

DCS 115

OBJECT ORIENTED PROGRAMMING

Have you understood? 1. When you will say two methods are overloaded? 2. Define constructor overloading? 11.7 Static Data Members

NOTES

Each object of a given class has its own copy of all the data defined by the class. Sometimes it is desirable for all the objects of a particular class to share data. In Java this can be achieved by defining the corresponding class members as static using the keyword static. Since static variables are common all the instances of the class, static variables can also be called as class variables.

for a static data member there will be only one copy of the class member shared by all objects of the class. A static data member is like a global variable, but has class-level scope.

To declare a variable as static we have to simply prefix the variable declaration with the keyword static. For example static int x; 11.7.1 Static Methods Like static variables , static methods are called without the object. The differences between a static methods and non-static methods are as follows.

A static method can access only static data and can call only other static methods. A non-static member function can access all of the above including the static data member. A static method can be called, even when a class is not instantiated, a nonstatic member function can be called only after instantiating the class as an object. A static method cannot have access to the this keyword. A static method cannot have access to the super keyword.

Example 5: This program makes use of static data members and methods class test { static int increment(int k) { k++; return k;
207 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

} static int decrement(int j) { j; return j; } } class static_test { public static void main(String args[]) { int a=static_test.increment(10); System.out.println(Incremented Value is : +a); int b=static_test.decrement(20); System.out.println(Decremented Value is : +b); } } In Java class libraries many static methods are found. For example in java.lang package, we have a class called Math all the methods declared in the Math class are static. Example 6: This program makes use of some static methods available in Math class. class Math_test { public static void main(String args[]) { System.out.println(Sin 30 is +Math.sin(30)); System.out.println(Square root of 25 is +Math.sqrt(25)); System.out.println(Absolute value for -15 is +Math.abs(-15)); System.out.println(Log value for 88.87 is +Math.log(88.87)); System.out.println(3 Power 5 is + Math.pow(3,5)); } }

Anna University Chennai

208

DCS 115

OBJECT ORIENTED PROGRAMMING

Have you understood? 1. What is static variable? 2. Write any two differences between static and non static variables 3. How will you find the square root of a number? 11.8 Inheritance

NOTES

Inheritance is a feature by which new classes are derived from the existing classes. Inheritance allows re-using code without having to rewrite from scratch. Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the base class or superclass) with another class (called the derived class or subclass). In Java, inheritance is used for two purposes: Class inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class, i.e., single class inheritance Interface inheritance Interface inheritance is used to achieve multiple inheritance. It is discussed in detail in chapter 14. The Syntax for class inheritance is given below [public ] class <classname> extends ParentClass { //variables and methods declaration } In keyword extends is used to implement inheritance in Java. In Java the following forms of class inheritance is supported. Single Inheritance Multilevel Inheritance Hierarchical Inheritance. Example 7: The program listed below is a single inheritance program. class rectangle { int l; int b; rectangle(int x,int y)
209 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

{ l=x; b=y; } void rect_area() { System.out.println(Area of Rectangle is + l*b); } } class cube extends rectangle { int h; cube(int x,int y,int z) { super(x,y); h=z; } void cube_volume() { System.out.println(Volume of the Cube is + l*b*h); } } class Mainprg { public static void main(String args[]) { cube c=new cube(10,20,30); c.rect_area(); c.cube_area(); } }
Output of the Program Area of Rectangle is 200 Volume of the Cube is 6000

Anna University Chennai

210

DCS 115

OBJECT ORIENTED PROGRAMMING

11.8.1 Super Keyword Java uses a unique keyword called super to call the super class constructers. In the previous example we have used super keyword to pass parameters to the super class constructer from the sub class constructer. The following is the syntax of super keyword super() (or) super(parameter list) With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called. The parameters in the super keyword must match the parameters in the super class constructer When super keyword is used it must be the first statement in the sub class constructor. 11.8.2 Multilevel Inheritance As mentioned earlier java supports multilevel inheritance. The syntax for multilevel inheritance is given below. class super1 { } class sub1 extends super1 { } class sub2 extends sub1 { } Example 8: This program listed below is a simple example for multilevel inheritance. //Super Class class data1 {
211

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

int a; data1(int x) { a=x; } }

//Sub Class1 class data2 extends data1 { int b; data2(int x,int y) { super(x); b=y; } } //Sub Class2 class data3 extends data2 { int c; data3(int x,int y,int z) { super(x,y); c=z; } void compute() { System.out.println(The Product is +a*b*c); } } //Main Program class Mainclass { public static void main(String args[]) { data3 d=new data3(1,2,3); d.compute(); } }

Anna University Chennai

212

DCS 115

OBJECT ORIENTED PROGRAMMING

Have you understood? 1. 2. 3. 4. 11.9 What is inheritance? Mention the two forms of inheritance. List the types of class inheritance supported in Java. What is the purpose of super keyword ? Write the syntax of super keyword. Method Overriding

NOTES

A subclass inherits all the methods from a superclass. Sometimes, it is necessary for the subclass to modify the methods defined in the superclass i.e., subclass may want to provide a new version of a method in the superclass. This is referred to as method overriding. In a sub class, if you include a method definition that has the same name and exactly the same number and types of parameters as a method already defined in the super class, this new definition replaces the old definition of the method. Example 9: This program listed below illustrates Method Overriding concept.. class Circle { double radius; Circle(double r) { radius =r; }

double getArea() { return Math.PI*radius*radius; } } class Cylinder extends Circle { double length; Cylinder(double radius, double l) { super(radius); length=l; } double getArea() {
213 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

return 2* Math.PI*radius*radius +2*Math.PI*radius*length; } } class Areaprg { public static void main(String args[]) { Cylinder cy=new Cylinder(3.3,5.2); double res; res=cy.getArea(); System.out.println(Area of Cylinder is +res); } } When the overriden method getArea() is invoked for an object of the Cylinder class, the new overridden version of the method is called and not the old definition from the superclass Circle. However, if we want to find the area of both circle and cylinder then we have to instantiate both the classes and invoke the getArea() method. Circle c=new Circle(3.3); c.getArea(); Cylinder cy=new Cylinder(3.3,5.2); c.getArea(); Have you understood? 1. What is method overriding? 11.10 Uses of Super Keyword We have already learnt the usage of super keyword in invoking the super class constructer. Super keyword can also be used to call super class method overridden by the subclass method. The previous program is modified with the help of super keyword. Example 10: This program is the modified version of the example 9 class Circle

Anna University Chennai

214

DCS 115

OBJECT ORIENTED PROGRAMMING

{ double radius; Circle(double r) { radius =r; } double getArea() { return Math.PI*radius*radius; } } class Cylinder extends Circle { double length; Cylinder(double radius, double l) { super(radius); length=l; } double getArea() { return 2* super.getArea() +2*Math.PI*radius*length; } } class Areaprg { public static void main(String args[]) { double res; Circle c=new Circle(3.3); res=c.getArea(); System.out.println(Area of Circle is +res); Cylinder cy=new Cylinder(3.3,5.2); res=cy.getArea(); System.out.println(Area of Cylinder is +res); } } Super keyword can also be used to refer superclass variables. Here is an example. Example 11: The Coding given below illustrates the use of super keyword to refer superclass variables.
215

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

class data1 { int a; data1(int x) { a=x; } } //Sub Class1 class data2 extends data1 { int b; data2(int x,int y) { super(x); b=y; } void display() { System.out.println(Value of a is +super.a); System.out.println(Value of b is +b); } } class Mainprg { public static void main(String args[]) { data2 d=new data2(10,20); d.display(); } }

Output of the Program Value of a is 10 Value of b is 20

Thus, we can use super keyword in the following three contexts 1 To call a superclass constructer 2 To call a superclass method overridden by the subclass method 3 To refer the superclass variable from the subclass.
Anna University Chennai 216

DCS 115

OBJECT ORIENTED PROGRAMMING

Have you understood? 1. Write the uses of super keyword. 11.11 Abstract Methods and Classes Abstract methods are those that will have only method declaration without any implementation. Hence we can say abstract methods are incomplete methods. A method in java can be declared as abstract by prefixing its declaration with the keyword abstract. For example abstract void area(); The implementations for these abstract methods are provided by overriding the abstract method using a subclass. Abstract class is a class that is declared as abstract. An abstract class will have one or more abstract methods. Abstract classes cannot be instantiated but it can be inherited by other subclasses. These subclasses will provide the implementation of all the abstract methods present in the parent class however, if not, the corresponding subclass must be declared abstract. Here is an example of a abstract class and its corresponding subclass. Example 12: The Coding listed below makes use of an abstract class. abstract class Shape { int l; Shape() { l=10; } abstract void area(); //abstract method declaration } class Rect extends Shape { int b; Rect() { b=10; }
217

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

void area() //overriding the abstract method. { System.out.println( Area of Rect is +l*b); } public static void main(String args[]) { Rect r=new Rect(); r.area(); } } Have you understood? 1. How will you declare an abstract method? 2. Is it possible to instantiate an abstract class? 11.12 Final Keyword Java supports an important keyword called Final. The keyword Final is used in three different context. Final keyword can be used along with 1 2 3 Variables Methods Classes

Final keyword when used with a variable, it becomes a constant. To declare a variable as a Final prefix the keyword Final along with the variable declaration. For example final int PI=3.14; When a method declaration is prefixed with the Final keyword the method cannot be overridden by the subclass method. Thus method overriding can be prevented. For example final void calculate() { //body of the method } When a class is declared as Final then the class cannot be subclassed. Hence it prevents inheritance. For example final class test {
Anna University Chennai 218

DCS 115

OBJECT ORIENTED PROGRAMMING

//body of the class } 11.12.1 Finalizer Methods Before an object is garbage collected, the runtime system calls its finalize () method. The purpose of finalize () method is to release system resources before the object gets garbage collected. The signature of finalize method is given below. protected void finalize () throws throwable Finalize () method in java has the following properties every class inherits the finalize() method from java.lang.Object the method is called by the garbage collector when it determines no more references to the object exist the Object finalize method performs no actions but it may be overridden by any class normally it should be overridden to clean-up non-Java resources ie closing a file Have you understood? 1. How will you declare a constant? 2. Mention the three ways in which final keyword can be used. 3. What is the purpose of finalize() method? Summary Java is purely an object oriented language. In Java no coding outside of class definitions is allowed, including the main() function. By default all classes in java will extend java.lang.Object. Objects are the run time instance of a class. Classes describe objects. Objects in java are created using the new operator. When a method is declared as native ,its implementation can be given in another language. Constructors are special type of methods that are invoked when we create objects for the classes. Constructers will have the same name as that of the class. Java supports public, private and protected access specifiers If none of access specifiers are specified to a method or a variable, then the scope is considered to be friendly, this is the default access scheme in Java.
219

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

In Java two or more methods can share the same name as long as either the type of their arguments differs or the number of their arguments differs - or both. When two or more methods share the same name, they are said overloaded. Constructer overloading is a concept in which you have multiple constructers that differ either in type of their arguments or the number of their arguments or both. Static variables are common all the instances of the class, static variables can also be called as class variables. Static methods are called without the object. Inheritance is a feature by which new classes are derived from the existing classes. The keyword extends is used to implement inheritance in Java. Java uses a unique keyword called super to call the super class constructers. If you include a method definition that has the same name and exactly the same number and types of parameters as a method already defined in the super class, this new definition replaces the old definition of the method. This concept is called method overriding. Abstract methods are those that will have only method declaration without any implementation. Final keyword when used with a variable, it becomes a constant When a method declaration is prefixed with the Final keyword the method cannot be overridden by the subclass method. When a class is declared as Final then the class cannot be subclassed. Before an object is garbage collected, the runtime system calls its finalize () method. The purpose of finalize () method is to release system resources before the object gets garbage collected. Exercises Short Questions 1. 2. 3. 4. 5. 6. 7. 8. 9. Mention the OOPs concepts supported by Java Write the syntax to create class and object List the modifiers that cannot be used with constructors Destructors are available in Java (True /False) Write some methods available in Math class What is Interface inheritance? Differentiate method overloading and method overriding How will you call super class constructor Write the significance of abstract class.

Anna University Chennai

220

DCS 115

OBJECT ORIENTED PROGRAMMING

Long Questions 1. 2. 3. 4. 5. 6. Explain how classes, methods and objects are created in Java Explain the various modifiers that can be used with methods Explain the various access specifiers used in Java programs. Explain the different context in which super keyword is used Explain the different context in which final keyword is used What do you mean by finalize() method ? Explain .

NOTES

Programming Exercises 1. Create a class in Java to implement a Stack 2. Create a class called Product with prod_name, prod_id, cost, quantity as data members create necessary methods and constructers for the class 3. Implement the inheritance scheme given below in Java. Answers to Have you Understood Questions Section 11.3 1. Classes are the basic building blocks of Java programs. Classes are called as Abstract Data Type (ADT) .Classes describes the structure of the object. 2. java.lang.object 3. Objects are the run time instance of a class. Classes describe objects. 4. [modifiers] return_type <method_name> (parameter_list) [throws_clause ] { //method body } 4. A method without implementation must be declared as abstract. Section 11.4 1. Constructors are special type of methods that are invoked when we create objects for the classes. Constructers will have the same name as that of the class. 2. Constructors cannot be made abstract, final, native, static, or synchronized and it cannot have return type. Section 11.5 1. The private access specifier , The public access specifier ,The protected access specifier
221 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

2. friendly scope. Section 11.6 1. When two or more methods share the same name but differ in their signature, they are said overloaded. 2. Constructer overloading is a concept in which you have multiple constructers that differ either in type of their arguments or the number of their arguments or both. Section 11.7 1. static variables are common all the instances of the class, static variables can also be called as class variables for a static data member there will be only one copy of the class member shared by all objects of the class A static data member is like a global variable, but has class-level scope. 2. (1) A static method can access only static data and can call only other static methods. A non-static member function can access all of the above including the static data member. (2) A static method can be called, even when a class is not instantiated, a non-static member function can be called only after instantiating the class as an object. 3. By calling Math.sqrt() function. Section 11.8 1. Inheritance is a feature by which new classes are derived from the existing classes The two forms of inheritance are (1) class inheritance (2) interface inheritance. 2. (1) Single (2) Multilevel (3) Hierarchical 3. Java uses a unique keyword called super to call the super class constructers. 4. super() or super(parameters) Section 11.9 1. If you include a method definition that has the same name and exactly the same number and types of parameters as a method already defined in the super class, this new definition replaces the old definition of the method. This concept is called method overriding. Section 11.10 1. (a) To call a superclass constructer (b) To call a superclass method over-

Anna University Chennai

222

DCS 115

OBJECT ORIENTED PROGRAMMING

ridden by the subclass method (c) To refer the superclass variable from the subclass. Section 11.11 1. By prefixing the method declaration with abstract. 2. No Section 11.12 1. By declaring the variables as final. 2. Final keyword can be used with variables, methods and classes 3. The purpose of finalize () method is to release system resources before the object gets garbage collected References 1. Java 2 Certification Guide Author: Jamie Jaworski Publisher: New Riders 2000 http:\\www.sun.com Thinking in Java Author: Bruce Eckel Publisher : Prentice Hall 2000 Programming with Java Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Java 2: The Complete Reference Author : Patrick Naughton & Herbert Schildt Publisher : Tata Mcgraw Hill 2000 Java in a Nutshell Author:David Flanagan Publisher :OReilly1999

NOTES

2. 3.

4.

5.

6.

223

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 12 ARRAYS AND VECTORS


Arrays Initializing a Two Dimensional Arrays Java Array Declaration Vectors Java Array Initialization Vector Creation Two Dimensional Arrays Methods in Vector

12.1 Introduction This Chapter introduces you to understand two important and frequently used data structures in Java The first data structure this chapter introduces to you is Arrays. You have already learnt about arrays in C++. Like C++ arrays in Java are used to hold values that are of the same type, but however Java handles arrays in a different manner. The creation and processing of arrays are discussed in detail in this chapter. The second important data structure discussed in this chapter is the vector. Vector is a class available in the java.util package. Vectors are commonly used instead of arrays. Vectors in Java is used to create a generic and dynamic array that hold objects of any type. The creation and processing of vectors are discussed in detail in this chapter. 12.2 Learning Objectives To introduce the concept of arrays To show how to declare ,initialize and process single dimensional array To show how to declare ,initialize and process two dimensional array To introduce the concept of vectors To show how to declare a vector To discuss various methods available in vector class.
224

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

12.3

Arrays

NOTES

Arrays are data structures used to hold values that are of the same type. Arrays are fixed-length structures for storing multiple values of the same type. An array implicitly extends java.lang.Object so an array is an instance of Object. The structure of java arrays is shown below.

The array a shown in the diagram has nine elements. Like C, C++ the index of an array in java starts with zero. All the elements in an array as accessed with the help of array index. The notation a[i] refers to the i-th element of the array.

12.3.1

Java Array Declaration

An array variable is declared in the same way that any Java variable is declared. It has a data type and a valid Java identifier. The data type is the type of the elements contained in the array. The [] notation is used to denote that the variable is an array. Java has a unique way of declaring array. 1 2 3 4 int data[]; data=new int[50]; int[] data; data=new int[50]; int[] data=new int[50]; int data[]=new int[50];

All the four statements declare an one dimensional array called data with the size 50. Similarly we can declare array for various data types. Some examples 1 2 12.3.2 String args[] double points[] Java Array Initialization

Once an array is declared we can initialize it with some initial values. The syntax is type arrayname[]={list of values };

225

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

For example int data[] = { 5,10,15,20,25 }; When we initialize an array, we will not specify the size of the array. The java compiler automatically calculates the size the array. Example 1: The following program computes the sum and average of an array class Array { public static void main(String args[]) { int data[]= { 5,10,15,20,25 }; int sum=0; double avg; for(int i=0;i<data.length;i++) sum+=data[i]; avg=sum/data.length; System.out.println( The Sum of the Array is +sum); System.out.println( The Average of the Array is +avg); } } Output of the Program The Sum of the Array is 75 The Average of the Array is 15
NOTE: The size of the array can be found using the variable length. In the previous example data.length returns the length of the array data.

Example 2: A simple bubble sort algorithm using single dimensional array is illustrated below. class Bubble
Anna University Chennai 226

DCS 115

OBJECT ORIENTED PROGRAMMING

{ public static void main(String args[]) { int a[]= { 23,7,19,46,53,21 }; for(int i=0;i<6;i++) for(j=i+1;j<6;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } System.out.println (The Sorted Output is); for(int i=0;i<6;i++) System.out.println(a[i]); } }
Output of the Program 7 19 21 23 46 53

NOTES

12.3.3 Two Dimensional Arrays Often data comes in a two dimensional form. For example, data represented in tables are two dimensional (or more), a computer-generated image is two dimensional, and so on. To handle these data we need 2-D arrays. To declare an 2-D array in java, the syntax is int data[][]; data=new int[3][3]; int data[][]=new int[3][3] The above statement declares a 3x3 matrix. The first dimension represents the row size the second dimension represents the column size. In Java, a two-dimen227 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

sional array x is really an array of one-dimensional arrays: int[][] x = new int[3][5]; The expression x[i] selects the ith one-dimensional array; the expression x[i][j] selects the jth element from that array. 12.3.4 Initializing a Two Dimensional Arrays We can initialize an 2-D array as given below. int[][] twoD = { {1,2,3}, {4,5,6}, {7,8,9} }; You can initialize the row dimension without initializing the columns but not vice versa int[][] myArray = new int[5][]; (Correct) int[][] myArray = new int[][5]; (Error will not work)
Output of the Program Transpose Of the Matrix is 1 4 7 2 5 8 3 6 9

Example 3: The below program performs transpose of a 3x3 matrix. class Transpose { public static void main(String args[]) { int[][] a = { {1,2,3}, {4,5,6}, {7,8,9} }; int [][] b=new int[3][3]; for (int i=0;i<3;i++) for (int j=0;j<3;j++) { b[i][j]=a[j][i]; } System.out.println(Transpose Of the Matrix is ); for (int i=0;i<3;i++)
Anna University Chennai 228

DCS 115

OBJECT ORIENTED PROGRAMMING

{ for (int j=0;j<3;j++) { System.out.print(b[i][j]+\t); } System.out.println(); } }

NOTES

} Have you understood? 1. 2. 3. 4. 5. 12.4 What is an Array ? Arrays in java extend _________ How will you access 10th element of an array a? Write the statement to declare an integer array k with 50 elements. How will you initialize 2D array? Vectors

Vector is a class available in the java.util package. Vectors are commonly used instead of arrays, because they expand automatically when new data is added to them. Vectors can hold only Objects and not primitive types (eg, int). If you want to put a primitive type in a Vector, you have to convert the primitive type to object and then add it to the vector. You must import either import java.util.Vector; or import java.util.*; to work with the vector. Vectors are implemented with an array, and when that array is full and an additional element is added, a new (bigger) array must be allocated and copy the elements from the old array to the new array, if you knew the final size, it is better to use an array but however if you want to create an array that dynamically grow and shrink in size,Vector is a better choice. 12.4.1 Vector Creation To create a Vector Java supports two types of constructers. The first constructer creates a vector with a default size 10. The general form is Vector v=new Vector(); Here v is the object of type vector.The second form of constructer creates a vector with a specified size. The general form is Vector v=new Vector(30);
229 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

The constructer given above creates a vector with an initial size 30. 12.4.2 Methods in Vector Vector class in java supports many methods. Some important methods available in Vector class are tabulated in the Table 12.1. Method v.add(o) v.add(i, o) v.clear() v.contains(o) v.firstElement() v.get(i) v.lastElement() v.listIterator() v.remove(i) v.set(i,o) v.size() v.toArray(Object[]) Description adds Object o to Vector v Inserts Object o at index i, shifting elements up as necessary. removes all elements from Vector v Returns true if Vector v contains Object o Returns the first element. Returns the object at int index i. Returns the last element. Returns a ListIterator that can be used to go over the Vector. This is a useful alternative to the for loop. Removes the element at position i, and shifts all following elements down. Sets the element at index i to o. Returns the number of elements in Vector v. The array parameter can be any Object subclass (eg, String). This returns the vector values in that array (or a larger array if necessary). This is useful when you need the generality of a Vector for input, but need the speed of arrays when processing the data.

Table 12.1 Methods in Vector Class To add elements to the Vector, you have to use the add() method as mentioned earlier. For example the statement v.add(o); adds the object o to the Vector v.

Anna University Chennai

230

DCS 115

OBJECT ORIENTED PROGRAMMING

To get the elements from the Vector, You have to use the ListIterator class. This class supports two important methods to access Vector elements. They are hasNext(), this method returns true ,if the Vector object still has some more elements. next() , this method returns the next available element present in the Vector object. Example 4: This example program makes use of some commonly used vector methods import java.util.*; class VectorDemo { public static void main(String args[]) { Vector v=new Vector(); v.add(new Integer(10)); v.add(new Double(55.10)); v.add(new String(Vector)); v.add(new Integer(100)); System.out.println( The First Element is +v.firstElement()); System.out.println( The Last Element is +v.lastElement()); System.out.println( The Size of the Vector is +v.size()); System.out.println( Vector Elements is ); ListIterator i=v.listIterator(); while(i.hasNext()) { System.out.println(The Element is +i.next()); } System.out.println(Removing Second Element + v.remove(2)); System.out.println(Adding a New Element in Third Position); v.add(new String(JAVA)); System.out.println(The New Set of Elements); i=v.listIterator(); while(i.hasNext()) { System.out.println(The Element is +i.next()); } } }
231

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

The Output of this program is listed below.

Have you understood? 1. 2. 3. 4. 5. 6. Vectors are available in _________ package Mention the advantage of Vectors over arrays. How will you add a float value to a vector? Write the syntax to create the vector with size 15. Which class is used display the elements stored in the Vector. How will you find the size of a Vector?

Summary Arrays are data structures used to hold values that are of the same type. Arrays are fixed-length structures for storing multiple values of the same type. Like C, C++ the index of an array in java starts with zero. The [] notation is used to denote that the variable is an array. To declare two dimensional arrays you need two dimensions. The first dimension represents the row size the second dimension represents the column size.
Anna University Chennai 232

DCS 115

OBJECT ORIENTED PROGRAMMING

Vector is a class available in the java.util package Vectors are commonly used instead of arrays, because they expand automatically when new data is added to them. To add elements to the Vector, the add() method is used To get the elements from the Vector, ListIterator class is used To clear all the elements in the Vector clear() method is used. size() method is used to determine the size of an Vector Exercises Short Questions 1. Write the different ways of creating an Array 2. How will you initialize a 1D array 3. Is the following array declaration correct? int[][] a=new int[5][] 4. What is Vector? 5. Write the syntax of remove() method. 6. What is the purpose of contains() method? Long Questions 1. Explain how arrays are declared and handled in Java 2. What is Vector? How it is created? Explain few methods available in Vector Programming Exercises 1. Write a program to perform matrix multiplication 2. Write a program to check whether a given matrix is upper triangular 3. Write a program to a create a vector of size 10 and perform the following operations (a) add two float numbers (b) add a string and then two integers (c) remove the fourth element (d) find the size (e) print the first and last element (f) display the content of the vector

NOTES

233

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Answers to Have you Understood Questions Section 12.3 1. Arrays are data structures used to hold values that are of the same type. Arrays are fixed-length structures for storing multiple values of the same type. 2. java.lang.Object 3. a[9] refers 10th element 4. int k[]=new int[50] 5. We can initialize an 2-D array as given below. int[][] twoD = { {1,2,3}, {4,5,6}, {7,8,9} }; Section 12.4 1. java.util 2. Vectors are commonly used instead of arrays, because they expand automatically when new data is added to them. 3. Cast the float to an object ,then add to the vector 4. Vector v1=new Vector(15) 5. ListIterator 6. By using the size() method. References 1. Java 2 Certification Guide Author: Jamie Jaworski Publisher: New Riders 2000 http:\\www.sun.com Thinking in Java Author: Bruce Eckel Publisher : Prentice Hall 2000 Programming with Java Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Java 2: The Complete Reference Author : Patrick Naughton & Herbert Schildt Publisher : Tata Mcgraw Hill 2000 Java in a Nutshell Author:David Flanagan Publisher :OReilly 1999
234

2. 3.

4.

5.

6.

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 13
STRING HANDLING
13.1 String Class Methods for Type Conversion Methods for Comparing and Concatenation of Strings Miscellaneous methods Methods for Handling Individual Characters StringBuffers Methods for Searching Strings Creation of StringBuffer Methods for Extracting Substrings Methods in StringBuffer Methods for Case Conversion Introduction

String handling is one of the most important facilities supported by programming languages. Handling character strings in Java is supported through two final classes: String and StringBuffer. The String class implements immutable character strings, which are read-only once the string has been created and initialized, whereas the StringBuffer class implements dynamic character strings. All string literals in Java programs are implemented as instances of String class. Strings in Java are 16-bit Unicode. This chapter provides all necessary details about both the classes. 13.2 Learning Objectives To introduce String class in Java To discuss methods used for comparing and concatenation of Strings To present methods for handling individual characters To show methods for searching Strings To discuss methods for extracting substrings To show methods used for case conversion To discuss miscellaneous String handling methods To discuss methods used for Type Conversion
235 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

To introduce StringBuffer concept in Java To present the various StringBuffer methods. 13.3 String Class The String class implements immutable character strings. The strings created using String class are read-only, once it has been created and initialized, all string literals in Java programs, such as java, are implemented as instances of this class. Because string objects are immutable they can be shared. In Java Strings can be created in three different ways. They are 1 2 3 String str=Hello String str=new String(Hello ); char str[]={H,e,l,l,o};

The String class in java supports a variety of methods to process strings. The class String includes methods for handling individual characters of the string, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase, for representing objects and other data types as strings, for converting strings to bytes. Some frequently used methods in String class are given below. 13.3.1 Methods for Comparing and Concatenation of Strings

Strings in java can be compared using the = operator and equals() method. In java Strings can be concatenated using + operator and concat() method. Example 1: The following code performs comparision and concatenation of strings class example1 { public static void main(String args[]) { String s1=Java; String s2=Java; String s3=C++; String obj=new String(Java); if(s1==s2) System.out.println(s1 and s2 are Equal); else System.out.println(s1 and s2 are not Equal); if(s1==obj) System.out.println(s1 and obj are Equal); else
Anna University Chennai 236

DCS 115

OBJECT ORIENTED PROGRAMMING

System.out.println(s1 and obj are not Equal); if(s1.equals(obj)) System.out.println(Now !! s1 and obj are Equal); else System.out.println(s1 and obj are not equal); System.out.println(s1 + s3 =+s1+s3); System.out.println(s2 + s3 =+s2.concat(s3)); } }
Output of the Program s1 and s2 are Equal s1 and obj are not Equal Now !! s1 and obj are Equal s1 + s3 =JavaC++ s2 + s3 =JavaC++

NOTES

13.3.2

Methods for Handling Individual Characters

The Table 13.1 list all the methods to handle individual characters Method charAt(intindex) Purpose Returns the character at the specified index. getChars(intsrcBegin,intsrcEnd, char[]dst,intdstBegin)

Copies characters from this string into the destination character array. Returns the index within this string of the first occurrence of the specified character Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. Returns the index within this string of the last occurrence of the specified character.

indexOf(intch)

indexOf(intch, intfromIndex)

lastIndexOf(intch)

237

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

lastIndexOf(int chint fromIndex)

Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. replace(charoldChar,charnewChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar Table 13.1 Individual Character Handling Methods Example 2: The following code snippet handles individual characters of the string class example2 { public static void main(String args[]) { String str=Anna University; System.out.println(4th Character +str.charAt(4)); System.out.println(Index of Character U is +str.indexOf(U)); System.out.println(Last Index of Character i is +str.lastIndexOf(i)); char m[]=new char[10]; str.getChars(6,10,m,0); System.out.println(The String is +new String(m)); System.out.println(When n Changed to m +str.replace(n,m)); } } 13.3.3 Methods for Searching Strings

The Table 13.2 list all the methods to search strings Method startsWith(Stringprefix) Purpose Tests if this string starts with the specified prefix.

startsWith(Stringprefix,inttoffset) Tests if this string starts with the specified prefix beginning a specified index endsWith(Stringsuffix) Tests if this string ends with the specified suffix

Table 13.2 Methods to Search Strings


Anna University Chennai 238

DCS 115

OBJECT ORIENTED PROGRAMMING

Example 3: This example performs searches for a pattern in the given string. class example3 { public static void main(String args[]) { String str=Anna University; System.out.println(String Starts with Anna : +str.startsWith(Anna)); System.out.println(Ends With Anna : +str.endsWith(Anna)); } }
Output of the Program String Starts with Anna : true Ends With Anna : false

NOTES

13.3.4

Methods for Extracting Substrings

The Table 13.3 list all the methods to extract substrings Method substring(intbeginIndex) substring(intbeginIndex, Purpose Returns a new string that is a substring of this string. Returns a new string that is a substring of this string.

Table 13.3 Methods to Extract Substrings Example 4: This example extracts a substring from the given string class example4 { public static void main(String args[]) { String str=Anna University; System.out.println(Substring from 6th position : +str.substring(5)); System.out.println(Substring from 6th to 10th position : +str.substring(5,9)); } }
239 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Output of the Program Substring from 6th position : University Substring from 6th to 10th position : Univ

13.3.5

Methods for Case Conversion

The Table 13.4 list all the methods to convert the case of a character Method toLowerCase() toUpperCase() Purpose Converts all of the characters in this String to lower case Converts all of the characters in this String to upper case

Table 13.4 Methods to perform case conversion Example 5: The program given below perform case conversion. class example5 { public static void main(String args[]) { String str=Anna University; System.out.println( LowerCase +str.toLowerCase()); System.out.println( UpperCase +str.toUpperCase()); } }

Output of the Program LowerCase anna university UpperCase ANNA UNIVERSITY

Anna University Chennai

240

DCS 115

OBJECT ORIENTED PROGRAMMING

13.3.6

Methods for Type Conversion

NOTES

The Table 13.5 list all the methods to convert the data type Table 13.5 Methods to perform type conversion Method valueOf(type) getBytes(Stringenc) Purpose Returns the string representation of the type argument. Convert this String into bytes according to the specified character encoding, storing the result into a new byte array.

Example 6: The following performs type conversion class example6 { public static void main(String args[]) { String str=This is a test; int i=100; System.out.println(Bytes Representation +str.getBytes()); System.out.println(String value of integer 100 : +String.valueOf(i)); } }

Output of the Program Bytes Representation [B@10b62c9 String value of integer 100 : 100

241

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

13.3.7

Miscellaneous methods

The Table 13.6 list some miscellaneous methods Table 13.6 List of miscellaneous methods Method trim() length() Example 7: The following program finds the length of the string an eliminates white space from the front and the end of a String. class example7 { public static void main(String args[]) { String str=JAVA ; str=str.trim(); System.out.println(Length of the String is +str.length()); } } Purpose This method removes white space from the front and the end of a String. Returns length of the String.

Output of the Program Length of the String is 4


Have you understood? 1. 2. 3. 4. 5. Write the two string handling classes Strings in Java is represented as ____________ Which operator is used for concatenation of strings. List the methods used to find the index of a particular character. You want to check whether a particular string ends with ler, how will you achieve this? 6. What is the purpose of valueOf() method? 7. How will you find the length of a String? 13.4 StringBuffers

StringBuffer class is a mutable class unlike the String class which is immutable. Both the size and character string of a StringBuffer can be changed dynamically. String buffers are preferred when frequent modification of character strings is involved like appending,
Anna University Chennai 242

DCS 115

OBJECT ORIENTED PROGRAMMING

inserting, deleting, modifying etc. A StringBuffer method involves substantial overhead in terms of computational complexity and memory space hence StringBuffer class must be used only in situations where String class cannot be used. Strings can be obtained from string buffers. 13.4.1 Creation of StringBuffer

NOTES

A StringBuffer in Java can be created using the following three constructers. 1 2 3 StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100 StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16 StringBuffer strBuf1 = new StringBuffer(Computer); // Capacity is 24

The first constructer creates a StringBuffer that has the storage capacity to store 100 characters. The second constructer creates a StringBuffer that has the default storage capacity to store 16 characters. The last constructer creates a StringBuffer with a String parameter, it creates a StringBuffer with a capacity 24 i.e default capacity + 8 (the length of String parameter). 13.4.2 Methods in StringBuffer StringBuffer supports many methods that are available in String Class, apart from that StringBuffer supports some unique methods. The Table 13.7 list some frequently used methods. Method capacity() length() toString() insert(int offset, char c) delete(int start, int end) Purpose Returns the current capacity of the String buffer. Returns the length (character count) of this string buffer. Converts to a string representing the data in this string buffer Inserts the string representation of the char argument into the StringBuffer Removes the characters in a substring of this StringBuffer
243 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

replace(int start, int end, String str)

Replaces the characters in a substring of this StringBuffer with characters in the specified String. The character sequence contained in this string buffer is replaced by the reverse of the sequence. Appends the string to this string buffer.

reverse()

append(String str)

13.7 Methods in StringBuffer Example 8: The following illustrates the various StringBuffer methods. public class StringBufferMethods { public static void main(String[] args) { //Examples of Creation of Strings StringBuffer strBuf1 = new StringBuffer(APPLE); StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100 StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16 //Print the Capacity of StringBuffers System.out.println(strBuf1 capacity : +strBuf1.capacity()); System.out.println(strBuf2 capacity : +strBuf2.capacity()); System.out.println(strBuf3 capacity : +strBuf3.capacity()); //toString Method System.out.println(strBuf1 toString() is : +strBuf1.toString()); //append Method strBuf2.append(HandBook); System.out.println( strBuf2 is appended with :+ strBuf2.toString()); //insert Method strBuf2.insert(1, A); System.out.println(strBuf2 when A is inserted at 1 : +strBuf2.toString()); strBuf2.insert(2, n); System.out.println(strBuf2 when n is inserted at 2 :
Anna University Chennai 244

DCS 115

OBJECT ORIENTED PROGRAMMING

+strBuf2.toString()); //delete Method strBuf2.delete(2, n); System.out.println(strBuf2 when n is deleted at 2 : +strBuf2.toString()); //reverse Method strBuf2.reverse(); System.out.println(Reversed strBuf2 : +strBuf2);

NOTES

} }
Output of the Program strBuf1 capacity : 21 strBuf2 capacity : 100 strBuf3 capacity : 16 strBuf1 toString() is : APPLE strBuf2 is appended with :HandBook strBuf2 when A is inserted at 1 : HAandBook strBuf2 when n is inserted at 2 : HAnandBook strBuf2 when n is deleted at 2 : HA Reversed strBuf2 : AH

Have you understood? 1. 2. 3. 4. How does StringBuffer class differs from String class Create a StringBuffer with a capacity 100. What is the default StringBuffer capacity ? How will you find the capacity() of a StringBuffer ?

Summary Handling character strings in Java is supported through two final classes: String and StringBuffer. The String class implements immutable character strings, which are read-only once the string has been created and initialized, whereas the StringBuffer class implements dynamic character strings. Strings in Java are 16-bit Unicode Strings in java can be compared using the = operator and equals() method.

245

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Strings can be concatenated using + operator and concat() method. The charAt()method returns the character at the specified index. The toLowerCase() method converts all of the characters in this String to lower case The toupperCase() method converts all of the characters in this String to upper case The getBytes() method convert this String into bytes according to the specified character encoding, storing the result into a new byte array. The trim() method removes white space from the front and the end of a String The length() method returns the length of the String. StringBuffer class is a mutable class . The default capacity for a StringBuffer is 16 The capcity() method returns the current capacity of the String buffer. The character sequence contained in this StringBuffer is replaced by the reverse of the sequence by using reverse() method Exercises Short Questions 1. String class represents __________ 2. Write the different ways of creating strings 3. ________ method is used to concatenate two strings 4. Write the signature of getChars() method 5. Write the two different forms of startsWith() method 6. How will you search a substring in a string? 7. The trim() method is used for ____________ 8. Write the different ways of creating StringBuffer 9. Write the syntax of delete method 10. How will you reverse a string? Long Questions 1. Explain the different ways of creating Strings and discuss some methods available in it 2. What is StringBuffer? Mention its advantages. Discuss some methods available in it Programming Exercises 1. Write a program to create two strings and perform the following operations (a) find the length of the string (b) concatenate the two strings (c) compare the two strings

Anna University Chennai

246

DCS 115

OBJECT ORIENTED PROGRAMMING

(d) display the location of the vowels in both strings (e) convert both the strings to uppercase (f) print the byte representations of the strings 2. Write a program to create a StringBuffer and perform the following operations (g) print the capacity of the string (h) reverse the string (i) append hello at the end of the string (j) delete characters from 2 to 4 in the string. Answers to Have you Understood Questions Section 13.3 1. 2. 3. 4. 5. String and StringBuffer 16 bit Unicode characters + indexOf() and lastindexOf() by using endsWith() method and passing ler as parameter to that method 6. It returns the string representation of the argument passed. 7. By using length() method. Section 13.4 1. StringBuffer class is a mutable class unlike the String class which is immutable 2. StringBuffer strBuf2 = new StringBuffer(100) 3. 16 4. The capacity() method returns the current capacity of the String buffer. References 1. Java 2 Certification Guide Author: Jamie Jaworski Publisher: New Riders 2000 http:\\www.sun.com Thinking in Java Author: Bruce Eckel Publisher : Prentice Hall 2000

NOTES

2. 3.

247

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

4.

Programming with Java Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Java 2: The Complete Reference Author : Patrick Naughton & Herbert Schildt Publisher : Tata Mcgraw Hill 2000 Java in a Nutshell Author:David Flanagan Publisher :OReilly 1999

5.

6.

Anna University Chennai

248

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 14
I N T E R F A C E S

14.1

Interfaces and Classes Interface Inheritance Defining an Interface Accessing Interface Variables Implementing Interfaces Introduction

Some languages support multiple inheritance in which a child class may derive some of its features from more than one parent class. This feature is not directly supported by java. However, java does provide a mechanism called an interface whereby the properties of one class can be used by another without formal inheritance. This chapter introduces you to interfaces and its relative components. You will learn about the differences between classes and interfaces. This chapter then introduces you how to define and implement an interface. Finally interface inheritance is discussed in this chapter. 14.2 1 2 3 4 5 14.3 Learning Objectives To introduce interface concept in Java To present the difference between an interface and a class To show how to define an interface To discuss how to implement an interface To introduce interface inheritance concept. Interfaces and Classes

Interfaces are used to define a standard behavior that can be implemented by any class in a class hierarchy. An interface declares a set of methods with their signatures. These methods will not have implementation part hence all the methods declared in an interface are abstract methods. All the methods in the interface are public by default. An interface can also have set of instance variables however all these variables are constant by default.
249 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Interfaces are almost similar to classes but however there exist few differences between them. These differences are listed in a Table 14.1. S/N INTERFACES 1. 2. 3. An interface will have only declaration of methods with their signatures All the methods in an interface are public methods All the variables declared in the interfaces are final variables i.e constant variable by default. Interfaces must be implemented by some class and that class should override all the methods present in the interface Objects cannot be created for a interface however it is possible to create reference for a interface CLASSES A class will have methods with their declaration and implementation A class can have methods in all visibility modes A class can have both final and non final variables. A class if necessary can be extended (inherited) by other classes.

4.

5.

Objects can be created for classes

Table 14.1 Comparison of Interfaces and Classes 14.3.1 Defining an Interface

As mentioned earlier interfaces are similar to classes the general form of declaring an interface: interface interfacename { // final variables declaration //methods declaration } Here is an example of an interface declaration called clock. interface clock { public int cur_time; void getCurrentTime(); void setCurrentTime(); void showClock(); }

Anna University Chennai

250

DCS 115

OBJECT ORIENTED PROGRAMMING

14.3.2

Implementing Interfaces

NOTES

After creating an interface we can create classes that implement the interface. A class that is implementing a interface should have the following properties. 1 2 A class that implements the interface must override all the methods present in the interface If a class overrides only a partial set of methods in the interface then in that case the class must be declared as abstract

The general syntax for a class that implements an interface is given below. [accessmode] class classname [extends superclass] implements interface1,interface2. { //body of the class. } An example is given below class tick implements clock { public void getCurrentTime() { //body of the method. } public void setCurrentTime() { //body of the method. } public void showClock() { //body of the method. } } Example 1: A simple example is given below that give complete details about how to create and make use of an interface. interface arithmetics { public int result;
251 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
}

void add(int x,int y); void sub(int x,int y); void mul(int x,int y); void div(int x,int y);

class calculator implements aritmetics { calculator() { x=1; y=1; } calculator(int m,int n) { x=m; y=n; } public void add(int x,int y) { result=x+y; System.out.println(SUM IS +result); } public void sub(int x,int y) { result=x-y; System.out.println(DIFFERENCE IS +result); } public void mul(int x,int y) { result=x*y; System.out.println(PRODUCT IS +result); } public void div(int x,int y) { if(x<y) System.out.println(RESULT WILL BE A REAL VALUE): else { result=x/y; System.out.println(QUOTIENT IS +result); } } public static void main(String args[])
Anna University Chennai 252

DCS 115

OBJECT ORIENTED PROGRAMMING

{ calculator cal =new calculator(25,5); cal.add(); cal.sub(); cal.mul(); cal.div(); } } Since java does not support multiple inheritance directly often we want to extend one parent class and implement many interfaces. For example class myclass extends Frame implements ActionListener,ItemListener { // body of the class. } Here we can note that the class myclass inherits the properties of the parent class Frame and implements to interfaces namely ActionListener and ItemListener. Example 2: In this example the class client extends the class dimension2 and implements the interface dimension1. interface dimension1 { final int xvalue; public void getx(int); } class dimension2 { int yvalue; void gety(int b) { yvalue=b; } } class client extends dimension2 implements dimension1 { public void getx(int a) {
253

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

xvalue=a; } void disp() { System.out.println(XVALUE IS +xvalue); System.out.println(YVALUE IS +yvalue); } public static void main(String args[]) { client obj=new client(); obj.getx(10); obj.gety(10); obj.disp(); } } Have you understood? 1. 2. 3. 4. Define an interface. Mention its contents. All the methods in an interface are________ by default. Objects can be created for an interface (True/False) If a class overrides only a partial set of methods in the interface then in that case the class must be declared as _________

14.4 Interface Inheritance You have learnt that in java a class can inherit the properties of other classes, similar to this an interface can inherit the properties of another interface. The syntax is the same as for inheriting classes. You have to use the keyword extends to implement the inheritance. Example 3: This example implements interface inheritance concept. interface inf1 { int i=100; public void disp_i(); } interface inf2 extends inf1 { double j=55.8;
Anna University Chennai 254

DCS 115

OBJECT ORIENTED PROGRAMMING

public void disp_j(); } class client implements inf2 { public void disp_i() { System.out.println(INTEGER FROM INTERFACE INF1 IS +i); } public void disp_j() { System.out.println(DOUBLE FROM INTERFACE INF2 IS +j); } public static void main(String args[]) { client cli=new client(); cli.disp_i(); cli.disp_j(); } } An interface can also inherit properties of more than one interface. In this case also we have to use the keyword extends. Here is the example Example 4: In this program the interface inf3 inherits the properties of inf1 and inf2 interface inf1 { public void meth1(); } interface inf2 { public void meth2(); } interface inf3 extends inf1,inf2 { public void meth3(); } class client implements inf3 {
255

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

client() { System.out.println(Constructer for client); } public void meth1() { System.out.println(THIS IS FROM INF1); } public void meth2() { System.out.println(THIS IS FROM INF2); } public void meth3() { System.out.println(THIS IS FROM INF3); } public static void main(String args[]) { client cli=new client(); cli.meth1(); cli.meth2(); cli.meth3(); } } Have you understood? 1. Explain how interface inheritance is achieved 14.5 Accessing Interface Variables You have already learnt that an interface can contain variables. All the variables that are declared in the interface are final variables. Declaring some variables in an interface is similar to declaring #defined constants in C/C++ languages or const variables. When you create some variables in an interface without any methods, then the class implementing that interface will not have any method to override .Hence the class will import only the constants from the interface. The final variables in such interface can act as shared constants. Example 5: The example given below show the procedure to access interface variables. interface constants

Anna University Chennai

256

DCS 115

OBJECT ORIENTED PROGRAMMING

{ int BAD=0; int GOOD=1; } class test implements constants { int mark; ex1(int a) { mark=a; } int check() { if(mark>=50) return GOOD; else return BAD; } public static void main(String args[]) { test e=new test(77); int x=e.check(); if(x==GOOD) System.out.println(Well Done !!!!); else System.out.println(Better Luck Next Time !!!!); } } Have you understood? 1. An interface is having only final variables then these variables can act as____________ Summary 1 Interfaces are used to define a standard behavior that can be implemented by any class in a class hierarchy. Interfaces are used to achieve multiple inheritance 2 All the methods in an interface are public methods and all the variables are final.
257

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

A class that implements the interface must override all the methods present in the interface A class can implement more than one interface An interface can inherit the properties of another interface An interface can also inherit properties of more than one interface. In this case also we have to use the keyword extends. The final variables in interface can act as shared constants. Exercises Short Questions 1. 2. 3. 4. How Java achieves multiple inheritance? How an interface differs from classes? How an interface differs from abstract class? A class will __________ an interface , and overrides all _________ methods 5. Interfaces can inherit another interface (True/False) 6. Mention some uses of declaring variables in a interface Long Questions 1. Write short notes on interfaces 2. Explain how interfaces are used to achieve multiple inheritance. Programming Exercises 1. Create an interface to create shared constants. Create a class to access these variables 2. Create an interface called shape with a method area(). Create classes Rect,Square and circle and override the area() method. Answers to Have you Understood Questions Section 14.3 1. Interfaces are used to define a standard behavior that can be implemented by any class in a class hierarchy. An interface contains variables declaration and a set of methods with their signatures. 2. public 3. False 4. abstract

Anna University Chennai

258

DCS 115

OBJECT ORIENTED PROGRAMMING

Section 14.4 1. An interface can also inherit properties of more than one interface. In this case also we have to use the keyword extends. Section 14.5 1. Shared constants ; References 1. Java 2 Certification Guide Author: Jamie Jaworski Publisher: New Riders 2000 http:\\www.sun.com Thinking in Java Author: Bruce Eckel Publisher : Prentice Hall 2000 Programming with Java Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Java 2: The Complete Reference Author : Patrick Naughton & Herbert Schildt Publisher : Tata Mcgraw Hill 2000 Java in a Nutshell Author:David Flanagan Publisher :OReilly 1999

NOTES

2. 3.

4.

5.

6.

259

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 15 PACKAGES
Java API Packages User Defined Packages Using Java API Packages Visibility and Access Rights in Java Hiding classes

15.1 Introduction Code reuse is an import concept in object-oriented programming. One tool that can help us increase the reusability of our code is the package statement. Programmers bundle groups of related types into packages. A Java package is a mechanism for organizing java classes and interfaces. Packages are also called as containers of classes.Java packages can be stored in compressed files called JAR files, allowing classes to download faster as a group rather than one at a time. Programmers also typically use packages to organize classes belonging to the same category or providing similar functionality. A package in java can contain the following members Classes Interfaces Enumerations Annotations

Java language supports two types of packages. They are Built in Packages (or) Java API packages User Defined Packages

This chapter introduces you to both the categories of packages. You will also learn how to create your own package and use it in your programs. This chapter also presents the various access specifiers used in the package.

Anna University Chennai

260

DCS 115

OBJECT ORIENTED PROGRAMMING

15.2 15.3

Learning Objectives To introduce the package concept in Java To discuss Java API packages To discuss how to create user defined and use them in your programs To discuss access and visibilty rights in Java Java API Packages

NOTES

Java langauage has a rich set of built in API packages from which you can access interfaces and classes, and then fields, constructors, and methods.The Figure 15.1 gives the list of Java API packages.

lang io util JAVA awt image

applet

peer

net

Figure 15.1 Java API packages The details regarding these packages are given below. java.lang Package that contains essential Java classes, including numerics, strings, objects, compiler, runtime, security, and threads. This is the only package that is automatically imported into every Java program.

261

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

java.io Package that provides classes to manage input and output streams to read data from and write data to files, strings, and other sources. java.util Package that contains miscellaneous utility classes, including generic data structures, bit sets, time, date, string manipulation, random number generation, system properties, notification, and enumeration of data structures. java.net Package that provides classes for network support, including URLs, TCP sockets, UDP sockets, IP addresses, and a binary-to-text converter. java.awt Package that provides an integrated set of classes to manage user interface components such as windows, dialog boxes, buttons, checkboxes, lists, menus, scrollbars, and text fields. (AWT = Abstract Window Toolkit) java.awt.image Package that provides classes for managing image data, including color models, cropping, color filtering, setting pixel values, and grabbing snapshots. java.awt.peer Package that connects AWT components to their platform-specific implementations (such as Motif widgets or Microsoft Windows controls). java.applet Package that enables the creation of applets through the Applet class. It also provides several interfaces that connect an applet to its document and to resources for playing audio. 15.3.1 Using Java API Packages In Java packages are organized in a hierarchical structure. The Java Package name consists of words separated by periods. The first part of the name contains the

Anna University Chennai

262

DCS 115

OBJECT ORIENTED PROGRAMMING

name java. The remaining words of the Java Package name reflect the contents of the package. The Java Package name also reflects its directory structure. For example the statement java.awt

NOTES

represents the awt (Abstract Window Toolkit) package. As mentioned earlier the first part of the package name starts with the word Java. The second part of the package name awt stands for the contents of the package, in this case the Abstract Window Toolkit. To import a class from the package into our program you have to use the import statement. The syntax is import packagename.classname or import packagename.*; 1. The first form of the syntax imports the specific class from the package .For example the statement import java.util.Date imports the Date class available in the java.util package into our program. 2. The second form of the syntax import all the classes available in the specified package. For example java.io.* will import all the classes available in the io package. It is always good to import only the classes you need. Bringing in an entire package does not alter the size of the class file, but does lengthen the compile time. Have you understood? 1. What do you mean by a Package? 2. Mention the two types of packages available in Java. 3. Which statement you will use to import a package to your program? 15.4 User Defined Packages

You know that java supports a rich set of built in packages. Apart from these packages Java allows us to create our own user defined packages. We can create our own package and use it in our programs. Creation of package in java is easy. The various steps involved in creation of package are listed below. 1. The package has to be declared at the beginning of the program. The syntax is package packagename;
263 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
2.

For example package mypack; The second step is to define classes and interfaces and put it inside the package. A package can contain any number of classes; however one of the classes should have the public access specifier. For example package mypack public class sample { //body of the class } Add methods and variables to class as required Create a subdirectory with name of the package and put it under the current working directory. Save the class in the subdirectory and compile the program.

3. 4. 5.

Example 1: A simple program to illustrate the creation of user-defined package is given below.

package mypack; public class sample { public sample() { System.out.println(This is from the constructer); } public void test() { System.out.println(This is from the package mypack); } } Create a directory with the name mypack and put inside the current working directory. Save the program with the name sample.java put in the sub directory mypack and compile the program. Once a package is created, you can import the package and use it in your program. Consider the code listing given below. import mypack.sample class Client { public static void main(String args[]) {
Anna University Chennai 264

DCS 115

OBJECT ORIENTED PROGRAMMING

sample s=new sample(); s.test(); } } The program Client imports the classes from package mypack. The program Client.java should be saved in the directory for which mypack is a subdirectory. After that compile and execute the program
Output of the Program This is from the constructer This is from the package mypack

NOTES

Example 2: In Java it is possible to access a class in one package from another package.

package pack1; class base { public String str=JAVA; protected int i=20; public void print_string() { System.out.println(The String is +str); } public void print_int() { System.out.println(The Integer is +i); } } The class base is available in the package pack1. Now lets create another package pack2 which contains a class that access the class base package pack1; import pack1.*; class X {
265 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

public static void main(String args[]) { base b=new base(); b.print_string(); b.print_int(); } } Thus in Java it is possible to access a class in one package from another package.

Output of the Program The String is JAVA The Integer is 20

15.4.1 Visibility and Access Rights in Java The table 15.1 lists the visibility and access rights in java. ACCESS RIGHTS FOR THE DIFFERENT SCOPES CLASS\ACCESS RIGHTS own class (Base) subclass - same package (SubA) class - same package (AnotherA) subclass - another package (SubB) class - another package (AnotherB) PRIVATE DEFAULT PROTECTED PUBLIC SCOPE SCOPE SCOPE SCOPE yes no no no no yes yes yes no no yes yes yes Yes/No * no yes yes yes yes yes

Table 15.1 Access Rights in Java

Note: Class subB has access only to the inherited from Base protected elements, i.e. its own elements, but the protected data of other Base instances is not accessible from SubB.

Anna University Chennai

266

DCS 115

OBJECT ORIENTED PROGRAMMING

Example 3: This example program illustrates the access rights for different scopes available in java. Consider a class base available in the package pack1. package pack1; public class Base { public String publicStr = public ; protected String protectedStr = protected String defaultStr = default; private String privateStr = private

NOTES

public void print() { System.out.println( From Package Pack1 and Class Base); System.out.println( publicStr); System.out.println( protectedStr); System.out.println(defaultStr); System.out.println(privateStr); } } Case1 (Sub Class in the Same Package) Now let us create a subclass for the class base in the same package. package pack1; public class Derived extends Base { public void print() { System.out.println(Same Package Sub class); System.out.println( publicStr ); System.out.println( protectedStr); System.out.println(defaultStr); System.out.println(privateStr); //will not compile } } From this example we can note that a private variable cannot be accessed by a sub class even if the subclass resides in the same package.

267

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Case 2(Same Package and Other Classes) package pack1; public class Someclass { public void print() { System.out.println(Same Package Some class); Base b=new Base (); System.out.println(b. publicStr ); System.out.println(b.protectedStr); System.out.println(b.defaultStr); System.out.println(b.privateStr); //will not compile } } A variable that is declared private cannot be accessed from any other class. Case 3(Other Package Sub Class) package pack2; import pack1.Base; public class Derived1 extends Base { public void print() { System.out.println (Other Package Sub Class); System.out.println (publicStr); System.out.println (protectedStr); System.out.println(b.defaultStr); //will not compile System.out.println(b.privateStr); //will not compile } } In a subclass of another package only public and protected variables are accessible. Case 4(Other Package Other Class) package pack2; import pack1.Base; public class Someclass { public void print()

Anna University Chennai

268

DCS 115

OBJECT ORIENTED PROGRAMMING

{ System.out.println (Other Package Other Class); Base b=new Base(); System.out.println (b.publicStr); System.out.println (protectedStr); //will not compile System.out.println(b.defaultStr); //will not compile System.out.println(b.privateStr); //will not compile } } Only public variables are accessible by a non subclass residing in some other package. Have you understood? 1. A variable has a default scope, is it possible to access that variable from another class from the same package (Yes/No) 2. What access specifier should be specified if you wish to access a variable from a sub class present in another package? 3. A variable with _________ scope can be accessed from a non subclass present in another package. 15.5 Hiding Classes

NOTES

When a package is imported to your program all the public classes will be imported to your program. Sometimes it may be desired to hide some classes in the package because accessing them may lead to some problems. To hide such classes these classes must be declared with a access specifier other than public. These non public classes will be hidden when the package is imported to another program. Consider the example package pack1; public class Publicclass { //body of the class } class Defaultclass { //body of the class } In this example the class Publicclass with the public scope is visible to programs importing the package pack1. The class Defaultclass with no access specifier is hidden to programs importing the package pack1. Thus,
269 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

import pack1.*; class test { public static void main(String args[]) { Publicclass p1; //OK Defaultclass d1; //ERROR .. .. } } Have you understood? 1. How will you hide a class in a package?

Summary A Java package is a mechanism for organizing java classes and interfaces. Packages are also called as containers of classes. A package in java can contain classes,interface,enumerations and annotations The Java Package name consists of words separated by periods. The first part of the name contains the name java. The remaining words of the Java Package name reflect the contents of the package To import a class from the package into our program you have to use the import statement. A package can contain any number of classes; however one of the classes should have the public access specifier. A private variable cannot be accessed by a sub class even if the subclass resides in the same package In a subclass of another package only public and protected variables are accessible. Only public variables are accessible by a non subclass residing in some other package. These non public classes in a package will be hidden when the package is imported to another program. Exercises Short Questions 1. List the members of a package 2. What is a JAR file?
Anna University Chennai 270

DCS 115

OBJECT ORIENTED PROGRAMMING

3. List the Java API packages 4. Write some contents of java..util package 5. Bringing the entire package to your program increases the compilation time (True/False) 6. Give a note on protected specifier 7. Which has a wider scope protected (or) default? Why? Long Questions 1. Explain the various steps involved in creating a user defined package 2. Give a brief note on access specifiers applied to packages. Programming Exercises 1. Create a package with a class called Bank. Add constructors and methods to compute simple and compound interest. Import the package into another program and make use of the methods. Apply appropriate access specifiers to the variables and methods. Answers to Have you Understood Questions Section 15.3 1. A Java package is a mechanism for organizing java classes and interfaces. Packages are also called as containers of classes. 2. Buit in Packages (or) Java API packages and User defined packages 3. import statement Section 15.4 1.Yes 2.public or protected 3.public. Section 15.5 1. By making that class non public. References 1. Java 2 Certification Guide Author: Jamie Jaworski Publisher: New Riders 2000

NOTES

271

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

2. 3.

http:\\www.sun.com Thinking in Java


A uthor: Bruce Eckel Publisher : Prentice Hall 2000

4.

Programming with Java A uthor: E Balagurusamy Publisher: Tata M cgraw Hill 2000 Java 2: The Complete Reference A uthor: Patrick Naughton & Herbert Schildt Publisher: Tata M cgraw Hill 2000 Java in a Nutshell A uthor: David Flanagan Publisher: O Reilly 1999

5.

6.

Anna University Chennai

272

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

CHAPTER 16 MULTITHREADED PROGRAMMING


16.1 Threads in Java Sleep Method Creating Threads Yield Method Extending Thread class Stop Method Implementing Runnable Interface Thread Priority Life Cycle of Thread Synchronization Thread Methods Introduction

The earliest computers did only one job at a time. All programs were run sequentially, one at a time; and each had full run of the computer. However two programs couldnt be run at once. This kind of processing is called batch processing. It is one of the earliest computing technologies Time sharing systems were invented after batch processing to allow multiple people to use the computer at the same time. On a time sharing system many people can run programs at the same time. The operating system is responsible for splitting the time among the different programs that are running. Once systems allowed different users to run programs at the same time the next step is to allow the same user run multiple programs simultaneously. Each running program (generally called a process) had its own memory space, its own set of variables, its own stack and heap, and so on. The ability to execute more than one task at the same time is called Multitasking. The terms multitasking and multiprocessing are often used interchangeably, although multiprocessing sometimes implies that more than one CPU is involved. In multitasking, only one CPU is involved, but it switches from one program to
273 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

another so quickly that it gives the appearance of executing all of the programs at the same time. The systems terminology of multitasking is multithreading. In multithreading a process is divided into two or more sub processes, these sub processes are allowed to execute simultaneously. For example a program, can print a file at the same time it can downloads a page and formats the page as it downloads. Threads are also called as lightweight processes. This chapter introduces to multithreaded programming. You will learn how to create multiple threads in your program and execute them simultaneously. This chapter also discuss about life cycle of a thread. This chapter also introduces you to thread priority and synchronization. 16.2 1 2 3 4 5 6 7 8 16.3 Learning Objectives To introduce thread concept To present the two ways of creating threads To show how to create threads by extending Thread class To show how to create threads by implementing runnable interface To discuss life cycle of thread To discuss some thread methods To present thread priority To introduce synchronization concept Threads in Java

Thread is a sequential flow of control. In Java every program consists of at least one thread - the one that runs the main method of the class provided as a startup argument to the Java virtual machine (JVM). Thread in java has a beginning part, the body part and the termination part. All the programs discussed in the previous chapters are single threaded programs however Java supports multithreading and hence in Java it is possible to create multiple flow of control and allow them to execute simultaneously. A program that has multiple flow of control is called Multithreading. Multithreading is one of the most powerful feature available in java. As mentioned earlier every java program has a single default thread (the one that runs the main method) that controls the execution of the code. This main() method thread is the first thread that will start its execution. We can use this main method thread to create many child threads to implement multithreaded programming. All the child threads created by the main thread will complete its execution part before the main thread. Thus in a java program main() method thread is the first thread to start and it is the last one to finish its execution. In a multithreaded program all the threads executes concurrently and share resources. Since one processor is responsible for executing all the threads, the java
Anna University Chennai 274

DCS 115

OBJECT ORIENTED PROGRAMMING

interpreter performs switching of control between the running threads. This concept is known as context switching in a thread.

NOTES

MAIN THREAD Start Start Start Start

CHILD THREAD1

CHILD THREAD2

CHILD THREAD3

..

CHILD THREAD n

Fig 16.1 Multithreaded Program

Have you understood? 1. Define Thread. 2. All the child threads are created by __________ thread 3. What do you mean by Context Switch? 16.4 Creating Threads

To create threads, Java has a class called Thread and this class is available in the java.lang package. Java supports two different ways of creating threads. They are 1 2 Extending the Thread class Implementing the Runnable interface

In both the cases we have to override the method called run(). The run() method will contain the code required by the thread. The syntax of run() method is given below. public void run() { // body of method }

275

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

16.4.1 Extending Thread class The simple way to create a threaded program is to extend the thread class. Any class that extends Thread class can access all the methods available in the thread. The steps to create a threaded program are given below. Step1: Create a class that extends thread. For example class myclass extends Thread { // Body of the class } Step 2: Override the run() method and write the code required by the thread class myclass extends Thread { public void run() { //body of the run method. } } Step 3: Create the object for the threaded class and start the thread using start() method. For example myclass mc=new myclass() mc.start() Example 1: The following is a simple example for multithreaded program class Two_table extends Thread

Anna University Chennai

276

DCS 115

OBJECT ORIENTED PROGRAMMING

{ public void run() { for(int i=1;i<=10;i++) { System.out.println(i + * 2 = + i*2) } } } class Three_table extends Thread { public void run() { for(int i=1;i<=10;i++) { System.out.println(i + * 3 = + i*3) } } } class Four_table extends Thread { public void run() { for(int i=1;i<=10;i++) { System.out.println(i + * 4 = + i*4) } } } class mainprg { public static void main(String args[]) { Two_table two=new Two_table(); Two.start(); Three_table three=new Three_table(); Three.start(); Four_table four=new Four_table(); four.start(); } } The output of the program is given here.
277

NOTES

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

From the output we can note that all the three threads were executed simultaneously. 16.4.2 Implementing Runnable Interface The next method of creating a thread is to create a class and making that class to implement runnable interface. Since java does not support multiple inheritance directly we often use runnable interface for creating threads. The various steps for creating a multithreaded program in this method are listed below. Step1: Create a class that implements runnable interface. For example class myclass implements Runnable { // Body of the class }

Anna University Chennai

278

DCS 115

OBJECT ORIENTED PROGRAMMING

Step 2: Override the run() method and write the code required by the thread class myclass implements Runnable { public void run() { //body of the run method. } } Step 3: Create the object for the Thread and pass the object of the class myclass as a parameter. For example myclass mc=new myclass() Thread t=new Thread(mc); Example 2: The program given in the example1 is modified by implementing the runnable interface.

NOTES

class Two_table implements Runnable { public void run() { for(int i=1;i<=10;i++) { System.out.println(i + * 2 = + i*2) } } } class Three_table implements Runnable { public void run() {
279 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
} }

for(int i=1;i<=10;i++) { System.out.println(i + * 3 = + i*3) }

class Four_table implements Runnable { public void run() { for(int i=1;i<=10;i++) { System.out.println(i + * 4 = + i*4) } } } class mainprg { public static void main(String args[]) { Two_table two=new Two_table(); Three_table three=new Three_table(); Four_table four=new Four_table(); Thread t1=new Thread(two); t1.start(); Thread t2=new Thread(three); t2.start() Thread t3=new Thread(four); T3.start(); } }

Anna University Chennai

280

DCS 115

OBJECT ORIENTED PROGRAMMING

Output of the Program

NOTES

Have you understood? 1. What are the two ways of creating Threads? 2. Write the signature of run() method. 3. How will you make a thread to run?

16.5

Life Cycle of Thread

When a new thread is created it passes through various states before it gets terminated and this process is called the Life Cycle of the Thread. The following figure shows the states a thread can pass in during its life and illustrates which method calls cause a transition to another state.

281

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
Runnable New Thread Start Running Suspend Not Running

Notify

The Run Method Terminates/Killed Dead Fig 16.2 Life Cycle of a Thread

Once the Thread class is instantiated a new thread is created and its life cycle begins A newly created thread enters the active running state when the start() method of the thread is invoked A running thread may be blocked, when blocked it enters the inactive not running state and waits until it is notified to run. A thread may be blocked because o It has been put to sleep for a set amount of time o It is suspended with a call to suspend() and will be blocked until a resume() message o The thread is suspended by call to wait(), and will become runnable on notify or notifyAll message. Once the thread completes its run() method or when killed by some other process it enters the dead state, that is the end of threads life cycle. Have you understood? 1. What do you mean by life cycle of a thread ? 2. List out the various thread states ? 3. How will you make a suspended thread to run ? 16.6 Thread Methods

Apart from the start() and run() method, a thread class supports the following methods that causes the state transition of a thread.

Anna University Chennai

282

DCS 115

OBJECT ORIENTED PROGRAMMING

sleep() method yield method() stop() method 16.6.1 Sleep Method

NOTES

The sleep method is static and pauses execution for a set number of milliseconds, here is an example of putting a Thread to sleep. The sleep method throws InterruptedException. Here is an example for sleep method. Example 3: The following program illustrates sleep method of Thread class. public class ThreadSleep extends Thread { public void run() { try { for(int i=0;i<5;i++) { this.sleep(1000); System.out.println(looping for + i + time); } }catch(InterruptedException ie){} } public static void main(String args[]) { ThreadSleep t = new ThreadSleep(); t.start(); } } 16.6.2 Yield Method Java Thread class has a static method called yield which causes the currently running thread to yield its hold on CPU cycles. This thread returns to the ready to run state and the thread scheduling system has a chance to give other threads the attention of the CPU. If no other threads are in a ready to run state the thread that was executing may restart running again. Here is an example for yield method

283

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Example 4: The following program illustrates yield method of Thread class. class ThreadYeild extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println(looping for + i + time); if(i==4) yield(); } } } 16.6.3 Stop Method Stop method in java forces the thread to stop executing. Example 5: The following program illustrates stop method of Thread class. class ThreadStop extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println(looping for + i + time); if(i==4) stop(); } } public static void main(String args[]) { ThreadStop st=new ThreadStop(); st.start(); } } The output of the code is given below.

Anna University Chennai

284

DCS 115

OBJECT ORIENTED PROGRAMMING

Output of the Program looping for 1 time looping for 2 time looping for 3 time looping for 4 time

NOTES

Have you understood? 1. Which exception is thrown when sleep method is called ? 2. What is the purpose of yield method ? 3. What is the purpose of stop method ? 16.7 Thread Priority

When a Java thread is created, it inherits its priority from the thread that created it.Each Thread has a priority, ranging between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY (defined as 1 and 10 respectively). The higher the integer, the higher the priority. At any given time, when multiple threads are ready to be executed, the runtime system chooses the Runnable thread with the highest priority for execution. Only when that thread stops, yields, or becomes not runnable for some reason the lower priority thread start executing. If two threads of the same priority are waiting for the CPU, the scheduler chooses one of them to run in a round-robin fashion. Here are some important points regarding thread priority.

By default, each new thread has the same priority as the thread that created it. The initial thread associated with a main by default has priority Thread.NORM_PRIORITY (5). The current priority of any thread can be accessed via method getPriority. The priority of any thread can be dynamically changed via method setPriority.

Example 6: This program creates threads with different priorities. class A extends Thread { public void run() { for(int i=1;i<=5;i++) {
285 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES
} }

System.out.println(i+ From A ) }

class B extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println(i+ From B ) } } } class C extends Thread { public void run() { for(int i=1;i<=5;i++) { System.out.println(i+ From C) } } } class mainprg { public static void main(String args[]) { A a=new A(); A.setPriority(Thread.MIN_PRIORITY); a.start(); B b=new B(); b.setPriority(b.getPriority()+1); b.start(); C c=new C(); c.setPriority(Thread.MAX_PRIORITY); four.start(); } }
Anna University Chennai 286

DCS 115

OBJECT ORIENTED PROGRAMMING

Output of the Program 1 From A 1 From B 1 From C 2 From C 2 From B 3 From C 2 From A 3 From B 4 From C 5 From C 3 From A 4 From B 4 From A 5 From B 5 From A

NOTES

Have you understood? 1. What is the value for MIN_PRIORITY, MAX_ PRIORITY, and NORM_ PRIORRITY? 2. How will you get the priority of the running thread? 16.8 Synchronization

Generally in a multithreaded environment all the threads share some critical resources such as a block of code. In many situations these resources has to be exclusively accessed, otherwise strange bugs can arise. Java provides a way to lock the shared resources for a thread which is currently executing it, and making other threads that wish to use it wait until the first thread is finished. These other threads are placed in the waiting state. To lock such shared resources java supports synchronization of threads i.e. providing an exclusive access to a thread currently accessing the shared resource. Java has a keyword called synchronized that has to be prefixed before the method declaration that contains the code to access the shared resource. For example synchronized void access_resource() { //block of the code to be synchronized. . . }
287 Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

When we declare a method as synchronized, Java creates a monitor (which is the basis of thread synchronization). A monitor is an object that can block and revive threads. A monitor is simply a lock that serializes access to an object or a class. To gain access, a thread first acquires the necessary monitor, and then proceeds. This happens automatically every time when a thread enters a synchronized method. During the execution of a synchronized method, the thread holds the monitor for that methods object, or if the method is static, it holds the monitor for that methods class. If another thread is executing the synchronized method, the current thread is blocked until that thread releases the monitor (by either exiting the method or by calling wait()). Have you understood? 1. What do you mean by synchronization of threads? 2. What do you mean by a monitor ? Summary Thread is a sequential flow of control. In Java every program consists of at least one thread - the one that runs the main method of the class. Thread in java has a beginning part, the body part and the termination part. Java supports two different ways of creating threads. The first way is to extend the Thread class and the next method is to implement the Runnable interface. In both the cases we have to override the method called run(). When a new thread is created it passes through various states before it gets terminated and this process is called the Life Cycle of the Thread. The newly created thread will pass through the following states in its life time. They are New thread (Born state), Running state, Not running state ,Dead state A running thread may be blocked, when blocked it enters the inactive not running state and waits until it is notified to run Once the thread completes its run() method or when killed by some other process it enters the dead state, that is the end of threads life cycle. The sleep method is static and pauses execution for a set number of milliseconds Java Thread class has a static method called yield which causes the currently running thread to yield its hold on CPU cycles. Stop method forces the thread to stop its execution Each Thread has a priority, ranging between Thread.MIN_PRIORITY and Thread.MAX_PRIORITY (defined as 1 and 10 respectively).

Anna University Chennai

288

DCS 115

OBJECT ORIENTED PROGRAMMING

The initial thread associated with a main by default has priority Thread.NORM_PRIORITY (value 5) The current priority of any thread can be accessed via method getPriority. The priority of any thread can be dynamically changed via method setPriority Synchronization of threads is used to provide an exclusive access to a thread currently accessing the shared resource A monitor is an object that can block and revive threads.A monitor is simply a lock that serializes access to an object or a class. Exercises Short Questions 1. 2. 3. 4. 5. 6. 7. 8. What do you mean by Multitasking? Define process What is Multithreading concept? In which situations extending thread will not be possible? When the thread go to the dead state? what is the purpose of stop() method Write the steps to change the priority of the current thread In which situations synchronization of threads will be necessary?

NOTES

Long Questions 1. Briefly explain the different ways of creating threads with examples 2. Explain the Life cycle of Threads 3. Explain the Synchronization concept Programming Exercises 1. Create a multithreaded program by extending Thread classes. Create two simultaneously executing thread , one thread to display hello and another thread to display world 2. Create a multithreaded program by implementing the runnable interface. Create two simultaneously executing thread , one thread to generate odd numbers and another thread to generate even numbers 3. Modify program 2 by assigning priorities to threads.

289

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Answers to Have you Understood Questions Section 16.3 1. Thread is a sequential flow of control. In Java every program consists of at least one thread - the one that runs the main method of the class. 2. main 3. Since one processor is responsible for executing all the threads, the java interpreter performs switching of control between the running threads. This concept is known as context switching in a thread. Section 16.4 1. Java supports two different ways of creating threads. They are o Extending the Thread class o Implementing the Runnable interface 2. public void run() { //body of the run method. } 3. By calling the start method of the thread class Section 16.5 1. When a new thread is created it passes through various states before it gets terminated and this process is called the Life Cycle of the Thread. 2. New thread (Born state), Running state, Not running state ,Dead state 3. By calling notify() (or) notifyall() method. Section 16.6 1. The sleep method throws InterruptedException. 2. Yield method causes the currently running thread to yield its hold on CPU cycles. Section 16.7 1. 0,5,10 2. The current priority of the running thread can be accessed via method getPriority Section 16.8 1. Synchronization of threads is used to provide an exclusive access to a thread currently accessing the shared resource

Anna University Chennai

290

DCS 115

OBJECT ORIENTED PROGRAMMING

2. A monitor is an object that can block and revive threads. A monitor is simply a lock that serializes access to an object or a class. References 1. Java 2 Certification Guide Author: Jamie Jaworski Publisher: New Riders 2000 http:\\www.sun.com Thinking in Java Author: Bruce Eckel Publisher : Prentice Hall 2000 Programming with Java Author: E Balagurusamy Publisher: Tata Mcgraw Hill 2000 Java 2: The Complete Reference Author : Patrick Naughton & Herbert Schildt Publisher : Tata Mcgraw Hill 2000 Java in a Nutshell Author:David Flanagan Publisher :OReilly 1999

NOTES

2. 3.

4.

5.

6.

291

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES NOTES

Anna University Chennai

292

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES NOTES

293

Anna University Chennai

DCS 115

OBJECT ORIENTED PROGRAMMING

NOTES

Anna University Chennai

294

Das könnte Ihnen auch gefallen