c++ and javajnujprdistance.com/assets/lms/lms jnu/b.sc.(it)/sem... · ii/jnu ole contents chapter...

130
C++ and Java

Upload: others

Post on 21-May-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

Page 2: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

This book is a part of the course by Jaipur National University, Jaipur.This book contains the course content for C++ and Java.

JNU, JaipurFirst Edition 2013

The content in the book is copyright of JNU. All rights reserved.No part of the content may in any form or by any electronic, mechanical, photocopying, recording, or any other means be reproduced, stored in a retrieval system or be broadcast or transmitted without the prior permission of the publisher.

JNU makes reasonable endeavours to ensure content is current and accurate. JNU reserves the right to alter the content whenever the need arises, and to vary it at any time without prior notice.

Page 3: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

I/JNU OLE

Index

ContentI. ...................................................................... II

List of FiguresII. ........................................................... V

List of TablesIII. ...........................................................VI

AbbreviationsIV. ....................................................... VII

ApplicationV. ............................................................. 109

BibliographyVI. ......................................................... 116

Self Assessment AnswersVII. ................................... 119

Book at a Glance

Page 4: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

II/JNU OLE

Contents

Chapter I ....................................................................................................................................................... 1Object Oriented Programming ................................................................................................................... 1Aim ................................................................................................................................................................ 1Objectives ...................................................................................................................................................... 1Learning outcome .......................................................................................................................................... 11.1 Introduction to OOP ................................................................................................................................. 21.2 Basic Concepts of Object-Oriented Programming .................................................................................. 21.3 Paradigms of Programming Languages ................................................................................................... 5 1.3.1 Imperative Paradigm ................................................................................................................ 6 1.3.2 Declarative Paradigm ............................................................................................................... 71.4 Characteristics of Object-Oriented Programming .................................................................................. 71.5 Advantages of Object Oriented Programming ......................................................................................... 8Summary ..................................................................................................................................................... 10References ................................................................................................................................................... 10Recommended Reading ............................................................................................................................. 10Self Assessment ............................................................................................................................................11

Chapter II ................................................................................................................................................... 13Classes and Objects.................................................................................................................................... 13Aim .............................................................................................................................................................. 13Objectives .................................................................................................................................................... 13Learning outcome ........................................................................................................................................ 132.1 Introduction to Classes ........................................................................................................................... 142.2 Specifying a Class .................................................................................................................................. 152.3 Creating Objects ..................................................................................................................................... 162.4 Defining Member Functions .................................................................................................................. 162.5 Static Data Members .............................................................................................................................. 172.6 Static Member Functions ....................................................................................................................... 182.7 Pointer to Members ................................................................................................................................ 192.8 Constructor ............................................................................................................................................. 19 2.8.1 Copy Constructor ................................................................................................................... 202.9 Destructors ............................................................................................................................................. 21Summary ..................................................................................................................................................... 23References ................................................................................................................................................... 23Recommended Reading ............................................................................................................................. 23Self Assessment ........................................................................................................................................... 24

Chapter III .................................................................................................................................................. 26Inheritance and Polymorphism ................................................................................................................ 26Aim .............................................................................................................................................................. 26Objectives .................................................................................................................................................... 26Learning outcome ........................................................................................................................................ 263.1 Introduction to Inheritance ..................................................................................................................... 273.2 Single Inheritance .................................................................................................................................. 273.3 Multiple Inheritance ............................................................................................................................... 313.4 Polymorphism ........................................................................................................................................ 34Summary ..................................................................................................................................................... 36References ................................................................................................................................................... 36Recommended Reading ............................................................................................................................. 36Self Assessment ........................................................................................................................................... 37

Page 5: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

III/JNU OLE

Chapter IV .................................................................................................................................................. 39Templates and Exception Handling ......................................................................................................... 39Aim .............................................................................................................................................................. 39Objectives .................................................................................................................................................... 39Learning outcome ........................................................................................................................................ 394.1 Introduction to Templates ...................................................................................................................... 404.2 Function Templates ................................................................................................................................ 40 4.2.1 A Simple Function Template .................................................................................................. 404.3 Class Templates ...................................................................................................................................... 414.4 Exceptions .............................................................................................................................................. 44 4.4.1 Exception Syntax ................................................................................................................... 44 4.4.2 Throwing an Exception .......................................................................................................... 47 4.4.3 Handling Exceptions .............................................................................................................. 48Summary ..................................................................................................................................................... 49References ................................................................................................................................................... 49Recommended Reading ............................................................................................................................. 49Self Assessment ........................................................................................................................................... 50

Chapter V .................................................................................................................................................... 52Introduction to JAVA ................................................................................................................................. 52Aim .............................................................................................................................................................. 52Objectives .................................................................................................................................................... 52Learning outcome ........................................................................................................................................ 525.1 Concept of Java ...................................................................................................................................... 535.2 Origin of Java ......................................................................................................................................... 535.3 A Virtual Machine .................................................................................................................................. 545.4 Java in Comparison to Other Languages ............................................................................................... 555.5 Object Oriented Programming Concepts in Java ................................................................................... 575.6 Types concept in JAVA ........................................................................................................................... 59Summary .................................................................................................................................................... 61References ................................................................................................................................................... 61Recommended Reading ............................................................................................................................. 61Self Assessment ........................................................................................................................................... 62

Chapter VI .................................................................................................................................................. 64Classes, Objects and Methods ................................................................................................................... 64Aim .............................................................................................................................................................. 64Objectives .................................................................................................................................................... 64Learning outcome ........................................................................................................................................ 646.1 Introduction ............................................................................................................................................ 656.2 Defining a Class ..................................................................................................................................... 656.3 Fields Declaration .................................................................................................................................. 656.4 Methods Declaration .............................................................................................................................. 666.5 Creating Objects ..................................................................................................................................... 68Summary ..................................................................................................................................................... 73References ................................................................................................................................................... 73Recommended Reading ............................................................................................................................. 73Self Assessment ........................................................................................................................................... 74

Page 6: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

IV/JNU OLE

Chapter VII ................................................................................................................................................ 76Inheritance and Polymorphism in JAVA ................................................................................................. 76Aim .............................................................................................................................................................. 76Objectives .................................................................................................................................................... 76Learning outcome ........................................................................................................................................ 767.1 Inheritance in JAVA ............................................................................................................................... 777.2 Protected Access .................................................................................................................................... 777.3 Overriding Methods ............................................................................................................................... 78 7.3.1 Dynamic Method Dispatching ............................................................................................... 79 7.3.2 The Super Keyword ............................................................................................................... 79 7.3.3 Final Methods and Final Classes ........................................................................................... 807.4 Interfaces ................................................................................................................................................ 80 7.4.1 The Implements Declaration .................................................................................................. 807.5 Polymorphism ........................................................................................................................................ 817.6 Method Calling Binding ........................................................................................................................ 817.7 Producing the Right Behaviour .............................................................................................................. 827.8 Extensibility ........................................................................................................................................... 847.9 Overriding vs Overloading .................................................................................................................... 877.10 Abstract Classes and Methods ............................................................................................................. 887.11 Constructors and Polymorphism .......................................................................................................... 91 7.11.1 Order of Constructor Calls ................................................................................................... 91Summary .................................................................................................................................................... 93References .................................................................................................................................................. 93Recommended Reading ............................................................................................................................. 93Self Assessment ........................................................................................................................................... 94

Chapter VIII ............................................................................................................................................... 96Exception Handling in Java ...................................................................................................................... 96Aim .............................................................................................................................................................. 96Objectives .................................................................................................................................................... 96Learning outcome ........................................................................................................................................ 968.1 Introduction to Exception Handling ....................................................................................................... 978.2 The Classification of Exceptions ........................................................................................................... 978.3 Advertising the Exceptions that a Method Throws ................................................................................ 988.4 How to Throw an Exception .................................................................................................................. 998.5 Creating Exception Classes .................................................................................................................. 1008.6 Catching Exceptions ............................................................................................................................ 1018.7 Catching Multiple Exceptions .............................................................................................................. 1038.8 Rethrowing Exceptions ........................................................................................................................ 103Summary ................................................................................................................................................... 106References ................................................................................................................................................. 106Recommended Reading ........................................................................................................................... 106Self Assessment ......................................................................................................................................... 107

Page 7: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

V/JNU OLE

List of Figures

Fig. 1.1 Property inheritance .......................................................................................................................... 4Fig. 1.2 Polymorphism ................................................................................................................................... 4Fig. 1.3 Message passing ............................................................................................................................... 5Fig. 1.4 Language paradigm .......................................................................................................................... 6Fig. 1.5 An object ........................................................................................................................................... 7Fig. 2.1 Representation of a class ................................................................................................................ 14Fig. 3.1 Adding more members to a class (by public derivation) ................................................................ 29Fig. 3.2 Adding more members to a class (by private derivation) ............................................................... 30Fig. 3.3 Multiple Inheritance ....................................................................................................................... 31Fig. 3.4 Polymorphism ................................................................................................................................. 35Fig. 5.1 The Java runtime environment ....................................................................................................... 54Fig. 5.2 Programming languages compared ................................................................................................ 56Fig. 5.3 Inheritance ...................................................................................................................................... 58Fig. 6.1 Creating object references .............................................................................................................. 68Fig. 6.2 Assigning one object reference variable to another ........................................................................ 69Fig. 7.1 Accessibility in an inheritance relationship .................................................................................... 78Fig. 7.2 Inheritance diagram ........................................................................................................................ 82Fig. 7.3 Addition of methods and classes to the instrument ........................................................................ 85Fig. 7.4 Instrument class into abstract class ................................................................................................. 89Fig. 8.1 Exception hierarchy in Java ............................................................................................................ 97

Page 8: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

VI/JNU OLE

List of Tables

Table 1.1 Procedural and object oriented paradigms ..................................................................................... 6Table 1.2 Functional and logical paradigms .................................................................................................. 7Table 7.1 Access to class A’s members ........................................................................................................ 78

Page 9: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

VII/JNU OLE

Abbreviations

ADT - Abstract Data Types GUI - Graphical User Interface HTML - Hyper Text Markup Language ITV - Interactive TVOOP - Object Oriented ProgrammingPDAs - Personal Digital Assistants SEI - Software Engineering Institute

Page 10: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1
Page 11: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

1/JNU OLE

Chapter I

Object Oriented Programming

Aim

The aim of this chapter is to:

explain the basic concepts of object-oriented programming •

discuss different language paradigms•

describe data abstraction and encapsulation •

Objectives

The objectives of this chapter are to:

elucidate inheritance•

determine the characteristics of object-oriented programming•

explain object orientation•

Learning outcome

At the end of this chapter, you will be able to:

analyse dynamic binding•

enlist the advantages of object-oriented programming•

compreh• end the characteristics of OOP

Page 12: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

2/JNU OLE

1.1 Introduction to OOPObject Oriented Programming, also known as OOP, is a computer science term which is used to describe a computer application composed of multiple objects which are connected to each other.

Traditionally, most computer programming languages were simply a group of functions or instructions. With OOP, every object can handle data, get messages, and transfer messages to other objects. The objects will all act as independent units in their own right, and they will be responsible for carrying out a certain process. Because the objectsarenotdependentoneachother,OOPisseenasbeingmoreflexiblethanoldermethodsofprogramming.It has become quite popular, and it is now used in a number of advanced software engineering projects.

Many programmers feel that object oriented programming is easier for beginners to learn than previous programming methods.Becauseitiseasiertolearn,itcanalsobeanalysedandmaintainedwithoutalargeamountofdifficulty.However, there are some people who feel that OOP is more complicated than older programming methods.

1.2 Basic Concepts of Object-Oriented ProgrammingThe basic concepts used extensively in object-oriented programming are as follows:

Objects•Classes•Data abstraction and encapsulation•Inheritance•Polymorphism•Dynamic binding•Message passing•

ObjectsAn object can be considered a “thing” that can perform a set of related activities. The set of activities that the •objectperformsdefinestheobject’sbehaviour.Forexample,thehandcangripsomethingoraStudent(object)can give the name or address.In pure OOP terms, an object is an instance of a class.•Objectisdefinedasanidentifiableentitywithsomecharacteristicandbehaviour.Forinstance,wecansay•‘Orange’ is an object. Its characteristics are: it is spherical shaped; its colour is orange, etc. Its behaviour is: it is juicy and it tastes sweet-sour. While programming using OOP approach, the characteristics of an object are represented by its data and its behaviour is represented by its functions associated. Therefore, in OOP, programming object represents an entity that can store data and has its interface through •functions. Programming problem is analysed in terms of objects and the nature of communication between them, so it is necessary for us to understand the nature of communication between objects.

ClassesThe objects contain data, and code to manipulate that data. •Theentiresetofdataandcodeofanobjectcanbemadeauser-defineddatatypewiththehelpofaclass.In•other words, objects are variables of the type class. Onceaclasshasbeendefined,anynumberofobjectsbelongingtothatclasscanbecreated.Eachobjectis•associated with the data of type class with which they are created. Thus, a class is a collection of objects of similar type. For example, mango, apple and orange are members of •the class fruit. Classesareuser-defineddatatypesandbehavelikethebuilt-intypesofaprogramminglanguage.•The syntax used to create an object is no different than the syntax used to create an integer object on C.•

Page 13: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

3/JNU OLE

Iffruithasbeendefinedasaclass,thenthestatementfruitmango;• will create an object mango belonging to the class fruit.

Data abstraction and encapsulationThe wrapping up of data and functions into a single unit (called class) is known as encapsulation. Data •encapsulation is the most striking feature of a class. The data is not accessible to the outside world, and only these functions which are wrapped in the class can access it. The encapsulation is the inclusion within a program object of all the resources needed for the object to function •- basically, the methods and the data.In OOP, the encapsulation is mainly achieved by creating classes; the classes expose public methods and •properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties •to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do.Abstraction refers to the act of representing essential features without including the background details or •explanations. Classesusetheconceptofabstractionandaredefinedasalistofabstractattributessuchassize,weightandcost,•and functions to operate on these attributes. They encapsulate all the essential properties of the objects that are to be created. The attributes are sometimes called data members because they hold information. The functions that operate on these data are sometimes called methods or member functions. Since the classes use the concept of data abstraction, they are known as abstract data types (ADT).•

InheritanceInheritance is the process by which objects of one class obtain the properties of objects of another class. It •supportstheconceptofhierarchicalclassification.Forexample,thebird‘robin’isapartoftheclass‘flyingbird’ which is again a part of the ‘class bird’. The principle behind this sort of division is that each derived class sharescommoncharacteristicswiththeclassfromwhichitisderivedasshowninthefigurebelow.In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features •of an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have the combined features of both the classes. The real appeal and power of the inheritance •mechanism is that it allows the programmer to reuse a class that is almost, but not exactly, what has been planned. Eachsub-classdefinesonlythosefeaturesthatareuniquetoit.Withouttheuseofclassification,eachclass•would have to explicitly include all of its features.

Page 14: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

4/JNU OLE

Bird

Flying Bird

Robin Swollen Penguin Kiwi

NonflyingBird

Attributes------------------------

Attributes--------

----------

Attributes --------- ----------

Attributes --------- ----------

Attributes --------- ----------

Attributes------------------------

AttributesFeathersLay eggs

Fig. 1.1 Property inheritance

PolymorphismPolymorphism is another important OOP concept. Polymorphism, a Greek term, refers to the ability to take •more than one form. An operation may exhibit different behaviours in different instances. Behaviour depends upon the types of data used in the operation. For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the •operands are strings, then the operation would produce a third string by concatenation. The process of making an operator to exhibit different behaviours in different instances is known as operator overloading.Thefiguregivenbelowillustratesthatasinglefunctionnamecanbeusedtohandledifferentnumberanddifferent•types or arguments. This is something similar to a particular world having different meanings depending on the context. Using a single function name to perform different types of tasks is known as function overloading.Polymorphism plays an important role in allowing objects having different internal structures to share the •same external interface. This means that a general class of operations may be accessed in the same manner eventhoughspecificactionsassociatedwitheachoperationmaydiffer.Polymorphismisextensivelyusedinimplementing inheritance.

Shape

Circle-object Box-object Triangle object

Draw (circle) Draw (box) Draw (triangle)

Draw( )

Fig. 1.2 Polymorphism

Page 15: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

5/JNU OLE

Dynamic bindingBinding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic •binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with a polymorphic reference depending on the dynamic type of that reference.•Considertheprocedure“draw”inthefigureabove.Byinheritance,everyobjectwillhavethisprocedure.Its•algorithmis,however,uniquetoeachobjectandsothedrawprocedurewillberedefinedineachclassthatdefinestheobject.At run-time, the code matching the object under current reference will be called.•

Message passingAn object-oriented program consists of a set of objects that communicate with each other. The process of •programming in an object-oriented language, therefore, involves the following basic steps:

Creatingclassesthatdefineobjectsandtheirbehaviour �Creatingobjectsfromclassdefinitions �Establishing communication among objects �

Objects communicate with one another by sending and receiving information much the same way as people •pass messages to one another. The concept of message passing makes it easier to talk about building systems that directly model or simulate their real-world counterparts. A message for an object is a request for execution of a procedure, and therefore, will invoke a function (procedure) •in the receiving object, the name of the function (message) and the information to be sent. An example is shown asthefiguregivenbelow:

Employee Salary (Name)

Object

Message

Information

Fig. 1.3 Message passing

Objects have a life cycle. They can be created and destroyed. Communication with an object is feasible as long as it is alive.

1.3 Paradigms of Programming LanguagesThe term paradigm describes a set of techniques, methods, theories and standards that together represent a way of thinking for problem solving. According to Wegner, paradigms are “patterns of thought for problem solving”.

Languageparadigmswereassociatedwithclassesoflanguages.First,theparadigmsaredefined.Thereafter,•programminglanguagesaccordingtothedifferentparadigmsareclassified.Thelanguageparadigmsaredividedinto two parts: imperative and declarative paradigms, asshowninfigurebelow.Imperativelanguagescanbefurtherclassifiedintoproceduralandobject-orientedapproach.Declarativelanguagescanbeclassifiedintofunctionallanguagesandlogicallanguages.Inthefigurebelow,theexamplesoflanguagesineachcategoryare also given.

Page 16: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

6/JNU OLE

Language Paradigm

Imperative Paradigm

Procedural

C, Pascal C++ Simula, Java Lisp Prolog

Object Oriented Functional Logical

Declarative Paradigm

Fig. 1.4 Language paradigm

1.3.1 Imperative ParadigmThe meaning of imperative is “expressing a command or order”. So, the programming languages in this category specify the step-by-step explanation of command.

Imperative programming languages describe the details of how the results are to be obtained in terms of the •underlying machine model.The programs specify step-by-step the entire set of transitions that the program goes through. •Theprogramstarts froman initial state, goes through the transitions and reaches afinal state.Within this•paradigm, we have the procedural approach and object-oriented approach.

Procedural paradigm Object-oriented paradigm

Procedural languages are statement oriented •with the variables holding values. The execution of a program is modelled as a •series of states of variable locations. Non-executable statements allocate memory, •bind symbolic names to absolute memory locations and initialise memory.

The object-oriented paradigm is centred on the •concept of the object. Everything is focused on objects. Can we think •what an object is? Programconsistsoftwothings:first,asetof•objects and second, the way they interact with each other.

The popular programming languages in this •category are Ada, FORTRAN, Basic, Algol, Pascal, COBOL, Modula, C, etc.

Computation in this paradigm is viewed as the •simulation of real world entities. The popular programming languages in this •paradigm are C++, Smalltalk and Java.

Table 1.1 Procedural and object oriented paradigms

Page 17: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

7/JNU OLE

1.3.2 Declarative ParadigmIn this paradigm, programs declare or specify what is to be computed without specifying how it is to be achieved. Declarative programming is also known as value-oriented programming.

Declarative languages describe the relationship between variables in terms of functions and inference rules. The languageexecutorappliesafixedmethodtotheserelationstoproduceadesiredresult.Itismainlyusedinsolvingartificialintelligenceandconstraint-satisfactionproblems.Declarativeparadigmisfurtherdividedintotwocategories:functional and logical paradigms.

Functional paradigm Logical paradigm

A programme consists of a collection of •functions. A function just calculates and returns a value. A program consists of calling a function with •appropriate arguments, but any function can make use of other functions also.

In this paradigm programs only explain what is •to be computed not how to compute it. Here program is represented by a set of •relationships, between objects or property of objects known as predicate which are held to be true, and a set of logic/clauses (i.e., if A is true, then B is true).

The main programming languages in this •category are Lisp, ML Scheme, and Haskell.

Normally, logical paradigm, integrates data •and control structures. The Prolog language is perhaps the most common example. Mercury language is a more modern attempt at creating a logic programming language.

Table 1.2 Functional and logical paradigms

1.4 Characteristics of Object-Oriented Programming The fundamental concept of object-oriented programming is that it allows combination of data and functions, methods and procedures which are working on that data, which did not exist in earlier procedure-based programming paradigms. This fundamental unit is called object.

Anobjecthasawell-definedinterface,whichistheonlywaytoaccesstheobject’sdata.Thus,thedataiswell-organised and hidden. Such hidden data is known as encapsulated. The basic terms used in OOPs include data encapsulation and data hiding.

Data

Procedures / Functions / Methods

Fig. 1.5 An object

Page 18: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

8/JNU OLE

An object-oriented programming system is composed of multiple objects. When one object needs information •fromanotherobject,arequestissentaskingforspecificinformation.Forexample,areportobjectmayneedto know what is today’s date and will send a request to the date object. These requests are called messages and each object has an interface that manages messages.A primary rule of object-oriented programming paradigm is “as the user of an object, we never need to peek •inside it.”Allcommunicationsamongtheobjectsisdoneviamessages.Messagesdefinetheinterfacetotheobject.The•object to which a message is sent is called the receiver of the message. Everything an object can do is represented by its message interface. So, we need not know anything about what is in the object in order to use it.If we look inside the objects, it may tempt us and we would like to tamper with the details of how the object •works. Suppose, we have changed the object and later the person who programmed and designed the object inthefirstplacedecidedtochangesomeofthesedetails,thenwemaybeintrouble.Oursoftwaremaynotbeworking correctly. But as long as we just deal with objects via their messages, the software is guaranteed to work. Thus, it is important that access to an object is provided only through its messages, while keeping the details hidden.But why should we be concerned about the changes in the object design? Because software engineering •experiences tell that software do change. A popular saying is that “software is not written, it is re-written.” Some of the costliest mistakes in computer history are because of software that failed when someone tried to change it.

The basic characteristics of object-oriented programming are as follows:The basic programming entity is the object. An object can be considered to be a variable that stores data and •can perform operation on the stored data itself.An object oriented program is a collection of objects for solving a problem. These objects send messages to •each other. A message can be equated to a request to call a function of the receiver object.Each object has its own memory or data that may be made up of other objects. Thus, object-oriented programs •are suitable for complex problem solving as they hide the complexity behind the simplicity of objects.Eachobjectcanberelatedtoatype,whichisitsclass.Animportantconsiderationofaclassisthatitspecifies•the message interface, i.e., the messages that can be sent to that type/class of the objects.All object of a particular class can receive the same messages, but may behave differently. This leads to an •important conclusion. For example, a circle object having centre at x=0 and y=0 and a radius of 1 cm is of the class circle. However, it is also of the type shape. Thus, this object is bound to accept the messages that can be sent to class shape. Similarly, a rectangle object is of type rectangle and also of type shape and will follow messages sent to class shape. Both these objects may be handled using the type shape, but may respond to a message differently on receiving the same message. This is one of the most powerful concepts of object-oriented programming language, which involves inheritance and polymorphism.

1.5 Advantages of Object Oriented ProgrammingThe popularity of object-oriented programming (OOP) was because of its methodology, which allowed breaking complex and large software programs into simpler, smaller and manageable components. The costs of building large monolithic software were enormous. Moreover, the fundamental things in object-oriented programming are objects which model real world objects. Following are the basic advantages of object-oriented systems:

Modular design:• The softwares built around OOP are modular, because they are built on objects. The objects are entity in themselves, whose internal working is hidden from other objects and is decoupled from the rest of the program.Simple approach:• The objects, model real world entities, which results in simple program structure.Modifiable:• Because of its inherent properties of data abstraction and encapsulation, the internal working of objectsishiddenfromotherobjects.Thus,anymodificationmadetothemshouldnotaffecttherestofthesystem.

Page 19: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

9/JNU OLE

Extensible:• The extension to the existing program for its adaptation to new environment can be done by simply adding few new objects or by adding new features in old classes/types.Flexible:• Softwarebuiltonobject-orientedprogrammingcanbeflexible inadapting todifferent situationsbecause interaction between objects does not affect the internal working of objects.Reusable:• Objects once made, can be reused in more than one program.Maintainable:• Objectsareseparateentities,whichcanbemaintainedseparatelyallowingfixingofbugsorany other change easily.

Page 20: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

10/JNU OLE

SummaryObject Oriented Programming, also known as OOP, is a computer science term which is used to describe a •computer application composed of multiple objects which are connected to each other. An object can be considered a “thing” that can perform a set of related activities. The set of activities that the •objectperformsdefinestheobject’sbehaviour.Theentiresetofdataandcodeofanobjectcanbemadeauser-defineddatatypewiththehelpofaclass.In•other words, objects are variables of the type class. The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Data •encapsulation is the most striking feature of a class. Abstraction refers to the act of representing essential features without including the background details or •explanations. Inheritance is the process by which objects of one class obtain• the properties of objects of another class. It supports the conceptofhierarchicalclassification.Polymorphism is an important OOP concept. Polymorphism, a Greek term, means the ability to take more than •one form.The term paradigm describes a set of techniques, methods, theories and standards that together represent a way •of thinking for problem solving.

ReferencesNirosh, 2011, Introduction • to Object-Oriented Programming Concepts and More [Online] Available at <http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx#Abstract> [Accessed 3 November 2011].Stroustrup, B., 2002. • A Tour of C++ [Online] Available at <http://www.informit.com/articles/article.aspx?p=25003&seqNum=3> [Accessed 3 November 2011].Balagurusamy, E., 2006. • Object Oriented Programming with C++, 3rd ed., Tata McGraw-Hill Publishing.Parsons, D., 2002. • Object Oriented Programming with C++, 2nd ed., Cengage Learning EMEA.VTC, 2011. • C++ Fundamentals: 06. Classes Objects [Video Online] Available at: <http://www.youtube.com/watch?v=UH3tRiX8bdo> [Accessed 3 November 2011].FreeComputerTutor, 2010. • Object oriented programming [Video Online] Available at: <http://www.youtube.com/watch?v=hX1Q9wQ5QMk> [Accessed 3 November 2011].

Recommended ReadingLafore, R.• , 2002. Object Oriented Programming in C++, 4th ed., Pearson Education India, Dorling Kindersley (India) Pvt. Ltd.Farrell, J., 2008. • Object Oriented Programming using C++, 4th ed., Course Technology, USA, Cengage Learning.Johnsonbaugh, R. & Kalin, M., 1999. • Object-Oriented Programming in C++, 2nd ed., Prentice Hall.

Page 21: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

11/JNU OLE

Self Assessment_________isdefinedasanidentifiableentitywithsomecharacteristicandbehaviour.1.

Objecta. Classb. Datac. Named.

Whatreferstouser-defineddatatypesandbehavelikethebuilt-intypesofaprogramminglanguage?2. Dataa. Keywordsb. Classesc. Objectd.

_______________ is the most striking feature of a class.3. Data encapsulationa. Inheritanceb. Polymorphismc. Message passingd.

Which of the following statements is false?4. Inheritancesupportstheconceptofhierarchicalclassification.a. In C++, the concept of inheritance provides the idea of reusability.b. Inheritance is the process by which objects of one class obtain the properties of objects of another class.c. Eachsub-classdefinesonlythosefeaturesthatareuniquetoitd.

Which of the following statements is true?5. Polymorphism, an Arabic term, means the ability to take more than one form.a. Inheritance, a Latin term, means the ability to take more than one form.b. Polymorphism, a Greek term, means the ability to take more than one formc. .Polymorphism, a German term, means the ability to take more than one form.d.

Polymorphism is extensively used in ____________ inheritance.6. implementinga. calculatingb. forcingc. carryingd.

The wrapping up of data and functions into a single unit (called class) is known as 7. ____________ polymorphisma. objectb. encapsulationc. inheritanced.

Page 22: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

12/JNU OLE

Which of the following is not an advantage of OOP?8. Modular designa. Flexibilityb. Extensiblec. Linearityd.

An object-oriented programming system is composed of _____________9. multiple objectsa. single objectb. multiple classesc. multiple eventsd.

Polymorphism is extensively used in implementing ______________10. encapsulationa. inheritanceb. objectsc. classesd.

Page 23: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

13/JNU OLE

Chapter II

Classes and Objects

Aim

The aim of this chapter is to:

introduce the concept of classes•

explain the method of specifying a class•

differentiate between class and structure•

Objectives

The objectives of this chapter are to:

discuss static data members•

defineconstructor•

explain the process of accessing class members•

Learning outcome

At the end of this chapter, you will be able to:

comprehend concept of destructors•

describe the pointer to members and static member functions•

define• member functions

Page 24: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

14/JNU OLE

2.1 Introduction to ClassesThe basic building blocks of object oriented programming are classes and objects.

ClassesThe characteristic features of a class are given below.

Aclassisauserdefineddatatypewithdataelementsandoperations.•Classes are the data members that describe the state of the object.•Classesaretheoperationsthatdefinethebehavioroftheobject.•Typically,aclassisusedtointroduceanewuserdefineddatatypeanddefineabstractionsthatdonotmap•naturallyintopredefinedorderiveddatatypes.

Class nameAttributes

Operations

Fig. 2.1 Representation of a class

Attributes denote static and dynamic properties.

An operation denotesanattributesservicethataclassofferstoitsclients(objects).Forexample,azooanimalclass, an employee class etc.

C structures is one of the unique features of the C language is structures. It provides a method for packing together data of different type. A structure is a convenient tool for handling a group of logically related data items. It is a user-defineddatatypewithatemplatethatservestodefineitsdataproperties.Oncethestructureisdefined,wecancreate variables of that type using declarations that are similar to the built-in type declaration.

For example: Struct student{ char name[20]; int roll_number; floattotal_marks;};

Thekeywordstructdeclaresstudentasanewdatatypethatcanholdthreefieldsofdifferentdatatypes.Thesefieldsareknownasstructuremembersorelements.Theidentifierstudentreferredtoasstructurenameorstructuretag,can be used to create variables of type student.

Page 25: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

15/JNU OLE

Differences between class and structureIn C++, structures can have member functions but the default scope of the members of the structure is public. •The default scope of the class is private.Structures don’t have access restrictions as public, private and protected as in the class.•Like class, structures can not be inherited.•Structures can not have constructors and destructors.•

2.2 Specifying a ClassA class is a way to bind the data and its associated functions together. It allows the data (and functions) tobehidden,ifnecessary,fromexternaluse.Whiledefiningaclass,wearecreatinganewabstractdatatypethatcanbetreatedlikeanyotherbuilt-indatatype.Aclassspecificationhastwoparts:

Class declaration•Classfunctiondefinitions•

class class_name{ private: variable declarations; functions declarations; public: variable declarations;functions declarations;};

Thekeyword class specifieswhat follows is an abstract dataof type class_name.The classbodycontains thedeclaration of variables and functions. These functions and variables are collectively called class members. They are grouped under two sections namely, private and public.

The class members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also. The variables declared inside the class are known as data members and the functions are known as member functions. Only the member functions can have access to the private data members and private functions. However, the public members (both functions and data) can be accessed from outside the class.

For example:class item{ int number; // variables declaration floatcost; //privatebydefaultpublic: voidgetdata(inta,floatb); //functionsdeclaration voidputdata(void); //usingprototype}://endswithsemicolon

Weusuallygiveaclasssomemeaningfulname,suchasitem,thisnamenowbecomesanewtypeidentifierthatcanbe used to declare instances of that class type. The class item contains two data members and two functions. The class item contains two data members and two functions members. The data members are private by default while both the functions are public by declaration. The function getdata() can be used to assign values to the member variables number and cost, and putdata() can be used for displaying their values.

Page 26: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

16/JNU OLE

2.3 Creating ObjectsOnce a class has been declared, we can create variables of that type by using the class name, for example: itemx; //memoryforxiscreated

creates a variable x of type item. In C++, the class variables are known as objects. Therefore, x is called an object of type item. We may also declare more than one object in one statement.

For example: itemx,y,z;

Objectscanalsobecreatedwhenaclassisdefinedbyplacingtheirnamesimmediatelyaftertheclosingbrace,aswe do in the case of structures.Class item{ ……….. ……….. ………..}x,y,z;

Accessing class membersThe private data of a class can be accessed only through the member functions of that class. The main() cannot contain statements that access number and cost directly. The following is the format for calling a member function:

Object-name.function-name(actual-agruments);

For example, the function call statementx.getdata(100, 75.5)

is valid and assigns the value 100 to number and 75.5 to cost of the object x by implementing getdata() function. The assignments occur in the actual function.

2.4DefiningMemberFunctionsMemberfunctionscanbedefinedintwoplaces:

Outsidetheclassdefinition•Insidetheclassdefinition•

OutsidetheclassdefinitionMemberfunctionsthataredeclaredinsideaclasshavetobedefinedseparatelyoutsidetheclass.Theirdefinitionsare very much like the normal functions. They should have a function header and a function body.

An important difference between a member function and a normal function is that a member function incorporates a membership ‘identify label’ in the header. This ‘label’ tells the compiler which class the function belongs to. The generalformofamemberfunctiondefinitionis:

return-typeclass-name::function-name(argumentdeclaration)

{ functionbody

}

Page 27: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

17/JNU OLE

The membership label class-name:: tells the compiler that the function function-name belongs to the class class-name. That is, the scope of the function is restricted to the class-namespecifiedintheheaderline.Thesymbol::iscalled the scope resolution operator.

Since these functions do not return any value, their return-type is void.

The member functions have some special characteristics that are often used in the program development. These characteristics are:

Several different classes can use the same function name; the ‘membership label’ will resolve their scope.•Member functions can access the private data of the class. A non-member function cannot do so.•A member function can call another member function directly, without using dot operator.•

InsidetheclassdefinitionAnothermethodofdefiningamemberfunctionistoreplacethefunctiondeclarationbytheactualfunctiondefinitioninsidetheclass.Forexample,wecoulddefinetheitemclassasfollows:class item{ int number;floatcost;public:voidgetdata(inta,floatb);//declarations//inlinefunctionvoidpurdata(void) { cout << number << “\n”; cout << cost << “\n”; }};

Whena function isdefined insideaclass, it is treatedasan inline function.Therefore, all the restrictionsandlimitationsthatapplytoaninlinefunctionarealsoapplicablehere.Normally,onlysmallfunctionsaredefinedinsidetheclassdefinition.

2.5 Static Data MembersAstaticmemberofaclasscanbequalifiedasstatic.Thepropertiesofastaticmembervariablearesimilartothatof a C static variable. A static member variable has certain special characteristics. These are:

Itisinitialisedtozerowhenthefirstobjectofitsclassiscreated.Nootherinitialisationispermitted.•Only one copy of that member is created for the entire class and is shared by all the objects of that class, no •matter how many objects are created.It is visible only within the class, but its lifetime is the entire program.•

Static variables are normally used to maintain values common to the entire class. For example, a static data member can be used as a counter that records the occurrences of all the objects. The program below illustrates the use of a static data member.#include >instream>using namespace std;class item{ static int count; int number;public;

Page 28: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

18/JNU OLE

void getdata (int a) { number = a; count ++; } void getcount (void) { cout << “count: “; cout << count <<”\n”;};int item :: count;int main (){itema,b,c; //countisintialisedtozeroa.getcount (); // display countb.getcount ();c.getdata ();

a.getdata (100); // getting data into object ab.getdata (200); // getting data into object bc.getdata (300); // getting data into object ccout << “ After reading data” << ”\n”;a.getcount (); // display countb.getcount ();c.getdata ();return o;}

The output of the program would be:count:0count:0count:0Afterreadingdatacount:3count:3count:3

Notethatthetypeandscopeofeachstaticmembervariablemustbedefinedoutsidetheclassdefinition.Thisisnecessary because the static data members are stored separately rather than a part of an object, they are also known as class variables.

2.6 Static Member FunctionsLike static member variable, we can also have static member functions. A member function that is declared static has the following properties:

A static function can have access to only other static members (functions or variables) declared in the same •class.A static member function can be called using the class name (instead of its objects as follows:•

Class-name::function-name;

Const member functionsIf a member function does not alter any data in the class, then we may declare it as a const member function as follows:

Page 29: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

19/JNU OLE

voidmul(int,int)const;doubleget_balance()const;

Thequalifierconstisappendedtothefunctionprototypes(inbothdeclarationanddefinition).Thecompilerwillgenerate an error message if such functions try to alter the data values.

2.7 Pointer to MembersIt is possible to take the address of a member of a class and assign it to a pointer. The address of a member can be obtained by applying the operator and to a “fully operator” class member name. A class member pointer can be declared using the operator:: * with the class name. For example, given the class:class a{private: int m;public:voidshow();};

Wecandefineapointertothemembermasfollows:int A::* ip = &A ::m;

The ip pointer created thus, acts like a class member in that it must be invoked with a class object. In the statement above, the phrase A::* means “pointer-to-member of A class”. The phrase & A::m means the “address of the member of A class”.

Remember, the following statement is not valid:int*ip = &m; // won’t work

This is because m is not simply an int type data.

The dereferencing operator->* is used to access a member when we use pointers to both the object and the member. The dereferencing operator * is used when the object itself is used with the member pointer. Note that *ip is used like a member name.

2.8 ConstructorA constructor is a special member function whose task is to initialise the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class. A constructor is declared and definedasfollows://classwithaconstructorclass integer{ int m, n;public: interger(void); //constructordeclared ……….. ………..};interger::integer(void) //constructordeclared{ m=0; n=0;}

Page 30: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

20/JNU OLE

Whenaclasscontainsaconstructorliketheonedefinedabove,itisguaranteedthatanobjectcreatedbytheclasswill be initialised automatically. For example, the declaration:integer int1; // object int1 created

notonlycreatestheobjectint1oftypeintegerbutalsoinitialisesitsdatamembersmandntozero.

A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A::A (). Ifnosuchconstructorisdefined,thenthecompilersuppliesadefaultconstructor.Therefore,astatementsuchasA a;

invokes the default constructor of the compiler to create the object a.

The constructor functions have some special characteristics. These are:They should be declared in the public section.•They are invoked automatically when the objects are created.•They do not have return types, not even void and therefore, and they cannot return values.•They cannot be inherited, though a derived class can call the base class constructor.•Like other C++ functions, they can have default arguments.•Constructors cannot be virtual.•We cannot refer to their addresses.•

2.8.1 Copy ConstructorCopy constructor initialises an object by copying the state from another object of the same class. Whenever an object is copied, another object (the copy) is created, this constructor is called copy constructor.

If the class of the object being copied is A, the copy constructor’s signature is usually A::A (const A&).Default copy constructor provided by the compiler does member wise copy.•Usually overridden when an object has data members that are pointers.•

For example:# include <iostream>usingnamespacestd;class code{ int id;public: code(){} //constructor code(inta){id=a;}//constructoragain code(code&x) { id=x.id;//copyinthevalue } voiddisplay(void) { cout << id; }};int main{}{ codeA(100); //objectAiscreatedandinitialised codeB(A); //copyconstructorcalled

Page 31: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

21/JNU OLE

codeC=A; //copyconstructorcalledagain code D; // D is created, not initialised D=A; //copyconstructornotcalled cout<<“\nidofA:“;A.display(); cout<<“\nidofB:“;B.display(); cout<<“\nidofC:“;C.display(); cout<<“\nidofD:“;D.display(); return 0;}

The ouput of the program is:idofA:100idofB:100idofC:100idofD:100

Whennocopyconstructorisdefined,thecompilersuppliesitsowncopyconstructor.

2.9 DestructorsA destructor, as the name implies, is used to destroy the objects that have been created by a constructor. Like a constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde.Forexample,thedestructorfortheclassintegercanbedefinedasshownbelow:-integer(){}

A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program (or block or function as the case may be) to clean up storage that is no longer accessible. It is good a practice to declare destructors in a program since it releases memory space for future use.

Whenever new is used to allocate memory in the constructors, we should use delete to free that memory. For example, thematrixclassmaybedefinedasfollows.matrix::∼matrix(){ for(inti=0;i<d1;i++) deletep[1] deletep;}

The example below illustrates that the destructor has been invoked implicitly by the compiler.#include <iostream>usingnamespacestd;int count = 0;classalpha{public: alpha() { count++; cout<<“\nNo.Ofobjectcreated”<<count; } ∼alpha() { cout<<“\nNo.Ofobjectdestroyed”<<count; }

Page 32: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

22/JNU OLE

};intmain(){ cout <<”\n\nENTER MAIN\n”; alphaA1,A2,A3,A4; { cout << “\n\nENTER BLOCK\n”; alphsA5; } { cout << “\n\nENTER BLOCK2\n”; alphaA6; } cout << “\n\nRE-ENTER MAIN\n”; return 0;}

Output of the program:ENTER MAIN

No.ofobjectcreated1No.ofobjectcreated2No.ofobjectcreated3No.ofobjectcreated4

ENTER BLOCK1

No.ofobjectcreated5No.ofobjectdestroyed5

ENTER BLOCK 2

No.ofobjectcreated5No.ofobjectdestroyed5

RE-ENTER MAIN

No.ofobjectdestroyed4No.ofobjectdestroyed3No.ofobjectdestroyed2No.ofobjectdestroyed1

Page 33: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

23/JNU OLE

SummaryThe basic building blocks of object oriented programming are classes and objects.•Attributes denote static and dynamic properties. An operation denotes an attributes service that a class offers •to its clients (objects). Astructureisaconvenienttoolforhandlingagroupoflogicallyrelateddataitems.Itisauser-defineddatatype•withatemplatethatservestodefineitsdataproperties.Thekeywordclassspecifieswhatfollowsisanabstractdataoftypeclass_name.Theclassbodycontainsthe•declaration of variables and functions. These functions and variables are collectively called class members. They are grouped under two sections namely, private and public. The class members that have been declared as private can be accessed only from within the class. On the other •hand, public members can be accessed from outside the class also.Once a class has been declared, we can create variables of that type by using the class name•Objectscanalsobecreatedwhenaclassisdefinedbyplacingtheirnamesimmediatelyaftertheclosingbrace,•as we do in the case of structures.The private data of a class can be accessed only through the member functions of that class. •Memberfunctionscanbedefinedintwoplaces:outsidetheclassdefinition,andinsidetheclassdefinition•An important difference between a member function and a normal function is that a member function incorporates •a membership ‘identify label’ in the headerAnothermethodofdefiningamemberfunctionistoreplacethefunctiondeclarationbytheactualfunction•definitioninsidetheclassAstaticmembervariablehascertainspecialcharacteristics.Theseare:itisinitialisedtozerowhenthefirst•object of its class is created. No other initialisation is permitted. Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created, and it is visible only within the class, but its lifetime is the entire program.Thetypeandscopeofeachstaticmembervariablemustbedefinedoutsidetheclassdefinition.•If a member function does not alter any data in the class, then we may declare it as a const member function •A constructor is a ‘special’ member function whose task is to initialise the objects of its class. It is special because •its name is the same as the class name. Copy constructor initialises an object by copying the state from another object of the same class.•A destructor is used to destroy the objects that have been created by a constructor. •

ReferencesBalagurusamy, E., 2006. • Object Oriented Programming with C++, 3rd ed., Tata McGraw Hill.Jana, D., 2005. C• ++ and Object-Oriented Programming Paradigm, 2nd ed., PHI Learning Pvt. Ltd.C++• Tutorial 11: Classes and Objects in C++ [Video Online] Available at: <http://www.youtube.com/watch?v=5cZAmJyMyjA> [Accessed 14 November 2011].C++ Programming• [13] - Classes (part 1), 2010 [Video Online] Available at: <http://www.youtube.com/watch?v=3x0lPQROfxg> [Accessed 14 November 2011].Exforsys Inc., 2007. • C++ Objects and Classes [Online] Available at: <http://www.exforsys.com/tutorials/c-plus-plus/c-plus-plus-objects-and-classes.html> [Accessed 14 November 2011].Intap.net, • What is an object? [Online] Available at: <http://www.intap.net/~drw/cpp/cpp06_01.htm> [Accessed 14 November 2011].

Recommended ReadingLafore, R., 2001. • Object-Oriented Programming in C++, 4th ed., Sams.Koffman, E.B., 2005. • Objects, Abstraction, Data Structures and Design: Using C++, Wiley.Johnsonbaugh, R. & Kalin, M., 1999. • Object-Oriented Programming in C++, 2nd ed., Prentice Hall.

Page 34: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

24/JNU OLE

Self AssessmentAn important difference between a member function and a normal function is that a member function incorporates 1. a membership ___________.

‘identify label’ in the headera. ‘identify label’ in the bodyb. ‘object label’ in the headerc. ‘structure label’ in the headerd.

Which of the following statements is false?2. A class is a way to bind the data and its associated functions together.a. The class body contains the declaration of variables and functions.b. The class members that have been declared as public can be accessed only from within the class. c. Once a class has been declared, we can create variables of that type by using the class name.d.

Thetypeandscopeofeach__________membervariablemustbedefinedoutsidetheclassdefinition.3. static a. constb. defaultc. privated.

If a member function does not alter any data in the class, then we may declare it as a _____.4. const data function a. static member function b. const member function c. const member d.

The function of constructor is to ______.5. initialise the members of its classa. initialise the objects of its functionsb. declare the objects of its classc. initialise the objects of its classd.

The ________data of a class can be accessed only through the member functions of that class.6. publica. privateb. staticc. dynamicd.

__________auser-defineddatatypewithatemplatethatservestodefineitsdataproperties.7. Structurea. Classb. Methodc. Objectd.

Page 35: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

25/JNU OLE

Which of the following statements is true?8. A destructor takes any argument and returns any value. a. It is bad a practice to declare destructors in a program since it releases memory space for future use.b. Copy constructor initialises an object by copying the state from another object of the same class.c. The constructor is invoked whenever an object of its associated class is destroyed.d.

Like a constructor, the destructor is a member function whose name is the same as the class name but is preceded 9. by a ______.

membera. functionb. objectc. tilded.

A constructor that accepts no parameters is called the ___________ constructor.10. copya. defaultb. memberc. functiond.

Page 36: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

26/JNU OLE

Chapter III

Inheritance and Polymorphism

Aim

The aim of this chapter is to:

elucidate inheritance•

definederivedclasses•

enlist the features of inheritance•

Objectives

The objectives of this chapter are to:

discuss polymorphism•

explain the concept of single inheritance•

describetheprocessofdefiningthederivedclass•

Learning outcome

At the end of this chapter, you will be able to:

comprehend multiple inheritance•

describe single inheritance with public as well as privation derivation•

defineinh• eritance

Page 37: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

27/JNU OLE

3.1 Introduction to InheritanceInheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the features of the base class and the programmer can choose to add new featuresspecifictothenewlycreatedderivedclass.Forexample,aprogrammercancreateabaseclassnamedfruitanddefinederivedclassesasmango,orange,banana,etc.Eachofthesederivedclasses,(mango,orange,banana,etc.)hasallthefeaturesofthebaseclass(fruit)withadditionalattributesorfeaturesspecifictothesenewlycreatedderivedclasses.Mango,bananaandorange,eachofthesewouldhaveitsowndefinedfeatures.

The features of inheritance are as follows:Reusability: • Inheritancehelpsthecodetobereusedinmanysituations.Thebaseclassisdefinedandonceitiscompiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classesfromthebaseclassasneededwhileaddingspecificfeaturestoeachderivedclassasneeded.Saves time and effort:• The above concept of reusability achieved by inheritance saves the programmer time and effort. Since the main code written can be reused in various situations as needed; increases program structure which results in greater reliability.

DefiningderivedclassesAderivedclasscanbedefinedbyspecifyingitsrelationshipwiththebaseclassinadditiontoitsowndetails.Thegeneralformofdefiningaderivedclassis:

Class derived-class-name : visibility-mode base-class-name{ ………// ………// members of derived class ………//};

The colon indicates that the derived-class-name is derived from the base-class-name. The visibility mode is optional and,ifpresent,maybeeitherprivateorpublic.Thedefaultvisibility-modeisprivate.Visibilitymodespecifieswhether the features of the base class are privately derived or publicly derived.

For example:classABC:privateXYZ//privatederivation{membersofABC};

In inheritance, some of the base class data elements and member functions are ‘inherited’ into the derived class. We can add our own data and member functions and thus extend the functionality of the base class. Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very powerful tool for incremental program development.

3.2 Single InheritanceLet us consider a simple example to illustrate inheritance. Program below shows a base class B and a derived class D. The class B contains one private data member, one public data member, and three public member functions. The class D contains one private data member and two public member functions.

Single inheritance: public# include <iostream>usingnamespacestd;class B{

Page 38: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

28/JNU OLE

int a; // private; not inheritable public; int b; // public; ready for inheritance void get_ab(); int get_a(void); void show_a(void);};

class D: public B // public derivation{ int c; public; void mul(void); void display(void);};//----------------------------------------------------------------------------------------------void B :: get_ab(void){ a=5; b=10;}int B :: get_a(){ return a;}voidB::show_a(){ cout << “a=” << a<< “\n”;}voidD::mul(){c=b*get_a();}voidD::display(){cout<<“a=“<<get_a()<<“\n”; cout << “b = “ << b << “\n”; cout << “c = “ << c << “\n”;}//-------------------------------------------------------------------------------------------------intmain(){ D d; d.get_ab();d.mul();d.show_a();d.display();

d.b = 20;d.mul();d.display();

Page 39: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

29/JNU OLE

return 0;}

Output of the program is:a=5a=5b=10c=50

a=5b = 20c = 100

The class D is a public derivation of the base class B. Therefore, D inherits all the public members of B and retains their visibility. Thus, a public member of the base class B is also a public member of the derived class D. The private members of B cannot be inherited by D. The class D, in effect, will have more members than what it contains at the timeofdeclarationasshowninthefiguregivenbelow.

Class D

Private Section

Public SectionInheritedfrom B

C

b

Bget_ab()

get_a()

show_a()

mul()

display()

Fig. 3.1 Adding more members to a class (by public derivation)

The program illustrates that the objects of class D have access to all the public members of B. Let us have a look at functions show_a() and mul():voidshow_a(){ cout <<”a=” << a<< “\n”;}voidmul(){

Page 40: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

30/JNU OLE

c=b*get_a();//c=b*a}

Although the data member is private in B and cannot be inherited, object of D are able to access it through an inherited member function of B.

Let us now consider the case of private derivation.class B{ int a;public: int b;voidget_ab();voidget_a();voidshow_a();};

classD:privateB//privatederivation{ int c;public:voidmul();voiddisplay();};

ThemembershipofthederivedclassDisshowninthefiguregivenbelow.Inprivatederivation,thepublicmembersof the base class become private members of the derived class. Therefore, the objects of D cannot have direct access to the public member functions of B.

Class D

Private Section

Public Section

Inheritedfrom B

C

b

Bget_ab()

get_a()

show_a()

mul()

display()

Fig. 3.2 Adding more members to a class (by private derivation)

Page 41: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

31/JNU OLE

The statements such asd.get_ab();//get_abisprivated.get_a();//soalsoget_a()d.show_a();//andshow_a()

will not work. However, these functions can be used inside mul() and display() like the normal functions as shown below:voidmul(){get_ab();c=b*get_a();}

voiddisplay(){show_a()//outputsvalueof‘a’ cout << “ b=” <<b<< “\n” << “c = “ <<c<<”\n\n”;}

3.3 Multiple InheritanceAclasscan inherit theattributesof twoormoreclassesasshownin thefiguregivenbelow.This isknownasmultiple inheritance. Multiple inheritance allow us to combine the features of several existing classes as a starting pointfordefiningnewclasses.Itislikeachildinheritingthephysicalfeaturesofoneparentandtheintelligenceof another.

B-1 B-2

D

B-n

Fig. 3.3 Multiple Inheritance

The syntax of a derived class with multiple base classes is as follows:

class D: visibility B-1, visibility B-2………..{ ………………. ………………. (body of D) ……………….};

Page 42: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

32/JNU OLE

where, visibility may be either public or private. The base classes are separated by commas.For example:classP:publicM,publicN{public: voiddisplay(void);};

ClassesMandNhavebeenspecifiedasfollows:

class M{protected: int m;public: voidget_m(int);};voidM::get_m(intx){ m = x;}class N{protected:

int n;public: voidget_n(int);};voidN::get_n(inty){ n=y;}

As declared above, the derived class P would, in effect, contain all the members of M and N in addition to its own members as shown below:class P{protected //fromM //fromN

public: //fromM //fromN //ownmember};

Thememberfunctiondisplay()canbedefinedasfollows:voidP::display(void){ cout << “m=”<<m<<”\n”;

Page 43: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

33/JNU OLE

cout << “n=”<<n<<”\n”; cout << “m*n=”<<m*n<<”\n”;};

The main() function which provides the user-interface may be written as follows:main(){ Pp; p.get_m(10); p.get_n(20); p.display();}

Program below shows the entire code illustrating how all the three classes are implemented in multiple inheritance mode.

# include <iostream>Usingnamespacestd;class M{protected: int m;public: voidget_m(int);};

class N{protected: int n;public: voidget_n(int);};

classP:publicM,publicN{public: voiddisplay(void);};

voidM::get_m(intx){ m = x;}

voidN::get_n(inty){ n=y};

voidP::display(void){ cout << “m= ” << m<< “\n”;

Page 44: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

34/JNU OLE

cout << “n= ” << n<< “\n”; cout << “m*n = ” << m*n<< “\n”;}

intmain(){ Pp; p.get_m(10); p.get_m(20); p.display();

return 0;}

Output of program is:m = 10n = 20m*n = 200

3.4 PolymorphismPolymorphism is one of the crucial features of object oriented programming. It simply means ‘one name, multiple forms’. The concept of polymorphism is implemented using the overloaded functions and operators. The overloaded member functions are ‘selected’ for invoking by matching arguments, both type and number. This information is known to compiler at the compile time and, therefore, compiler is able to select the appropriate function for a particular call at the compile time itself. This is called early binding or static binding or static linking. Also known as compile time polymorphism, early binding simply means that an object is bound to its function call at compile time.

Now let us consider a situation where the function name and prototype is the name in both the base and derived classes,forexample,considerthefollowingclassdefinitions:class A{ int x;public: voidshow(){…….} //show()inbaseclass};classB:publicA{ inty;public: voidshoe(){……} //show()inderivedclass};

How do we use the member function show() to print the values of objects of both the classes A and B? Since the prototype of show() is the same in both the places, the function is not overloaded and therefore, static binding does not apply. In such situations, we may use the class resolution operator to specify the class while invoking the functions with the derived class objects.

If the appropriate member function is selected while the program is running is known as run time polymorphism. Ithappenswiththemechanismknownasvirtualfunctionasshowninthefiguregivenbelow.

Page 45: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

35/JNU OLE

Polymorphism

Compile timepolymorphism

Run timepolymorphism

Functionoverloading

OperatorOverloading

Virtualfunctions

Fig. 3.4 Polymorphism

At run time, when it is known which class objects are under consideration, the appropriate version of the function is invoked. Since the function is linked with a particular class much later after the compilation, this process is termed as late binding. It is also known as dynamic binding because the selection of the appropriate function is done dynamically at run time.

Page 46: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

36/JNU OLE

SummaryInheritance is the process by which new classes called derived classes are created from existing classes called •base classes. The derived classes have all the features of the base class and the programmer can choose to add new features •specifictothenewlycreatedderivedclass.Features of inheritance: reusability, saves time and effort, and increases program structure which results in •greater reliability.Aderivedclasscanbedefinedbyspecifyingitsrelationshipwiththebaseclassinadditiontoitsowndetails.•Visibilitymodespecifieswhetherthefeaturesofthebaseclassareprivatelyderivedorpubliclyderived.•In inheritance, some of the base class data elements and member functions are ‘inherited’ into the derived •class. A class can inherit the attributes of two or more classes this is known as multiple inheritance. Multiple inheritance •allowsustocombinethefeaturesofseveralexistingclassesasastartingpointfordefiningnewclasses.Polymorphism is one of the crucial features of object oriented programming. It simply means ‘one name, multiple •forms’. The concept of polymorphism is implemented using the overloaded functions and operators. If the appropriate member function is selected while the program is running is known as run time •polymorphism.

ReferencesBalaguruswamy, E., 2006. • Object Oriented Programming with C++, 3rd ed., Tata McGraw Hill.Keogh, J., 2004. • Object Oriented Programming: Principles and Fundamentals, Dreamtech Press.Pitts, R. I., 2000• . Introduction to Polymorphism in C++ [Online] Available at: <http://www.cs.bu.edu/teaching/cpp/polymorphism/intro/>[Accessed 3 November 2011].Tenoul.com, • C++ Object Oriented: Readme First [Online] Available at: <http://www.tenouk.com/cplusplustutorial.html> [Accessed 3 November 2011].Xoax.net, 2009. • C++ Console Lesson 38: Simple Inheritance [Video Online] Available at: <http://www.youtube.com/watch?v=UIrDafFNr2U> [Accessed 3 November 2011].Xoax.net, 2009. • C++ Console Lesson 42: Virtual Member Functions Video Online] Available at: < http://www.youtube.com/watch?v=xxR9FBs8g4Q > [Accessed 3 November 2011].

Recommended ReadingJosuttis, N. M., 2002. • Object-Oriented Programming in C++, 1st ed., Wiley.Kak, A., 2003. • Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java, 1st ed., Wiley-IEEE Press.Farrell, J., 2008• . Object-Oriented Programming Using C++, 4th ed., Cengage Learning.

Page 47: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

37/JNU OLE

Self AssessmentThe concept of polymorphism is implemented using the _______functions and operators.1.

overriddena. overloadedb. object orientedc. inheritedd.

Multipleinheritanceallowsustocombinethefeaturesofseveralexistingclassesasastartingpointfordefining2. new___________.

objectsa. functionsb. classesc. methodsd.

Which of the following statements is false?3. Inheritance means ‘one name, multiple forms’. a. Aderivedclasscanbedefinedbyspecifying its relationshipwith thebaseclass inaddition to itsownb. details. Visibilitymodespecifieswhetherthefeaturesofthebaseclassareprivatelyderivedorpubliclyderived.c. In inheritance, some of the base class data elements and member functions are ‘inherited’ into the derived d. class.

Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very powerful 4. tool for ____________program development.

incrementala. existingb. object orientedc. implementingd.

If the appropriate ________function is selected while the program is running is known as run time 5. polymorphism.

classa. objectb. memberc. derivedd.

A________class can be defined by specifying its relationshipwith the base class in addition to its own6. details.

basea. derivedb. memberc. functiond.

Page 48: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

38/JNU OLE

____________is the process by which new classes called derived classes are created from existing classes 7. called base classes

Inheritancea. Exceptionb. Polymorphismc. Bindingd.

Which of the following statements is true?8. We can delete our own data and member functions and thus extend the functionality of the base class. a. Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very dynamic b. tool for incremental program development.Inheritance decreases program structure which results in greater reliabilityc. The derived classes have all the features of the base class and the programmer can choose to add new features d. specifictothenewlycreatedderivedclass.

Early binding simply means that an object is bound to its function call at ________.9. compile timea. run timeb. error timec. development timed.

__________modespecifieswhetherthefeaturesofthebaseclassareprivatelyderivedorpubliclyderived.10. Dynamica. Staticb. Visibilityc. Developmentd.

Page 49: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

39/JNU OLE

Chapter IV

Templates and Exception Handling

Aim

The aim of this chapter is to:

introduce the concept of templates•

analyse the sequence of events when the exception occurs•

discuss the simple function template•

Objectives

The objectives of this chapter are to:

describe class templates•

explain the concept of exceptions•

discuss the process of throwing an exception•

Learning outcome

At the end of this chapter, you will be able to:

discuss function templates•

justify the need of exceptions•

comprehend cla• ss template

Page 50: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

40/JNU OLE

4.1 Introduction to TemplatesAtemplateenablesustodefinegenericclassesandfunctionsandthusprovidessupportforgenericprogramming.A template can be used to create a family of classes or functions. For example, a class template for an array class wouldenableustocreatearraysofvariousdatatypessuchasintarrayandfloatarray.

A templatecanbeconsideredasakindofmacro.Sincea template isdefinedwithaparameter thatwouldbereplacedbyaspecifieddatatypeatthetimeofactualuseoftheclassorfunction,thetemplatesaresometimescalledparameterised classes or functions. The template concept can be used in two different ways:

Functions•Classes•

4.2 Function TemplatesSuppose we want to write a function that returns the absolute value of two numbers. As we remember from high school algebra, the absolute value of a number is its value without regard to its sign. The absolute value of 3 is 3, and the absolute value of –3 is also 3. Ordinarily, this function would be written for a particular data type:intabs(intn)//absolutevalueofints { return(n<0)?-n:n;//ifnisnegative,return-n }

Here,thefunctionisdefinedtotakeanargumentoftypeintandtoreturnavalueofthissametype.Butnowsupposewewanttofindtheabsolutevalueofatypelong.Wewillneedtowriteacompletelynewfunction:longabs(longn)//absolutevalueoflongs { return(n<0)?-n:n; }Andagain,fortypefloat:

floatabs(floatn)//absolutevalueoffloats { return(n<0)?-n:n; }

The body of the function is written the same way in each case, but they are completely different functions because they handle arguments and return values of different types. It is true that in C++, these functions can all be overloaded tohavethesamename,butnevertheless,wemustwriteaseparatedefinitionforeachone.

Rewriting the same function body over and over for different types is time consuming and wastes space in the listing.Also,ifwefindanerrorinonesuchfunction,itneedstobecorrectedineachfunctionbody.Failingtodothis correctly, introduce inconsistencies into the program. It would be nice if there was a way to write such a function just once, and have it work for many different data types.

4.2.1 A Simple Function TemplateOurfirstexampleshowshowtowriteourabsolute-valuefunctionasatemplate,sothatitwillworkwithanybasicnumericaltype.Thisprogramdefinesatemplateversionofabs()andthen,inmain(),invokesthisfunctionwithdifferent data types to prove that it works. Here is the listing for TEMPABS:

//tempabs.cpp//templateusedforabsolutevaluefunction#include <iostream>usingnamespacestd;//--------------------------------------------------------------

Page 51: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

41/JNU OLE

template<classT>//functiontemplateTabs(Tn) { return(n<0)?-n:n; }//--------------------------------------------------------------intmain() { intint1=5; intint2=-6; long lon1 = 70000L; long lon2 = -80000L; doubledub1=9.95; doubledub2=-10.15; //callsinstantiatefunctions cout<<“\nabs(“<<int1<<”)=”<<abs(int1);//abs(int) cout<<“\nabs(“<<int2<<”)=”<<abs(int2);//abs(int) cout<<“\nabs(“<<lon1<<”)=”<<abs(lon1);//abs(long) cout<<“\nabs(“<<lon2<<”)=”<<abs(lon2);//abs(long) cout<<“\nabs(“<<dub1<<”)=”<<abs(dub1);//abs(double) cout<<“\nabs(“<<dub2<<”)=”<<abs(dub2);//abs(double) cout << endl; return 0; }Output of the program is:abs(5)=5abs(-6)=6abs(70000)=70000abs(-80000)=80000abs(9.95)=9.95abs(-10.15)=10.15

As we can see, the abs() function now works with all three of the data types (int, long, and double) that we use as arguments.Itwillworkonotherbasicnumericaltypesaswell,anditwillevenworkonuser-defineddatatypes,provided that the less-than operator (<) and the unary minus operator (-) are appropriately overloaded.

Here is how we specify the abs() function to work with multiple data types:template<classT>//functiontemplateTabs(Tn) { return(n<0)?-n:n; }

Thisentiresyntax,withafirstlinestartingwiththekeywordtemplateandthefunctiondefinitionfollowing,iscalleda function template.

4.3 Class TemplatesThe template concept can be extended to classes. Class templates are generally used for data storage (container) classes. Stacks and linked lists are examples of data storage classes.classStack {private: intst[MAX];//arrayofints

Page 52: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

42/JNU OLE

inttop;//indexnumberoftopofstackpublic: Stack();//constructor voidpush(intvar);//takesintasargument intpop();//returnsintvalue };

Ifwewantedtostoredataoftypelonginastack,wewouldneedtodefineacompletelynewclass:classLongStack {private: longst[MAX];//arrayoflongs inttop;//indexnumberoftopofstackpublic: LongStack();//constructor voidpush(longvar);//takeslongasargument longpop();//returnslongvalue };

Similarly, we would need to create a new stack class for every data type we wanted to store. It would be nice to be abletowriteasingleclassspecificationthatwouldworkforvariablesofalltypes,insteadofasinglebasictype.Aswe know, class templates allow us to do this. We will create a variation of STAKARAY that uses a class template. Here is the listing for TEMPSTAK://tempstak.cpp//implementsstackclassasatemplate#include <iostream.h>usingnamespacestd;constintMAX=100;//sizeofarray////////////////////////////////////////////////////////////////template<classType>class Stack { private: Type st[MAX]; //stack: array of any type int top; //number of top of stack public: Stack() //constructor { top = -1; } void push(Type var) //put number on stack { st[++top] = var; } Type pop() //take number off stack { return st[top--]; } };////////////////////////////////////////////////////////////////int main() {Stack<float>s1;//s1isobjectofclassStack<float>s1.push(1111.1F);//push3floats,pop3floats s1.push(2222.2F); s1.push(3333.3F); cout << “1: ” << s1.pop() << endl; cout << “2: ” << s1.pop() << endl; cout << “3: ” << s1.pop() << endl;

Page 53: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

43/JNU OLE

Stack<long> s2; //s2 is object of class Stack<long>

s2.push(123123123L); //push 3 longs, pop 3 longs s2.push(234234234L); s2.push(345345345L); cout << “1: ” << s2.pop() << endl; cout << “2: ” << s2.pop() << endl; cout << “3: ” << s2.pop() << endl; return 0; }

Here, the class Stack is presented as a template class. The approach is similar to that used in function templates. The template keyword and class Stack signal that the entire class will be a template.template<classType>classStack{//dataandmemberfunctionsusingtemplateargumentType};

Atemplateargument,namedTypeinthisexample,isthenused(insteadofafixeddatatypelikeint)everyplaceintheclassspecificationwherethereisareferencetothetypeofthearrayst.Therearethreesuchplaces:thedefinitionof st, the argument type of the push() function, and the return type of the pop() function.

Class templates differ from function templates in the way they are instantiated. To create an actual function from afunctiontemplate,wecallitusingargumentsofaspecifictype.Classes,however,areinstantiatedbydefininganobject using the template argument.Stack<float>s1;

Thiscreatesanobject,s1,astackthatstoresnumbersoftypefloat.Thecompilerprovidesspaceinmemoryforthisobject’sdata,usingtypefloatwhereverthetemplateargumentTypeappearsintheclassspecification.Italsoprovides space for the member functions (if these have not already been placed in memory by another object of typeStack<float>).Thesememberfunctionsalsooperateexclusivelyontypefloat.

Creating a Stack object that stores objects of a different type, as inStack<long>s2;

creates not only a different space for data, but also a new set of member functions that operate on type long.

Note,thatthenameofthetypeofs1consistsoftheclassnameStackplusthetemplateargument:Stack<float>.This distinguishes it from other classes that might be created from the same template, such as Stack<int> or Stack<long>.

In TEMPSTAK, we exercise the s1 and s2 stacks by pushing and popping three values on each one and displaying each popped value. Here is the output:1:3333.3//floatstack2:2222.23:1111.11:345345345//longstack2:2342342343:123123123

In this example, the template approach gives us two classes for the price of one, and we could instantiate class objects for other numerical types with just a single line of code.

Page 54: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

44/JNU OLE

4.4 ExceptionsExceptions provide a systematic, object-oriented approach to handling run-time errors generated by C++ classes. Exceptions are errors that occur at run time. They are caused by a wide variety exceptional circumstance, such as runningoutofmemory,notbeingabletoopenafile,tryingtoinitialiseanobjecttoanimpossiblevalue,orusingan out-of-bounds index to a vector.

Why do we need exceptions?Why do we need a new mechanism to handle errors? Let us look at how the process was handled in the past. In C-language programs, an error is often signalled by returning a particular value from the function in which it occurred.Forexample,disk-filefunctionsoftenreturnNULLor0tosignalanerror.Eachtimewecalloneofthesefunctions, you check the return value:

if(somefunc()==ERROR_RETURN_VALUE)//handletheerrororcallerror-handlerfunctionelse//proceednormallyif(anotherfunc()==NULL)//handletheerrororcallerror-handlerfunctionelse//proceednormallyif(thirdfunc()==0)//handletheerrororcallerror-handlerfunctionelse//proceednormally

One problem with this approach is that every single call to such a function must be examined by the program. Surrounding each function call with an if...else statement, and adding statements to handle the error (or call an error-handler routine), requires a lot of code and makes the listing convoluted and hard to read. The problem becomes more complex when classes are used, since errors may take place without a function being explicitly called. For example,supposeanapplicationdefinesobjectsofaclass:

SomeClassobj1,obj2,obj3;

Howwilltheapplicationfindoutifanerroroccurredintheclassconstructor?Theconstructoriscalledimplicitly,sothere is no return value to be checked. Things are complicated even further when an application uses class libraries. A class library and the application that makes use of it are often created by separate people: the class library by a vendor and the application by a programmer who buys the class library. This makes it even harder to arrange for error values to be communicated from a class member function to the program that is calling the function. The problem of communicating errors from deep within class libraries is probably the most important problem solved by exceptions.

4.4.1 Exception SyntaxImagine an application that creates and interacts with objects of a certain class. Ordinarily the application’s calls to the class member functions cause no problems. Sometimes, however, the application makes a mistake, causing an error to be detected in a member function. This member function then informs the application that an error has occurred. When exceptions are used, this is called throwing an exception. In the application, we install a separate section of code to handle the error. This code is called an exception handler or catch block; it catches the exceptions thrown by the member function. Any code in the application that uses objects of the class is enclosed in a try block. Errors generated in the try block will be caught in the catch block. Code that does not interact with the class need not be in a try block.

The exception mechanism uses three new C++ keywords: throw, catch and try. Also, we need to create a new kind of entity called an exception class. XSYNTAX is not a working program, but a skeleton program to show the syntax.

Page 55: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

45/JNU OLE

//xsyntax.cpp//notaworkingprogram////////////////////////////////////////////////////////////////class AClass //a class {public:classAnError//exceptionclass { };voidFunc()//amemberfunction { if(/*errorcondition*/) throwAnError();//throwexception } };////////////////////////////////////////////////////////////////intmain()//application {try//tryblock { AClassobj1;//interactwithAClassobjects obj1.Func();//maycauseerror }catch(AClass::AnError)//exceptionhandler {//(catchblock) //tell user about error, etc. }return 0;}

We start with a class called AClass, which represents any class in which errors might occur. An exception class, AnErrorisspecifiedinthepublicpartofAClass.InAClass’smemberfunctions,wecheckforerrors.Ifwefindone,we throw an exception, using the keyword throw followed by the constructor for the error class:throwAnError(); //’throw’ followed by constructor for AnError class

In the main() part of the program, we enclose any statements that interact with AClass in a try block. If any of these statements causes an error to be detected in an AClass member function, an exception will be thrown and control will go to the catch block that immediately follows the try block.

A simple exception exampleLet us look at a working program example that uses exceptions. The application program might attempt to push too many objects onto the stack, thus exceeding the capacity of the array, or it might try to pop too many objects off the stack, thus obtaining invalid data. In the XSTAK program we use an exception to handle these two errors.

//xstak.cpp//demonstratesexceptions#include <iostream>usingnamespacestd;constintMAX=3;//stackholds3integerss////////////////////////////////////////////////////////////////classStack {private:

Page 56: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

46/JNU OLE

intst[MAX]; //arrayofintegers inttop; //indexoftopofstackpublic: classRange //exceptionclassforStack { //note:emptyclassbody };

Stack() //constructor{top=-1;}

voidpush(intvar) {if(top>=MAX-1) //ifstackfull, throwRange(); //throwexceptionst[++top]=var; //putnumberonstack }intpop() {if(top<0) //ifstackempty, throwRange(); //throwexceptionreturnst[top--]; //takenumberoffstack }};////////////////////////////////////////////////////////////////intmain(){Stacks1;{trys1.push(11);s1.push(22);s1.push(33);//s1.push(44);//oops:stackfullcout<<“1:”<<s1.pop()<<endl;cout<<“2:”<<s1.pop()<<endl;cout<<“3:”<<s1.pop()<<endl;cout<<“4:”<<s1.pop()<<endl;//oops:stackempty }catch(Stack::Range)//exceptionhandler {cout<<“Exception:StackFullorEmpty”<<endl; }

cout<<“Arrivehereaftercatch(ornormalexit)”<<endl;return 0;}

Note that we have made the stack small so that it is easier to trigger an exception by pushing too many items.

Letusexaminethefeaturesofthisprogramthatdealwithexceptions.Therearefourofthem.Intheclassspecification,there is an exception class. There are also statements that throw exceptions. In the main() part of the program, there is a block of code that may cause exceptions (the try block), and a block of code that handles the exception (the catch block).

Page 57: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

47/JNU OLE

Specifying the exception classTheprogramfirstspecifiesanexceptionclasswithintheStackclass:

class Range{//note:emptyclassbody};

Here the body of the class is empty, so objects of this class have no data and no member functions. All we really need in this simple example is the class name, Range. This name is used to connect a throw statement with a catch block.

4.4.2 Throwing an ExceptionIn the Stack class, an exception occurs if the application tries to pop a value when the stack is empty or tries to push a value when the stack is full. To let the application know that it has made such a mistake when manipulating a Stack object, the member functions of the Stack class check for these conditions using if statements, and throw an exception if they occur. In XSTAK, the exception is thrown in two places, both using the statement:

throwRange();

The Range() part of this statement invokes the (implicit) constructor for the Range class, which creates an object of this class. The throw part of the statement transfers program control to the exception handler.

The try blockAll the statements in main() that might cause this exception, i.e., statements that manipulate Stack objects, are enclosed in braces and preceded by the try keyword:try{//codethatoperatesonobjectsthatmightcauseanexception}

This is simply part of the application’s normal code; it is what we would need to write even if we are not using exceptions. Not all the code in the program needs to be in a try block; just the code that interacts with the Stack class. Also, there can be many try blocks in our program, so we can access Stack objects from different places.

The exception handler (catch block)The code that handles the exception is enclosed in braces, preceded by the catch keyword, with the exception class name in parentheses. The exception class name must include the class in which it is located. Here it is Stack::Range.

catch(Stack::Range){//codethathandlestheexception}

This construction is called the exception handler. It must immediately follow the try block. In xstak the exception handler simply prints an error message to let the user know why the program failed.

Control “falls through” the bottom of the exception handler, so we can continue processing at that point. Or the exception handler may transfer control elsewhere, or (often) terminate the program.

Page 58: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

48/JNU OLE

Sequence of eventsLet us summarise the sequence of events when an exception occurs.

Code is executing normally outside a try block.•Control enters the try block.•A statement in the try block causes an error in a member function.•The member function throws an exception.•Control transfers to the exception handler (catch block) following the try block.•

Notice how clean the resulting code is. Any of the statements in the try block could cause an exception, but we don’t need to worry about checking a return value for each one, because the try-throw-catch arrangement handles them all automatically. In this particular example we have deliberately created two statements that cause exceptions. Thefirst,s1.push(44); //pushes too many items

causes an exception if you remove the comment symbol preceding it, and the second,cout<<“4:”<<s1.pop()<<endl; //pops item from empty stack

causesanexceptionifthefirststatementiscommentedout.Tryiteachway.Inbothcases,thesameerrormessagewill be displayed:StackFullorEmpty

Initialising an exception objectHow do we initialise the data when we throw an exception? In the two-argument constructor for the Stack class we say:throwInchesEx(“2-argconstructor”,in);andinthegetdist()nmemberfunctionforStackitisthrowInchesEx(“getdist()function”,inches);

When the exception is thrown, the handler will display the string and inches values. The string will tell us which member function is throwing the exception, and the value of inches will report the faulty inches value detected by thememberfunction.Thisadditionaldatawillmakeiteasierfortheprogrammerorusertofigureoutwhatcausedthe error.

4.4.3 Handling ExceptionsAfter we catch an exception, we will sometimes want to terminate our application. The exception mechanism gives us a chance to indicate the source of the error to the user, and to perform any necessary clean-up chores before terminating. It also makes clean-up easier by executing the destructors for objects created in the try block. This allows us to release system resources, such as memory, that such objects may be using.

Inothercases,wewillnotwanttoterminatetheprogram.Perhapsourprogramcanfigureoutwhatcausedtheerror and correct it, or the user can be asked to input different data. When this is the case, the try and catch blocks are typically embedded in a loop, so control can be returned to the beginning of the try block (which the exception mechanism has attempted to restore to its initial state). If there is no exception handler that matches the exception thrown, the program is unceremoniously terminated by the operating system.

Page 59: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

49/JNU OLE

SummaryAtemplateenablesustodefinegenericclassesandfunctionsandthusprovidessupportforgenericprogramming.•A template can be used to create a family of classes or functions. Sinceatemplateisdefinedwithaparameterthatwouldbereplacedbyaspecifieddatatypeatthetimeofactual•use of the class or function, the templates are sometimes called parameterised classes or functions.The template concept can be used in two different ways: functions, and classes. The body of the function is •written the same way in each case, but they are completely different functions because they handle arguments and return values of different types. It is true that in C++ these functions can all be overloaded to have the same name,butwemustneverthelesswriteaseparatedefinitionforeachone.Class templates are generally used for data storage (container) classes.•Class templates differ from function templates in the way they are instantiated. To create an actual function •fromafunctiontemplate,wecallitusingargumentsofaspecifictype.Classes,however,areinstantiatedbydefininganobjectusingthetemplateargument.Exceptions provide a systematic, object-oriented approach to handling run-time errors generated by C++ classes. •Exceptions are errors that occur at run time. The problem of communicating errors from deep within class libraries is probably the most important problem •solved by exceptions. The exception mechanism uses three new C++ keywords: throw, catch, and try. The exception mechanism •gives us a chance to indicate the source of the error to the user, and to perform any necessary clean-up chores before terminating. If there is no exception handler that matches the exception thrown, the program is unceremoniously terminated •by the operating system

ReferencesMsdn.microsoft.com, 2011. • C++ Exception Handling [Online] Available at: <http://msdn.microsoft.com/en-us/library/4t3saedz.aspx>[Accessed3November2011]Balaguruswamy, E., 2006. • Object Oriented Programming with C++, 3rd ed., Tata McGraw Hill.Venugopal, K. R., 1997. • Mastering C++, Muhammadali Shaduli.Williams, A., 2001. • Introduction to C++ Templates [pdf] Available at: <http://www.justsoftwaresolutions.co.uk/articles/intrototemplates.pdf> [Accessed 3 November 2011].Xoax.net, 2009. • C++ Console Lesson 19: Function Templates [Video Online] Available at: <http://www.youtube.com/watch?v=0e1ia9wfPnQ> [Accessed 3 November 2011].VTC, 2011. • C++ Fundamentals: 51. Exception Handling [Video Online] Available at: <http://www.youtube.com/watch?v=MMGEc3angZ8&feature=results_video&playnext=1&list=PLB08C597637C40FC4> [Accessed 3 November 2011].

Recommended ReadingSkinner, M. T., 1992• . The advanced C++ book: Volume 1. Silicon Press.Lafore, R., 1998. • Object Oriented Programming in C++, 3rd ed., Macmillan Computer Publishing.Stroustrup, B., 2000. • The C++ Programming Language: Special Edition, 3rd ed., Addison-Wesley Professional.

Page 60: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

50/JNU OLE

Self AssessmentTocreateanactualfunctionfromafunctiontemplate,wecallitusing_______ofaspecifictype.1.

argumentsa. datab. membersc. sourced.

Exceptions provide a systematic, object-oriented approach to handling ______errors generated by C++ 2. classes.

compilea. run-timeb. codingc. datad.

In ______language programs, an error is often signaled by returning a particular value from the function in 3. which it occurred.

Javaa. Cb. C++c. Cobold.

The exception mechanism gives us a chance to indicate the source of the error to the user, and to perform any 4. necessary ___________.

clean-up chores before runninga. clean-up chores before startingb. run-time chores before terminatingc. clean-up chores before terminatingd.

Class templates are generally used for data _______classes.5. clean-upa. terminatingb. storagec. errord.

Which of the following statements is false?6. The exception class name must include the object in which it is located.a. Any code in the application that uses objects of the class is enclosed in a try block.b. Exceptions are errors that occur at run time. c. Class templates differ from function templates in the way they are instantiated.d.

If there is no exception handler that matches the exception thrown, the program is unceremoniously ____________ 7. by the operating system.

compileda. instantiatedb. locatedc. terminatedd.

Page 61: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

51/JNU OLE

Which of the following is the most important problem solved by exceptions?8. Communicating errors from deep within class librariesa. To perform any necessary clean-up choresb. To worry about checking a return value c. To let the user know why the program failedd.

A__________enables us to define generic classes and functions and thus provides support for generic9. programming.

programa. functionb. objectc. templated.

A template can be considered as a kind of _________.10. programa. datafileb. macroc. classd.

Page 62: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

52/JNU OLE

Chapter V

Introduction to JAVA

Aim

The aim of this chapter is to:

introduce the concept of Java•

explain the concept of polymorphism in Java•

compare Java with other languages•

Objectives

The objectives of this chapter are to:

discuss history of Java•

explain the concept of virtual machine•

enumerate the types concept in Java•

Learning outcome

At the end of this chapter, you will be able to:

understand the concept of inheritance in Java•

describe virtual machine •

defineencap• sulation in Java

Page 63: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

53/JNU OLE

5.1 Concept of JavaThe Java programming language, developed at Sun Microsystems under the guidance of Net luminaries James Gosling and Bill Joy, is designed to be a machine-independent programming language that is both safe enough to traverse networks and powerful enough to replace native executable code. Java addresses the issues raised here and may help us start building the kinds of applications we want.

Initially, most of the enthusiasm for Java centered on its capabilities for building embedded applications for the World Wide Web; these applications are called applets. Applets could be independent programs in themselves, or sophisticated frontends to programs running on a server.

More recently, interest has shifted to other areas. With Java 2, Java has the most sophisticated toolkit for building graphical user interfaces; this development has allowed Java to become a popular platform for developing traditional application software.

Java has also become an important platform for server-side applications, using the servlet interface, and for enterprise applications using technologies such as Enterprise JavaBean. And Java is the platform of choice for modern distributed applications.

5.2 Origin of JavaThe seeds of Java were planted in 1990 by Sun Microsystems patriarch and chief researcher, Bill Joy. Since, Sun’s inception in the early 80s, it has steadily pushed one idea “the network is the computer”. At the time though, Sun was competing in a relatively small workstation market, while Microsoft was beginning its domination of the more mainstream, Intel-based PC world. When Sun missed the boat on the PC revolution, Joy retreated to Aspen, Colorado, to work on advanced research. He was committed to accomplish complex tasks with simple software, and founded the aptly named Sun Aspen Smallworks.

Of the original members of the small team of programmers assembled in Aspen, James Gosling is the one who •willberememberedasthefatherofJava.Goslingfirstmadeanameforhimselfintheearly80’sastheauthorofGoslingEmacs,thefirstversionofthepopularEmacseditorthatwaswritteninCandranunderUnix.Gosling Emacs became popular, but was soon eclipsed by a free version, GNU Emacs, written by Emacs’s original •designer.Bythattime,GoslinghadmovedontodesignSun’sNeWSwindowsystem,whichbrieflycontendedwith the X Window System for control of the UNIX graphical user interface (GUI) desktop in 1987.While some people would argue that NeWS was superior to X, NeWS lost out because Sun kept it proprietary •and didn’t publish source code, while the primary developers of X formed the X Consortium and took the opposite approach.Designing NeWS taught Gosling the power of integrating an expressive language with a networkaware windowing •GUI. It also taught Sun that the Internet programming community will refuse to accept proprietary standards, no matter how good they may be. The seeds of Java’s remarkably permissive licensing scheme were sown by NeWS’s failure. Gosling brought what he had learned to Bill Joy’s nascent Aspen project, and in 1992, work on the project led •to the founding of the Sun subsidiary, FirstPerson, Inc. Its mission was to lead Sun into the world of consumer electronics.The FirstPerson team worked on developing software for information appliances, such as cellular phones and •personal digital assistants (PDAs).The goal was to enable the transfer of information and real-time applications over cheap infrared and packet- based •networks.Memoryandbandwidthlimitationsdictatedsmallandefficientcode.Thenatureoftheapplicationsalso demanded they be safe and robust. Gosling and his teammates began programming in C++, but they soon found themselves confounded by a •language that was too complex, unwieldy, and insecure for the task. They decided to start from scratch, and Gosling began working on something he dubbed “C++ minus minus.”

Page 64: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

54/JNU OLE

With the foundering of the Apple Newton, it became apparent that the PDA’s ship had not yet come in, so Sun •shifted First Person’s efforts to interactive TV (ITV).The programming language of choice for ITV set-top boxes was the near ancestor of Java, a language called •Oak. Even with its elegance and ability to provide safe interactivity, Oak could not salvage the lost cause of ITV. Customers didn’t want it, and Sun soon abandoned the concept.At that time, Joy and Gosling got together to decide on a new strategy for their language. It was 1993, and the •explosion of interest in the Internet, and the World Wide Web in particular, presented a new opportunity. Oak was small, robust, architecture-independent, and object-oriented. As it happens, these are also the requirements for a universal, network-savvy Programming language. Sun quickly changed focus, and with a little retooling, Oak became Java.

5.3 A Virtual MachineJava is both a compiled and an interpreted language. Java source code is turned into simple binary instructions, much likeordinarymicroprocessormachinecode.However,whereasCorC++sourceisrefinedtonativeinstructionsfora particular model of processor, Java source is compiled into universal format instructions for a virtual machine.

Compiled Java byte-code, also called J-code, is executed by a Java runtime interpreter. The runtime system •performs all the normal activities of a real processor, but it does so in a safe, virtual environment. It executes the stack-based instruction set and manages a storage heap. It creates and manipulates primitive data types, and loads and invokes newly referenced blocks of code. Mostimportantly,itdoesallthisinaccordancewithastrictlydefinedopenspecificationthatcanbeimplemented•by anyone who wants to produce a Java-compliant virtual machine.Together,thevirtualmachineandlanguagedefinitionprovideacompletespecification.Therearenofeatures•ofJavaleftundefinedorimplementation-dependent.Forexample,Javaspecifiesthesizesofallitsprimitivedata types, rather than leave it up to each implementation.The Java interpreter is relatively lightweight and small; it can be implemented in whatever form is desirable •for a particular platform. On most systems, the interpreter is written in a fast, natively compiled language such as C or C++. The interpreter can be run as a separate application, or it can be embedded in another piece of software, such as a web browser.All of this means that Java code is implicitly portable. The same Java application byte-code can run on any •platformthatprovidesaJavaruntimeenvironment,asshowninthefigurebelow.Youdon’thavetoproducealternative versions of your application for different platforms, and you don’t have to distribute source code to end users.

Source Code

Java runtimeByte Code

Unix PC Macintosh

Fig. 5.1 The Java runtime environment

Page 65: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

55/JNU OLE

The fundamental unit of Java code is the class. As in other object-oriented languages, classes are application •components that hold executable code and data. Compiled Java classes are distributed in a universal binary format that contains Java byte-code and other class information.Classescanbemaintaineddiscretelyandstoredinfilesorarchivesonalocalsystemoronanetworkserver.•Classes are located and loaded dynamically at runtime, as they are needed by an application.Inadditionto theplatform-specificruntimesystem,Javahasanumberoffundamentalclasses thatcontain•architecture-dependent methods. These native methods serve as the gateway between the Java virtual machine and the real world. They are implemented in a natively compiled language on the host platform. They provide accesstoresourcessuchasthenetwork,thewindowingsystemandthehostfilesystem.The rest of Java is written entirely in Java, and is therefore portable. This includes fundamental Java utilities •such as the Java compiler and Sun’s HotJava web browser, which are also Java applications and are therefore available on all Java platforms. Historically, interpreters have been considered slow, but because the Java interpreter runs compiled byte-code, Java is a relatively fast interpreted language.More importantly, Java has also been designed so that software implementations of the runtime system can •optimisetheirperformancebycompilingbyte-codetonativemachinecodeonthefly.Thisiscalledjust-in-timecompilation.Sun claims that with just-in-time compilation, Java code can execute nearly as fast as native compiled code •and maintain its transportability and security. There is only one true performance hit that compiled Java code will always suffer for the sake of security array bounds checking. But on the other hand, some of the basic design features of Java place more information in the hands of the compiler, which allows for certain kinds of optimisations not possible in C or C++. The latest twist in compilation techniques is a new virtual machine that Sun calls HotSpot. The problem with a traditional just-in-time compilation is that optimising code takes time, and is extremely •important for good performance on modern computer hardware. So, a just-in-time compiler can produce decent results, but can never afford to take the time necessary to do a good job of optimisation. HotSpot uses a trick called “adaptive compilation” to solve this problem.If you look at what programs actually spend their time doing, it turns out that they spend almost all of their time •executing a relatively small part of the code again and again. The chunk of code that is executed repeatedly may only be a small percent of the total program, but its behaviour determines the program’s overall performance.To take advantage of this fact, HotSpot starts out as a normal Java byte code interpreter, but with a difference: •itmeasures(profiles)thecodeasitisexecuting,toseewhatpartsarebeingexecutedrepeatedly.Once it knows which parts of the code are crucial to the performance, Hotspot compiles those sections and only •those sections into true machine code. Since it only compiles a small portion of the program into machine code, it can afford to take the time necessary to optimise those portions. The rest of the program may not need to be compiled at all-just interpreted-saving memory and time.The technology for doing this is very complex, but the idea is essentially simple: optimise the parts of the program •that need to go fast, and don’t worry about the rest. Another advantage of using an adaptive compiler at runtime is that it can make novel kinds of optimisations that a static (compile time only) compiler cannot dream of.

5.4 Java in Comparison to Other LanguagesJava is a new language, but it draws on many years of programming experience with other languages in its choice of features. So, a lot can be said in comparing and contrasting Java with other languages. There are at least three pillars necessary to support a universal language for network programming today: portability, speed, and security. ThefigurebelowshowshowJavaiscomparedtootherlanguages.

Page 66: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

56/JNU OLE

C/C++

SPEE

D

SPEE

D

SPEE

D

SEC

UR

ITY

SEC

UR

ITY

SEC

UR

ITY

SEC

UR

ITY

PORT

AB

ILIT

Y

PORT

AB

ILIT

Y

PORT

AB

ILIT

Y

PORT

AB

ILIT

Y

JAVA Smalltalk

Tcl

Fig. 5.2 Programming languages compared

YoumayhaveheardthatJavaisalotlikeCorC++,butthatisreallynottrue,exceptatasuperficiallevel.•WhenyoufirstlookatJavacode,youwillseethatthebasicsyntaxlooksalotlikeCorC++.Butthatiswherethe similarities end.Java is by no means a direct descendant of C or a next-generation C++.If you compare language features, you •will see that Java actually has more in common with languages such as Smalltalk and Lisp.In fact, Java’s implementation is about as far from native C as you can imagine. The surface-level similarities •to C and C++ are worth noting, however. Java borrows heavily from C and C++ syntax, so you will see lots of familiar language constructs, including an abundance of curly braces and semicolons.Java also subscribes to the C philosophy that a good language should be compact; in other words, it should •besufficientlysmallandregularsoaprogrammercanholdallthelanguage’scapabilitiesinhisorherheadatonce.Just as C is extensible with libraries, packages of Java classes can be added to the core language components. C •has been successful because it provides a reasonably featureful programming environment, with high performance and an acceptable degree of portability.Java also tries to balance functionality, speed, and portability, but it does so in a very different way. C trade’s •functionality for portability; Java trades speed for portability. Java also addresses security issues, while C doesn’t. Java is an interpreted language, so it won’t be as fast as a •compiled language like C. But Java is fast enough, especially for interactive, network-based applications, where the application is often idle, waiting for the user to do something or waiting for data from the network.For situations where speed is critical, a Java implementation can optimise performance with just-in-time •compilation to byte-code, as previously discussed. Scripting languages such as Perl, Python, Tcl/Tk and Wksh, are becoming very popular, and for good reason.There’s no reason for which a scripting language could not be suitable for safe, networked applications (e.g., •Safe Tcl), but most scripting languages are not designed for serious, large scale programming.The attraction to scripting languages is that they are dynamic; they are powerful tools for rapid prototyping. •Some scripting languages, such as awk and Perl, also provide powerful tools for text-processing tasks that more general-purposelanguagesfindunwieldy.Scriptinglanguagesarealsohighlyportable.One problem with scripting languages, however, is that they are rather casual about program structure and data •typing. Most scripting languages (with a hesitant exception for Perl 5.0 and Python) are not object-oriented. Theyalsohavevastlysimplifiedtypesystemsandgenerallydon’tprovideforsophisticatedscopingofvariablesand functions. These characteristics make them unsuitable for building large, modular applications.

Page 67: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

57/JNU OLE

Speed is another problem with scripting languages; the high-level, fully interpreted nature of these languages •often makes them quite slow.Javaofferssomeoftheessentialadvantagesofascriptinglanguage,alongwiththeaddedbenefitsofalower-•level language.Incremental development with object-oriented components, combined with Java’s simplicity, make it possible •to develop applications rapidly and change them easily, with a short concept-to implementation time.Java also comes with a large base of core classes for common tasks such as building GUIs and doing network •communications. But along with these features, Java has the scalability and software-engineering advantages of more static languages. It provides a safe structure on which to build higher-level networked tools and languages. However, don’t confuse Java with JavaScript! JavaScript is an object-based scripting language being developed by Netscape and others. It serves as glue and an “in the document” language for dynamic, interactive HTML-based applications. JavaScript draws its name from its intended integration with Java. You can currently interact with Java applets •embedded in HTML using JavaScript. There have been a few portable implementations of JavaScript that would promote it to the level of a general scripting language. As already said, Java is similar in design to languages like Smalltalk and Lisp. However, these languages are •currently used mostly as research vehicles, rather than for developing large-scale systems.One reason is that they never developed a standard portable binding to operating system services, like the C •standard library or the Java core classes.Smalltalk is compiled to an interpreted byte-code format, and it can be dynamically compiled to native code on •thefly,justlikeJava.ButJavaimprovesonthedesignbyusingabyte-codeverifiertoensurethecorrectnessofcompiledJavacode.ThisverifiergivesJavaaperformanceadvantageoverSmalltalkbecauseJavacoderequiresfewerruntimechecks.Java’sbyte-codeverifieralsohelpswithsecurityissues,somethingthatSmalltalkdoesn’t address.Smalltalk is a mature language, though, and Java’s designers took lessons from many of its features.•

5.5 Object Oriented Programming Concepts in JavaThree of the most basic concepts for object-oriented programming are classes, objects, and methods. However, there are a few more concepts that we need to be familiar with these are:

Inheritance•Abstraction•Polymorphism•Event•Encapsulation•

We will be using the class Cats as an example throughout the chapter.

InheritanceInheritance will allow a sub-group to make a connection with the associates of its parent class. For example, let’s say the class Cats decides to create a method called purr() and a property named Colorfur. As the name implies, a propertyisaspecificattributewhichisconnectedtoanobject.

Every sub-group will be able to inherit the associates, and this means the developer only needs to create the code •for them one time. The traits that are inherited by the sub-group can be changed. For example, the Persian cat class may choose to make the Colorfur white for their default color. In contrast, another cat breed may choose adifferentColorfurtrait.Itisalsopossibleforthesub-grouptoaddnewassociates.IfaspecificcatClasssub-group wants to set a default eye color, this can be inherited as well. Some object oriented programming languages may also allow a class to inherit traits from multiple ancestors, •and this is called multiple inheritance. Some programs may not allow this. One object-oriented concept that helps objects work together is inheritance.

Page 68: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

58/JNU OLE

Inheritancedefinesrelationshipsamongclassesinanobject-orientedlanguage.IntheJavaprogramminglanguage,•all classes descend from Java.lang.Object and implement its methods. The following diagram shows the class hierarchy as it descends from Java.lang.Object for the classes in the user interface example above.The Java.lang.Object methods are also shown because they are inherited and implemented by all of its subclasses, •whichiseveryclassintheJavaAPIlibraries.Java.lang.Objectdefinesthecoresetofbehavioursthatallclasseshaveincommon.Aswemovedownthehierarchy,eachclassaddsitsownsetofclass-specificfieldsandmethodsto what it inherits from its superclass or superclasses.TheJava.awt.swing.JFrameclassinheritsfieldsandmethodsfromJava.awt.Frame,whichinheritsfields,and•methodsfromJava.awt.Container,whichinheritsfieldsandmethodsfromJava.awt.Component,whichfinallyinheritsfromJava.lang.Object,andeachsubclassaddsitsownfieldsandmethodsasneeded.

java.lang.String

java.awt.event.WindowAdapter

java.util.EventObject

java.awt.Component

java.awt.Container

java.awt.swing.JPanel

java.awt.swing.JLabel

java.awt.Window

java.awt.Frame java.awt.swing.JFrame

java.awt.AWTEvent

java.awt.WindowEvent

java.awt.ComponentEvent

java.lang.Objectclone ()equal ()finalise()getClass ()hashCode ()notify ()notifyAll ()Object ()toString ()wait ()wait (long timeout)wait (long timeout, int nanos)

Fig. 5.3 Inheritance

Page 69: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

59/JNU OLE

AbstractionAbstractioncanbedefinedastheprocessinwhichanapplicationwillignorethecharacteristicsofasub-groupandwork on a general level when it is needed. As an example, Betsy the cat may be treated as a cat when it is necessary, but it can also be processed as a Felidae, which is a superclass of cat family.

PolymorphismPolymorphismcanbedefinedasabehaviorwhichisdependentontheclasstowhichitisconnected.Asanexample,if a Cat is sent a command to speak, this may cause it to purr, while a dog will bark, or a lion may roar.

EncapsulationEncapsulation will allow a class to hide information from objects that may use the code. For example, the Cat class will have a purr () method. A code will be written which will explain how the cat purrs. Despite this, it is not necessary for Betsy the cat to know how she purrs.

Encapsulation makes it easier for the developer to change the code without having to change the code for Betsy. When the structure of class is hidden, it is harder for it to be used in the wrong way. Encapsulation will basically state which class is allowed to use the members of a certain object. This concept makes it easier for programmers to deal with or avoid errors when developing a program. The members within OOP can be categorised as being protected, public, or private.

EventAneventcansimplybedefinedasanythingthathappenstoanobject.Generally,aneventissomethingthatwillcause the object to react with a method. Another term that advanced programmers may run into is called multiple inheritance. It is a situation where a class is able to inherit traits from a number of different superclasses.

A multiple inheritance can create a number of perplexing situations. Because of this, there is debate in the programming communityaboutwhetheritisbeneficialorrisky.Oneexampleofaprogramwhichdealswithmultipleinheritancesis Java. It will permit a class to have interfaces which come from multiple parents, but it can only inherit methods from a single parent. Other programming languages which use this approach are C# and Visual Basic.

There are a number of popular object oriented programming languages that are being used, and one of the most popular is Java.

5.6 Types concept in JAVAJava,likemostprogramminglanguagesclassifiesvaluesandexpressionsintotypes.Forexample,String’sandint’saretypes.Atypebasicallyspecifiestheallowedvaluesandallowedoperationsonvaluesofthattype.

A type is a set of values together with one or more operations that can be applied uniformly to all these values. A type system basically gives meaning to collections of bits. Because any value simply consists of a set of bits in a computer, the hardware makes no distinction between memory addresses, instruction code, characters, integers and floating-pointnumbers.

Types inform programs and programmers how they should treat those bits. For example, the integers are a type with valuesintherange−2,147,483,648to+2,147,483,647andvariousallowedoperationsthatincludeaddition,subtraction, modulus, etc.

The use of types by a programming language has several advantages:

SafetyUse of types may allow a compiler to detect meaningless or invalid code. For example, we can identify an expression “Hello, World” / 3 as invalid because one cannot divide a string literal by an integer. Strong typing offers more safety.

Page 70: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

60/JNU OLE

OptimisationStatic type-checking may provide useful information to a compiler. The compiler may then be able to generate moreefficientcode.

DocumentationTypes can serve as a form of documentation, since they can illustrate the intent of the programmer. For instance, timestamps may be a subtype of integers but if a programmer declares a method as returning a timestamp rather than merely an integer, this documents part of the meaning of the method.

AbstractionTypes allow programmers to think about programs at a higher level, not bothering with low-level implementation. For example, programmers can think of strings as values instead of as a mere array of bytes.

There are fundamentally two types in JAVA: primitive types and objects types, i.e. any variable you declare are •either declared to be one of the primitive types or an object type. int, double and char are the built-in, primitive types in JAVA.Theprimitivetypescanbeusedinvariouscombinationstocreateother,compositetypes.Everytimewedefine•aclass,weareactuallydefininganewtype.Forexample,theStudentclassdefinedaboveintroducesanewtype.We can now use this type like any other type: we can declare variables to be of this type and we can use it as a •type for parameters of methods. Before a variable can be used, it must be declared.A declaration gives a variable a name, a type and an initial value for e.g. int x = 8 declares x to be of type int. •Allobjectsthatwedeclarealsohavetobeofaspecifiedtypethetypeofanobjectistheclassfromwhichitiscreated. Thus, when we declare objects we state the type like so: Student st = newStudent();. This statement declares the variable st to be of type Student. This statement creates •anewobjectofthespecifiedtypeandrunstheStudentconstructor.Theconstructor’sjobistoproperlyinitialisethe object. The String type is another example of an object type. Student and String are composite types and give us the •same advantages as the built-in types. The ability to create our own types is a very powerful idea in modern languages. When declaring variables, •we can assign initial values.If you do not specify initial values, the compiler automatically assigns one: Instance variables of numerical •type(int,double,etc.)areautomaticallyinitialisedtozero;Booleanvariablesareinitialisedtofalse;andcharvariables,totheUnicodecharacterwithcodenumberzero.Thedefaultinitialvalueofobjecttypesisnull.

Page 71: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

61/JNU OLE

Summary Java has also become an important platform for server-side applications, using the servlet interface, and for •enterprise applications using technologies like Enterprise JavaBean.The seeds of Java were planted in 1990 by Sun Microsystems patriarch and chief researcher, Bill Joy.•Java source code is turned into simple binary instructions, much like ordinary microprocessor machine code.•Compiled Java byte-code, also called J-code, is executed by a Java runtime interpreter.•Compiled Java classes are distributed in a universal binary format that contains Java byte-code and other class •information.Java is a new language, but it draws on many years of programming experience with other languages in its •choice of features.Speed is another problem with scripting languages; the high-level, fully interpreted nature of these languages •often makes them quite slow.Javaofferssomeoftheessentialadvantagesofascriptinglanguage,alongwiththeaddedbenefitsofalower-•level languageInheritance will allow a sub-group to make a connection with the associates of its parent class.•Abstractioncanbedefinedastheprocessinwhichanapplicationwillignorethecharacteristicsofasub-group•and work on a general level when it is needed.Polymorphismcanbedefinedasabehaviorwhichisdependentontheclasstowhichitisconnected.•Encapsulation will allow a class to hide information from objects that may use the code• .

ReferencesThomas, C., 2009. • An Introduction to Object-Oriented Programming with Java, McGraw-Hill Higher Education.Mulholland, A. & Murphy, G., 2003. • Java 1.4 Game Programming, Word Ware Publishing.Brown, L., • Basic Object-Oriented Programming in Java [pdf] Available at: <http://notes.corewebprogramming.com/student/Java-OOP.pdf> [Accessed 24 November 2011].Object Oriented Programming using Java• [pdf] Available at: <http://math.hws.edu/eck/cs124/downloads/OOP2_from_Univ_KwaZulu-Natal.pdf> [Accessed 24 November 2011].Elzwai,2010.• What is Java [Video Online] Available at: <http://www.youtube.com/watch?v=pxbb8vthXKQ&feature=related> [Accessed 3 November 2011].www.tihl.info, 2009. • 002 - The Java Virtual Machine [Video Online] Available at: <http://www.youtube.com/watch?v=K8I1OqXkYwc> [Accessed 3 November 2011].

Recommended ReadingHorstmann, C. S. & Cornell, G., 2001. • Core Java 2: Fundamentals, Prentice Hall PTR.Anderson, J. & Franceschi, H. 2008. • Java 6 illuminated: an Active Learning Approach, Jones & Bartlett Learning.Barnes, D. & Barnes, D. J., 2000. • Object-oriented programming with Java: an introduction. Prentice Hall.

Page 72: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

62/JNU OLE

Self AssessmentWhich of the following will allow a class to hide information from objects that may use the code?1.

Encapsulationa. Inheritanceb. Polymorphismc. Bindingd.

_______________will allow a sub-group to make a connection with the associates of its parent class.2. Encapsulationa. Inheritanceb. Polymorphismc. Bindingd.

Whichofthefollowingisdefinedasabehaviorwhichisdependentontheclasstowhichitisconnected?3. Encapsulationa. Inheritanceb. Polymorphismc. Bindingd.

Which of the following sentences is true?4. Java source code is turned into simple decimal instructions, much like ordinary microprocessor machine a. code.Java source code is turned into simple binary instructions, much like ordinary assembly language code.b. C++ source code is turned into simple binary instructions, much like ordinary microprocessor machine c. code.Java source code is turned into simple binary instructions much like ordinary microprocessor machine d. code.

__________offerssomeoftheessentialadvantagesofascriptinglanguage,alongwiththeaddedbenefitsofa5. lower-level language

Javaa. C++b. Cc. Visual Basicsd.

A _________is a set of values together with one or more operations that can be applied uniformly to all these 6. values

objecta. typeb. classc. eventd.

Which of the following is a problem with scripting languages?7. Modular designa. Errorsb. Speed c. Reusabilityd.

Page 73: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

63/JNU OLE

Compiled Java byte-code is also called__________.8. P-codea. C-codeb. A-codec. J-coded.

The fundamental unit of Java code is the ____________9. classa. objectb. eventc. bitd.

__________ type-checking may provide useful information to a compiler.10. Dynamic a. Staticb. Non-staticc. Lineard.

Page 74: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

64/JNU OLE

Chapter VI

Classes, Objects and Methods

Aim

The aim of this chapter is to:

introduce the concepts of objects, class and methods•

explainfielddeclaration•

elaborate the concept of class•

Objectives

The objectives of this chapter are to:

discuss method declaration•

explain the method of creating objects•

discuss how to create object reference•

Learning outcome

At the end of this chapter, you will be able to:

understand the applications of classes and objects•

describe the concept of constructors and its application•

anlayse th• e class members

Page 75: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

65/JNU OLE

6.1 IntroductionJava is a true object oriented language and therefore the underlying structure of all Java programs is classes. Anything wewishtorepresentinaJavaprogrammustbeencapsulatedinaclassthatdefinesthestateandbehaviourofthebasic program components known as objects. Classes create objects and objects use methods to communicate between them. Classes provide a convenient method for packing together a group of logically related data items and functionsthatworkonthem.InJava,thedataitemsarecalledarecalledfieldsandthefunctionsarecalledmethods.Callingaspecificmethodinanobjectisdescribedassendingtheobjectamessage.

Aclassisessentiallyadescriptionofhowtomakeanobjectthatcontainsfieldsandmethods.Itprovidesasortoftemplateforanobjectandbehaveslikeabasicdatatypeint.ItisthereforeimportanttounderstandhowthefieldsandmethodsaredefinedinaclassandhowtheyareusedtobuildJavaprogramthatincorporatesthebasicOOPconcepts such as encapsulation, inheritance and polymorphism.

6.2DefiningaClassAclassisauser-defineddatatypewithatemplatethatservestodefineitsproperties.Oncetheclasstypehasbeendefined,wecreate“variable”ofthattypeusingdeclarationthataresimilartothebasictypedeclaration.InJava,thesevariablesaretermedasinstancesofclasses,whicharetheactualobjects.Thebasicformofaclassdefinitionis:

Class classname [extends superclassname] { [fieldsdeclaration;] [methods declaration:] }

Everythinginsidethesquarebracketsisoptional.Thismeansthatthefollowingwouldbeavalidclassdefinition.Class Empty{}

Because the body is empty, this class does not contain any properties and therefore cannot do anything. We can, however, compile it and even create objects using it. C++ programmers may note that there is no semicolon after closing brace.

Classname and superclassname areanyvalidJavaidentifiers.Thekeywordsextendsindicatesthatthepropertiesof the superclassname class are extended to the classname class.

6.3 Fields DeclarationDataisencapsulatedinaclassbyplacingdatafieldsinsidethebodyoftheclassdefinition.Thesevariablesarecalled instance variables because they are created whenever an object of the class is instantiated. We can declare the instance variables exactly the same way as we declare local variables.

For example:

class Rectangle{int length;int width;}

Page 76: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

66/JNU OLE

The class rectangle contains two integer type instance variables. It is allowed to declare them in one line as

int length, width;

Remember these variables are only declared and therefore no storage space has been created in the memory. Instance variables are also known as member variables.

6.4 Methods DeclarationAclasswithonlydatafields(andwithoutmethodsthatoperateonthatdata)hasnolife.Theobjectscreatedbysucha class cannot respond to any messages. We must therefore add methods that are necessary for manipulating the data contained in the class. Methods are declared inside the body of the class but immediately after the declaration of instance variables. The general form of a method declaration is:

type methodname (parameter-list){Method-body}

Method declarations have four basic parts:The name of the method (methodname)•The type of the value the method returns (type)•A list of parameters (parameter-list)•The body of the method•

Thetypespecifiesthetypeofvaluethemethodwouldreturn.Thiscouldbesimpledatatypesuchasint as well as any class type. It could even be void type, if the method does not return any value. The methodname is a valid identifier.Theparameterlistisalwaysenclosedinparentheses.Thisjustcontainsvariablenamesandtypesofallthe values we want to give to the method as input. The variables in the list are separated by commas. In the case where no input data are required, the declaration must retain the empty parentheses.

For example:

(intm,floatx,floaty)//Threeparameters( ) // Empty list

The body actually describes the operations to be performed on the data. Let us consider the Rectangle class again and add a method getData ( ) to it.

class Rectangle{int length;intwidth;voidgetData(intx,inty)//Methoddeclaration{ length = x;width=y; }}

Page 77: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

67/JNU OLE

Note that the method has a return type of void because it does not return nay value. We pass two integer values to the methods which are then assigned to the instance variables length and width. The getData method is basically added to provide values to the instance variables. Notice that we are able to use directly length and width inside the method.

Letusaddsomemorepropertiestotheclass.Assumethatwewanttocomputetheareaoftherectangledefinedbythe class. This can be done as follows:

class Rectangle{ int length, width; // Combined declaration void getData (int x. int y) { length = x; width = y; } int rectArea ( ) // Declaration of another method { int area = length * width; return (area); }}

The new method rectArea( ) computes area of the rectangle and returns the result. Since the result would be an integer,thereturntypeofthemethodhasbeenspecifiedasint.Alsonotethattheparameterlistisempty.Remember that while the declaration of instance variables (and also local variables) can be combined as

int length, width;

the parameter list used in the method header should always be declared independently separated by commas. That is,

void getData (int x, y) // Incorrect

is illegal.

Now, our class Rectangle contains two instance variables and two methods. We can add more variables and methods, if necessary. Most of the times when we use classes, we have many methods and variables within the class. Instance variables and methods in classes are accessible by all the methods in the class but a method cannot access the variables declared in other methods.

Page 78: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

68/JNU OLE

For example:

class Access{int x;voidmethod1(){inty;x = 10; // legaly=x; //legal}Voidmethod2(){Intz;X=5 //legalZ=10; //legalY=1; //illegal}}

6.5 Creating ObjectsAn object in Java is essentially a block of memory that contains space to store all the instance variables. Creating an object is also referred to as instantiating an object.

ObjectsinJavaarecreatedusingthenewoperator.Thenewoperatorcreatesanobjectofthespecifiedclassandreturns a reference to that object. Here is an example of creating an object of type Rectangle.

Rectangle rect1; // declare the objectrect1=newRectangle(); // instantiate the object

Thefirststatementdeclaresavariabletoholdtheobjectreferenceandthesecondoneactuallyassignstheobjectreference to the variable. The variable rect1 is now an object of the Rectangle class.

Action Statement Result

Declare Rectangle rect1; null rect1

Instantiate rect1 = new Rectangle ( ) rect1

rect1 is a reference Rectangle to Rectangle object Object

Fig. 6.1 Creating object references

Both statements can be combined into one as shown below:

Rectangle rect1 = new Rectangle ( );

Page 79: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

69/JNU OLE

The method Rectangle ( ) is the default constructor of the class. We can create any number of objects of Rectangle. Example:

Rectanglerect1=newRectangle();Rectanglerect2=newRectangle();

and so on.

It is important to understand that each object has its own copy of the instance variables of its class. This means that any changes to the variables of one object have no effect on the variables of another. It is also possible to create two or more references to the same object.RectangleR1=newRectangle();Rectangle R2 = R1;

Both R1 and R2 refer to the same object.

R1

Rectangle Object

R1

Fig. 6.2 Assigning one object reference variable to another

Accessing class membersNow that we have created objects, each containing its own set of variables, we should assign values to these variables in order to use them in our program. Remember, all variables must be assigned values before they are used. Since we are outside the class, we cannot access the instance variables and the methods directly. To do this, we must use the concerned object and the dot operator as shown below:

Objectname.variablename = value;Objectname.methodname (parameter-list);

Here objectname is the name of the object; variablename is the name of the instance variable inside the object that we wish to access, methodname is the method that we wish to call, and parameter-list is a comma separated list of “actual values” (or expressions) that must match in type and number with the parameter list of the methodname declared in the class. The instance variables of the Rectangle class may be accessed and assigned values as follows:

rect1.length = 15;rect1.width = 10;rect2.length = 20rect2.width = 12;

Page 80: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

70/JNU OLE

Note that the two objects rect1 and rect2 store different values as shown below:

rect1.length 15 rect2.length 20rect1.width 10 rect2.width 12

This is one way of assigning values to the variables in the objects. Another way and more convenient way of assigning to the instance variables is to use a method that is inside the class.In our case, the method getData can be used to do this work. We can call the getData method on any Rectangle object to set the values of both length and width. Here is the code segment to achieve this.

Rectangle rect1 = new rectangle ( ); // Creating an objectRect1.getData (15, 10); // Calling the method using the object

This code creates rect1 object and then passes in the values 15 and 10 for the x and y parameters of the method getData. This method then assigns these values to length and width variables respectively. For the sake of convenience, the method is again shown below:

voidgetData(intx,inty){length = x;width=y;}

Now that the object rect1 contains values for its variables, we can compute the area of the rectangle represented by rect1. This again can be done in two ways.

Thefirstapproachistoaccesstheinstancevariablesusingthedotoperatorandcomputethearea.Thatis.•int area1 = rect1.length * rect1.width;The second approach is to call the method rectArea declared inside the class. That is, •int area1 = rect1.rectArea ( ); // calling the method

The program below illustrates the concepts discussed above.

Page 81: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

71/JNU OLE

Program: Application of classes and objects

class Rectangle{int length.width; // Declaration of variablesvoidgetData(intx,inty)//Definitionofmethod { length = x; width = y;}intrectArea() //Definitionofanothermethod{ int area = length*width; return (area);}}class RectArea // Class with main method{ Public static void main (String args [ ] ){ int area1.area2; Rectangle rect1 = new Rectangle ( ); // Creating objects Rectangle rect2 = new Rectangle ( ); Rect1.length = 15; // Accessing variables rect1.width = 10; area1 = rect1.length * rect1.width; rect2.getData (20, 12) // Accessing methods area2 = rect2.rectArea ( ); System.out.println (“Area1 = “+ area1); System.out.println (“Area12= “+ area2);}

Program would output the followingArea1=150Area2=240

ConstructorsWe know that all objects are created must be given initial values. We have done this earlier using two approaches. Thisfirstapproachusesthedotoperatortoaccesstheinstancevariablesandthenassignsvaluestothemindividually.It can be tedious approach to initialise all the variables of all the objects.

The second approach takes the help of a method like getData to initialise each object individually using statements like,

rect1.getData (15, 10);

It would be simpler and more concise to initialise an object when it is created. Java supports a special type of method, called a constructor that enables an object to initialise itself when it is created. Constructors have the same name as the class itself. Secondly, they do not specify a return type, not even a void. This is because they return the instance of the class itself.

Let us consider our Rectangle class again. We can now replace the getData method by a constructor method as shown below:

Page 82: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

72/JNU OLE

class Rectangle{int length;int width;Rectangle (int x , int y) // Constructor method{length = x;width = y;}int rectArea ( ){return (length*width);}}

The program below illustrates the use of constructor method to initialise an object at the time of its creation.

Program: Application of constructors

class Rectangle{intlength,width;Rectangle(intx,inty) //Definingconstructor{length = x;width=y;}intrectArea(){return(length*width);}}class RectangleArea{publicstaticvoidmain(stringargs[]){ Rectanglerect1=newRectangle(15,10); //Callingconstructor intarea1=rect1.Area(); System.out.println (“Area1 = “+ area1); }}

Output of program 2.2:Area1=150

Page 83: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

73/JNU OLE

class Rectangle{int length;int width;Rectangle (int x , int y) // Constructor method{length = x;width = y;}int rectArea ( ){return (length*width);}}

The program below illustrates the use of constructor method to initialise an object at the time of its creation.

Program: Application of constructors

class Rectangle{intlength,width;Rectangle(intx,inty) //Definingconstructor{length = x;width=y;}intrectArea(){return(length*width);}}class RectangleArea{publicstaticvoidmain(stringargs[]){ Rectanglerect1=newRectangle(15,10); //Callingconstructor intarea1=rect1.Area(); System.out.println (“Area1 = “+ area1); }}

Output of program 2.2:Area1=150

SummaryJava is a true object oriented language and therefore the underlying structure of all Java programs is classes.•InJava,thedataitemsarecalledarecalledfieldsandthefunctionsarecalledmethods•AnythingwewishtorepresentinaJavaprogrammustbeencapsulatedinaclassthatdefinesthestateand•behaviour of the basic program components known as objectsAclassisauser-defineddatatypewithatemplatethatservestodefineitsproperties.Oncetheclasstypehas•beendefined,wecreate“variable”ofthattypeusingdeclarationthataresimilartothebasictypedeclarationClassnameandsuperclassnameareanyvalidJavaidentifiers.•Dataisencapsulatedinaclassbyplacingdatafieldsinsidethebodyoftheclassdefinition.Thesevariablesare•called instance variables because they are created whenever an object of the class is instantiatedMethods are declared inside the body of the class but immediately after the declaration of instance variables•Method declarations have four basic parts: the name of the method (methodname), the type of the value the •method returns (type), a list of parameters (parameter-list), and the body of the methodAn object in Java is essentially a block of memory that contains space to store all the instance variables. Creating •an object is also referred to as instantiating an object.ObjectsinJavaarecreatedusingthenewoperator.Thenewoperatorcreatesanobjectofthespecifiedclass•and returns a reference to that objectJava supports a special type of method, called a constructor that enables an object to initialise itself when it is •created.

ReferencesArnold, 2000• . The Java Programming Language, Pearson Education India.Dale, N. B. & Weems, C., 2007. • Programming and problem solving with Java, 2nd ed., Jones & Bartlett Learning. Classes and Objects in Java• [Online] Available at: <http://docstore.mik.ua/orelly/Java/Javanut/ch03_01.htm> [Accessed 19 November 2011]Javabeginner.com, 2008, • Java Classes and Objects [Online]. Available at: <http://www.Javabeginner.com/learn-Java/Java-classes-and-objects> [Accessed 19 November 2011].ssby79, 2010. • Java Tutorial: Creating Objects [Video Online] Available at: <http://www.youtube.com/watch?v=IQmOONWhhYY> [Accessed 3 November 2011]. Thenewboston, 2009. • Java Programming Tutorial - 17 – Constructors [Video Online] Available at: <http://www.youtube.com/watch?v=tPFuVRbUTwA> [Accessed 3 November 2011].

Recommended ReadingSierra, K., 2005. • Head First Java. 2nd ed., O’Reilly Media.Barnes, D. J. & Kolling, M., 2008. • Objects First With Java: A Practical Introduction Using BlueJ, 4th ed., Prentice Hall.Bronson, G. J., 2005. • Object-Oriented Program Development Using Java: A Class-Centered Approach, 2nd ed., Course Technology.

Page 84: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

74/JNU OLE

Self AssessmentUnderlying structure of all Java programs is ________.1.

methodsa. classesb. objectsc. instancesd.

An object in Java is essentially a block of memory that contains space to store all the ______.2. instance variablesa. object variablesb. basic variablec. dot variabled.

Which of the following statements is false?3. Callingaspecificmethodinanobjectinanobjectisdescribedassendingtheobjectamessage.a. Aclassisessentiallyadescriptionofhowtomakeanobjectthatcontainsfieldsandmethodsb. Classesprovideadifficultmethodforpackingtogetheragroupoflogicallyrelateddataitemsandfunctionsc. that work on them.Classes create objects and objects use methods to communicate between them.d.

Objects in Java are created using the __________.4. new operatora. data operatorb. object operatorc. class operatord.

Datais__________inaclassbyplacingdatafieldsinsidethebodyoftheclassdefinition.5. communicateda. providedb. packedc. encapsulatedd.

Constructors have the same name as the __________.6. object itselfa. method itselfb. class itselfc. instance itselfd.

Which of the following statements is true?7. Aclassisauser-definedobjecttypewithatemplatethatservestodefineitsproperties.a. We can declare the instance variables exactly the same way as we declare global variables.b. Creating an object is also referred to as instantiating an object.c. It is important to understand that each object has a its own copy of the instance variables of its object.d.

Page 85: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

75/JNU OLE

Java supports a special type of method, called a ________that enables an object to initialise itself when it is 8. created.

constructora. destructorb. methodc. messaged.

Callingaspecificmethodinanobjectisdescribedassendingtheobjecta_____.9. messagea. communicationb. datac. objectd.

Classnameandsuperclassnameareanyvalid______identifiers.10. objecta. classb. methodc. Javad.

Page 86: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

76/JNU OLE

Chapter VII

Inheritance and Polymorphism in JAVA

Aim

The aim of this chapter is to:

defineinheritance•

elucidate polymorphism•

investigate overriding methods•

Objectives

The objectives of this chapter are to:

elucidate method call binding•

explain the dynamic method dispatching •

discuss the concept of interfaces •

Learning outcome

At the end of this chapter, you will be able to:

identifythefinalmethodsandfinalclasses•

discuss constructors and polymorphism•

comp• rehend dynamic method dispatching

Page 87: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

77/JNU OLE

7.1 Inheritance in JAVAInheritance is a powerful feature that allows new classes to be derived from existing ones. The derived class inherits the interface of the base class and can add new methods or change existing ones to suit its purpose. Any number of classes can be added to an inheritance scheme to produce a hierarchy of related types. The Java implementation of inheritance supports polymorphism, which allows objects of different types to be treated as if they were of the same type.

Developers working with object-oriented languages visualise classes as being related to each other in hierarchies of “kind of” relationships. Just as programmers generalise the common features of objects in an abstract data type, they alsoidentifyandabstractcommonfeaturesofsimilartypesinasuperclass.Oncethesuperclassisdefined,eachsubclassisdefinedasa“kindof”thesuperclass,sothatitcantheninheritthecommonfeatures.Theprogrammerneed only specify the behavior that sets the subclass apart from its parent and its siblings. Java programmers say that the subclasses are derived from the superclass, and refer to them as derived types and base types, respectively.

Programmers conceptualise programs both upward and downward, through levels of abstraction during the design and implementation stages of a development cycle. However, it is observed that they usually tend to think predominantly from the bottom up during the design phase, and predominantly top down during the implementation phase. Once the characteristics of a superclass are well described, its interface can be written before the subclasses are developed. Eachsubclassinheritsbothitssuperclass’sinterfaceanditsimplementation.Itmodifiesandextendstheformer,orextends only the latter, as needed. The use of inheritance produces a hierarchy of classes.

Derivation syntaxThekeywordextendsinthesubclassdefinitionbelowdeclaresoneclassasasubclassofanother.AJavaclassmayderive from at most one base class.

public class TextObject{ public int length () { ... }}public class CompactText extends TextObject{}public class WordProcText extends TextObject{}

Anyuser-definedclassthatdoesnotexplicitlyderivefromanotherclassderivesfromthelibraryclassjava.lang.Object. The Object class is therefore the ultimate base class of all other Java classes. The Object class provides the equals ( ) method as well as other features common to all Java objects.

7.2 Protected AccessInadditiontopublic,privateanddefault(package-friendly)memberaccess,therearetwootheraccessspecifiersthatapply only to derived classes. Any member that is declared protected is accessible only by a class that is derived from the current class or is in the same package as the containing class. Any member that is declared private protected is accessible only by a class that is derived from the containing class.Consider the following example:

Page 88: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

78/JNU OLE

public class A{ protected int x; private protected int y;}

Member x is accessible to any class that derives from class A and to any class in the same package as class A. Member y is only accessible to any class that derives from class A.

Thefiguregivenbelowshowstherelationshipbetweenclasseswithdifferentaccessspecifier.

Package Stuff Package Things

Class A

Class C

Class B Class D

Class E

(derived)

Fig. 7.1 Accessibility in an inheritance relationship

Accessspecifier Accessible by classesPublic A, B, C, D, E

Protected A, B, C, DDefault A, B, C

Private protected A, B, Dprivate A

Table 7.1 Access to class A’s members

7.3 Overriding MethodsTheprocessofaderivedclassredefiningamethodcontainedintheparentclass(withthesameparametertypes)is called overriding the method. Whenever a method is called for a derived-type object, the compiler calls the overriding version instead of the inherited version. The method is thus implemented in a way that is unique to the derived class. The following is a syntax example:

Page 89: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

79/JNU OLE

public class TextObject{ public int length () { //TextObject’s implementation }}public class CompactText extends TextObject{ public int length () { // CompactText’s implementation }}

This allows a programmer to use a parent type variable to point to a derived type object, call a method for that object, and have the compiler call the specialised version. This is how polymorphism is implemented. C++ programmers willrecognisethisasavirtualfunction.InJava,allmethodsarevirtualunlessspecifiedotherwise.

7.3.1 Dynamic Method DispatchingConsider the following example:

class Fish { void eat(), other items... }class Bass extends Fish { void eat()...}class Shark extends Fish { void eat()...}Fishredfish,bluefish;redfish=newBass();bluefish=newShark();redfish.eat();bluefish.eat();

The compiler cannot tell at compile-time which method to call here. The solution entails waiting until run-time to determine which function is the correct one. In other words, the run-time code must check the actual type rather than the apparent type of an object based on the name of the variable used in the code. This is known as dynamic method dispatching.

7.3.2 The Super KeywordIt is often desirable for an overriding implementation of a method to call the inherited implementation of the method. Often, the inherited code need not be completely replaced, only augmented to add some new actions. Any method in a derived class that overrides a method in the base class can call the corresponding base class method by using the super keyword as shown below.

Page 90: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

80/JNU OLE

publicclassWordProcText extends TextObject{ publicintlength() { intlen=super.length(); ... return len; }}

Note that there is no way to access a method overridden more than once.The following code is illegal:

super.super. f()

7.3.3 Final Methods and Final ClassesDynamic lookup takes time. Therefore, there are some situations where it should be disabled. Also, there are some methods for which the compiler must be able to resolve a required action, or for which an overriding version would betoocomplicatedtoimplement.Methodslabelledfinal,private,orstaticarenotsubjecttodynamiclookupbecausethey may not be overridden. Private methods are simply not inherited because they would never be callable anyway. Static methods apply to a particular class’s static data and thus make no sense in a derivation. Final methods are those designated as non-overrideable for reasons of complexity or safety.

7.4 InterfacesSome languages support multiple inheritance in which a child class may derive some of its features from one parentclassandotherfeaturesfromanother(orothers).Thereisacontinuingcontroversyoverwhetherthebenefitspromised by this feature justify the extra complexity that comes with it. Java does not support multiple inheritance. However, it does provide a mechanism called an interface whereby the properties of one class can be used by another without formal inheritance. This enables Java to avoid most of the syntactical complications that multiple inheritance requires.Whenaparentclassistobedefinedasabstract,insteadofdefiningoneormoremethodsasabstract,theclasscanbedefinedwiththekeywordinterfaceinsteadofclass.Thisdefinestheminimumsetofmethodsaclassmust contain.

7.4.1 The Implements DeclarationA derived class cannot have two parent classes, as multiple inheritance leads to problems of how to decide which method to use for inherited methods. Yet multiple inheritance is desirable because it lets an object be assigned into, and thus used as, variables of different types. For example, a programmer might instantiate a Circle as a class derived from Shape, yet wish to pass it into a method requiring a Graphic object parameter.

For example, an interface type is named for derivation with the keyword implements instead of extends. All of its methods are implicitly public and abstract. If desired, they can be declared that way for clarity. Also, any data definedinaninterfacemustbeconstant(i.e.,finalstatic).

Page 91: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

81/JNU OLE

interface Shape{...}

class Circle extends Drawable implements Shape{...}

class Square extends Drawable implements Shape{...}

Shape sp1 = new Circle(), sp2 = new Square();

sp1.area();sp2.area():

The classes circle and square are derived from class drawable, but by implementing shape, they also inherit shape’s interface and are enabled to act as polymorphic instances of Shape.

With interface and implements, Java supports the polymorphic features of multiple inheritance, while yet avoiding the complications of methods implemented in multiple ways.

7.5 PolymorphismPolymorphism is the third essential feature of an object-oriented programming language, after data abstraction and inheritance. It provides another dimension of separation of interface from implementation, to decouple what from how. Polymorphism allows improved code organisation and readability as well as the creation of extensible programs that can be “grown” not only during the original creation of the project but also when new features are desired.

Encapsulation creates new data types by combining characteristics and behaviours. Implementation hiding separates the interface from the implementation by making the details private. This sort of mechanical organisation makes ready sense to someone with a procedural programming background. But polymorphism deals with decoupling in terms of types. The polymorphic method call allows one type to express its distinction from another, similar type, as long as they are both derived from the same base type. This distinction is expressed through differences in behavior of the methods that we can call through the base class.

7.6 Method Calling BindingConnecting a method call to a method body is called binding. When binding is performed before the program is run (by the compiler and linker, if there is one), it is called early binding. We might not have heard the term before because it has never been an option with procedural languages. C compilers have only one kind of method call, and that’s early binding.

The confusing part of the above program revolves around early binding because the compiler cannot know the correct method to call when it has only an instrument reference. The solution is called late binding, which means that the binding occurs at run-time based on the type of object. Late binding is also called dynamic binding or run-time binding. When a language implements late binding, there must be some mechanism to determine the type of the object at run-time and to call the appropriate method. That is, the compiler still doesn’t know the object type, but themethod-callmechanismfindsoutandcallsthecorrectmethodbody.Thelate-bindingmechanismvariesfromlanguage to language, but we can imagine that some sort of type information must be installed in the objects.

AllmethodbindinginJavauseslatebindingunlessamethodhasbeendeclaredfinal.Thismeansthatordinarilywe don’t need to make any decisions about whether late binding will occur; it happens automatically.

Page 92: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

82/JNU OLE

Wedeclareamethodfinalasitpreventsanyonefromoverridingthatmethod.Perhapsmoreimportant,iteffectively“turns off” dynamic binding, or rather it tells the compiler that dynamic binding isn’t necessary. This allows the compilertogenerateslightlymoreefficientcodeforfinalmethodcalls.However,inmostcasesitwon’tmakeanyoverallperformancedifferenceinourprogram,soitisbesttoonlyusefinalasadesigndecision,andnotasanattempt to improve performance.

7.7 Producing the Right BehaviourAfter knowing that all method binding in Java happens polymorphically via late binding, we can write our code to talk to the base class and know that all the derived-class cases will work correctly using the same code. Or to put it anotherway,we“sendamessagetoanobjectandlettheobjectfigureouttherightthingtodo.”

The classic example in OOP is the “shape” example. This is commonly used because it is easy to visualise, but unfortunately it can confuse novice programmers into thinking that OOP is just for graphics programming, which is of course not the case. The shape example has a base class called Shape and various derived types: Circle, Square, Triangle, etc. The reason the example works so well is that it is easy to say “a circle is a type of shape” and be understood. The inheritance diagram shows the relationships:

Cast "up" theinheritance

diagram

Shape

CircleCircle

Handle

Square Triangle

draw ( )erase ( )

draw ( )erase ( )

draw ( )erase ( )

draw ( )erase ( )

Fig. 7.2 Inheritance diagram

The upcast could occur in a statement as simple as:

Shape s = new Circle();

Here, a Circle object is created and the resulting reference is immediately assigned to a Shape, which would seem tobeanerror(assigningonetypetoanother);andyetitisfinebecauseaCircleisaShapebyinheritance.Sothecompiler agrees with the statement and doesn’t issue an error message.Suppose we call one of the base-class methods (that have been overridden in the derived classes):

s.draw();

Again, we might expect that Shape’s draw( ) is called because this is, after all, a Shape reference—so how could the compiler know to do anything else? And yet the proper Circle.draw( ) is called because of late binding (polymorphism).

Page 93: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

83/JNU OLE

The following example puts it a slightly different way:

//: c07:Shapes.java// Polymorphism in java.

class Shape { void draw() {} void erase() {}}class Circle extends Shape { void draw() { System.out.println(“Circle.draw()”); } void erase() { System.out.println(“Circle.erase()”); }}

class Square extends Shape { void draw() { System.out.println(“Square.draw()”); } void erase() { System.out.println(“Square.erase()”); }}

class Triangle extends Shape { void draw() { System.out.println(“Triangle.draw()”); } void erase() { System.out.println(“Triangle.erase()”); }}publicclassShapes{ publicstaticShaperandShape(){ switch((int)(Math.random()*3)){ default: case0:returnnewCircle(); case1:returnnewSquare(); case2:returnnewTriangle(); }}publicstaticvoidmain(String[]args){ Shape[]s=newShape[9]; //Fillupthearraywithshapes: for(inti=0;i<s.length;i++) s[i]=randShape(); //Makepolymorphicmethodcalls: for(inti=0;i<s.length;i++) s[i].draw(); }

Page 94: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

84/JNU OLE

}///:~

The base class Shape establishes the common interface to anything inherited from Shape, i.e., all shapes can be drawnanderased.Thederivedclassesoverridethesedefinitionstoprovideuniquebehaviorforeachspecifictypeof shape.The main class Shapes contains a static method randShape( ) that produces a reference to a randomly-selected Shape object each time we call it. Note that the upcasting happens in each of the return statements, which take a reference to a Circle, Square, or Triangle and sends it out of the method as the return type, Shape. So whenever we call this methodwenevergetachancetoseewhatspecifictypeitis,sinceyoualwaysgetbackaplainShapereference.

main()containsanarrayofShapereferencesfilledthroughcallstorandShape().AtthispointweknowwehaveShapes,butwedon’tknowanythingmorespecificthanthat(andneitherdoesthecompiler).However,whenwestepthroughthisarrayandcalldraw()foreachone,thecorrecttype-specificbehaviormagicallyoccurs,aswecansee from one output example:

Circle.draw()Triangle.draw()Circle.draw()Circle.draw()Circle.draw()Square.draw()Triangle.draw()Square.draw()Square.draw()

Of course, since the shapes are all chosen randomly each time, our runs will have different results. The point of choosing the shapes randomly is to drive home the understanding that the compiler can have no special knowledge that allows it to make the correct calls at compile-time. All the calls to draw( ) are made through dynamic binding.

7.8 ExtensibilityNow let us return to the musical instrument example. Because of polymorphism, we can add as many new types as we want to the system without changing the tune( ) method. In a well-designed OOP program, most or all of our methods will follow the model of tune( ) and communicate only with the base-class interface. Such a program is extensible because we can add new functionality by inheriting new data types from the common base class. The methods that manipulate the base-class interface will not need to be changed at all to accommodate the new classes.

Consider what happens if we take the instrument example and add more methods in the base class and a number of new classes. Here is the diagram:

Page 95: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

85/JNU OLE

Instrument

Wind Percussion Stringed

Woodwind Brass

void play()String what()void adjust()

void play()String what()void adjust()

void play()String what()

void play()String what()void adjust()

void play()void adjust()

void play()String what()void adjust()

Fig. 7.3 Addition of methods and classes to the instrument

Allthesenewclassesworkcorrectlywiththeold,unchangedtune()method.Eveniftune()isinaseparatefileand new methods are added to the interface of Instrument, tune( ) works correctly without recompilation. Here is the implementation of the above diagram:

//c07:music3:Music3.java//An extensible program.import java.util.*;

class Instrument { public void play() { System.out.println(“Instrument.play()”); } public String what() { return “Instrument”; } public void adjust() {}}class Wind extends Instrument { public void play() { System.out.println(“Wind.play()”); } public String what() { return “Wind”; } public void adjust() {}}class Percussion extends Instrument { public void play() { System.out.println(“Percussion.play()”); }

Page 96: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

86/JNU OLE

public String what() { return “Percussion”; } public void adjust() {}}class Stringed extends Instrument { public void play() { System.out.println(“Stringed.play()”); } public String what() { return “Stringed”; } public void adjust() {}}

class Brass extends Wind { public void play() { System.out.println(“Brass.play()”); } public void adjust() { System.out.println(“Brass.adjust()”); }}class Woodwind extends Wind { public void play() { System.out.println(“Woodwind.play()”); } public String what() { return “Woodwind”; }}public class Music3 { //Doesn’t care about type, so new types //added to the system still work right: static void tune(Instrument i) { // ... i.play(); } static void tuneAll(Instrument[] e) { for(int i = 0; i < e.length; i++) tune(e[i]); } public static void main(String[] args) { Instrument[]orchestra=newInstrument[5]; int i = 0; //Upcastingduringadditiontothearray: orchestra[i++]=newWind(); orchestra[i++]=newPercussion(); orchestra[i++]=newStringed(); orchestra[i++]=newBrass(); orchestra[i++]=newWoodwind(); tuneAll(orchestra); }}///:~

The new methods are what( ), which returns a String reference with a description of the class, and adjust( ), which provides some way to adjust each instrument. In main( ), when we place something inside the Instrument array we automatically upcast to Instrument.

Page 97: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

87/JNU OLE

We can see that the tune( ) method is blissfully ignorant of all the code changes that have happened around it, and yet it works correctly. This is exactly what polymorphism is supposed to provide. Our code changes don’t cause damage to parts of the program that should not be affected. Put another way, polymorphism is one of the most important techniques that allow the programmer to “separate the things that change from the things that stay the same.”

7.9 Overriding vs OverloadingIn the following program, the interface of the method play( ) is changed in the process of overriding it, which means that we have not overridden the method, but instead overloaded it. The compiler allows us to overload methods so it gives no complaint. But the behavior is probably not what we want. Here is the example:

//c07:WindError.java// Accidentally changing the interface.

class NoteX { publicstaticfinalint MIDDLE_C = 0, C_SHARP = 1, C_FLAT = 2;}class InstrumentX { public void play(int NoteX) { System.out.println(“InstrumentX.play()”); }}class WindX extends InstrumentX { // OOPS! Changes the method interface: public void play(NoteX n) { System.out.println(“WindX.play(NoteX n)”); }}public class WindError { public static void tune(InstrumentX i) { // ... i.play(NoteX.MIDDLE_C);}public static void main(String[] args) { WindXflute=newWindX(); tune(flute);//Notthedesiredbehavior! }} ///:~

There is another confusing aspect thrown in here. In InstrumentX, the play( ) method takes an int that has the identifierNoteX.EventhoughNoteXisaclassname,itcanalsobeusedasanidentifierwithoutcomplaint.ButinWindX,play()takesaNoteXreferencethathasanidentifiern.(Althoughwecouldevensayplay(NoteXNoteX)without an error.) Thus it appears that the programmer intended to override play( ) but mistyped the method a bit. The compiler, however, assumed that an overload and not an override was intended.

NotethatifwefollowthestandardJavanamingconvention,theargumentidentifierwouldbenoteX(lowercase‘n’), which would distinguish it from the class name.

In tune, the InstrumentX i is sent the play( ) message, with one of NoteX’s members (MIDDLE_C) as an argument. SinceNoteXcontainsintdefinitions,thismeansthattheintversionofthenow-overloadedplay()methodiscalled,and since that has not been overridden the base-class version is used.

Page 98: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

88/JNU OLE

The output is:

InstrumentX.play()

Thiscertainlydoesn’tappeartobeapolymorphicmethodcall.Onceweunderstandwhat’shappening,wecanfixthe problem fairly easily.

7.10 Abstract Classes and MethodsIn all the instrument examples, the methods in the base class Instrument were always “dummy” methods. If these methods are ever called, we’ve done something wrong. That’s because the intent of Instrument is to create a common interface for all the classes derived from it. The only reason to establish this common interface is so it can be expressed differently for each different subtype. It establishes a basic form, so we can say what’s in common with all the derived classes.

Another way of saying this is to call Instrument an abstract base class (or simply an abstract class). We create an abstract class when we want to manipulate a set of classes through this common interface. All derived-class methods that match the signature of the base-class declaration will be called using the dynamic binding mechanism.

If we have an abstract class like Instrument, objects of that class almost always have no meaning. Instrument is meant to express only the interface, and not a particular implementation, so creating an Instrument object makes no sense, and we will probably want to prevent the user from doing it. This can be accomplished by making all the methods in Instrument print error messages, but that delays the information until run-time and requires reliable exhaustive testing on the user’s part. It is always better to catch problems at compile-time.

Java provides a mechanism for doing this called the abstract method. This is a method that is incomplete; it has only a declaration and no method body. Here is the syntax for an abstract method declaration:

abstract void f();

A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods, the classmustbequalifiedasabstract(otherwise,thecompilergivesusanerrormessage).

If an abstract class is incomplete, what is the compiler supposed to do when someone tries to make an object of that class? It cannot safely create an object of an abstract class, so we get an error message from the compiler. This way the compiler ensures the purity of the abstract class, and we don’t need to worry about misusing it.

Ifweinheritfromanabstractclassandwewanttomakeobjectsofthenewtype,wemustprovidemethoddefinitionsfor all the abstract methods in the base class. If we don’t, then the derived class is also abstract and the compiler will force us to qualify that class with the abstract keyword.

It is possible to create a class as abstract without including any abstract methods. This is useful when we’ve got a class in which it doesn’t make sense to have any abstract methods, and yet we want to prevent any instances of that class.

The Instrument class can easily be turned into an abstract class. Only some of the methods will be abstract, since making a class abstract doesn’t force us to make all the methods abstract. Here is what it looks like:

Page 99: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

89/JNU OLE

abstract Instrument

Wind

extends extends extends

extendsextends

Percussion Stringed

Woodwind Brass

abstract void play() ;String what() { /* ... */ }abstract void adjust() ;

void play()String what()void adjust()

void play()String what()

void play()String what()void adjust()

void play()void adjust()

void play()String what()void adjust()

Fig. 7.4 Instrument class into abstract class

Hereistheorchestraexamplemodifiedtouseabstractclassesandmethods://c07:music4:Music4.java// Abstract classes and methods.Import java.util.*;

abstract class Instrument { int i; // storage allocated for each public abstract void play(); public String what() { return “Instrument”; } public abstract void adjust();}class Wind extends Instrument { public void play() { System.out.println(“Wind.play()”); } public String what() { return “Wind”; } public void adjust() {}}class Percussion extends Instrument { public void play() { System.out.println(“Percussion.play()”); } public String what() { return “Percussion”; } public void adjust() {}}class Stringed extends Instrument {

Page 100: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

90/JNU OLE

public void play() { System.out.println(“Stringed.play()”); } public String what() { return “Stringed”; } public void adjust() {}}class Brass extends Wind { public void play() { System.out.println(“Brass.play()”); } public void adjust() { System.out.println(“Brass.adjust()”); }}class Woodwind extends Wind { public void play() { System.out.println(“Woodwind.play()”); } public String what() { return “Woodwind”; }}public class Music4 { // Doesn’t care about type, so new types // added to the system still work right: static void tune(Instrument i) { // ... i.play(); } static void tuneAll(Instrument[] e) { for(int i = 0; i < e.length; i++) tune(e[i]); } public static void main(String[] args) { Instrument[] orchestra = new Instrument[5]; int i = 0; // Upcasting during addition to the array: orchestra[i++]=newWind(); orchestra[i++]=newPercussion(); orchestra[i++]=newStringed(); orchestra[i++]=newBrass(); orchestra[i++]=newWoodwind(); tuneAll(orchestra); }}///:~We can see that there is really no change except in the base class.

It is helpful to create abstract classes and methods because they make the abstractness of a class explicit, and tell both the user and the compiler how it was intended to be used.

Page 101: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

91/JNU OLE

7.11 Constructors and PolymorphismConstructors are different from other kinds of methods. This is also true when polymorphism is involved. Even though constructors are not polymorphic, it is important to understand the way constructors work in complex hierarchies and with polymorphism. This understanding will help us avoid unpleasant entanglements.

7.11.1 Order of Constructor CallsA constructor for the base class is always called in the constructor for a derived class, chaining up the inheritance hierarchy so that a constructor for every base class is called. This makes sense because the constructor has a special job to see that the object is built properly.

A derived class has access to its own members only, and not to those of the base class (whose members are typically private). Only the base-class constructor has the proper knowledge and access to initialise its own elements. Therefore, it is essential that all constructors get called; otherwise the entire object wouldn’t be constructed. That’s why the compiler enforces a constructor call for every portion of a derived class. It will silently call the default constructor if we don’t explicitly call a base-class constructor in the derived-class constructor body. If there is no default constructor, the compiler will complain.

Let us take a look at an example that shows the effects of composition, inheritance, and polymorphism on the order of construction://:c07:Sandwich.java//Orderofconstructorcalls.

Class Meal { Meal(){System.out.println(“Meal()”);}}class Bread { Bread(){System.out.println(“Bread()”);}}class Cheese { Cheese(){System.out.println(“Cheese()”);}}class Lettuce { Lettuce(){System.out.println(“Lettuce()”);}}class Lunch extends Meal { Lunch(){System.out.println(“Lunch()”);}}class PortableLunch extends Lunch { PortableLunch(){ System.out.println(“PortableLunch()”); }}classSandwichextendsPortableLunch{ Breadb=newBread(); Cheesec=newCheese(); Lettuce l = new Lettuce(); Sandwich() { System.out.println(“Sandwich()”); }public static void main(String[] args) { new Sandwich(); }} ///:~

Page 102: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

92/JNU OLE

This example creates a complex class out of other classes, and each class has a constructor that announces itself. TheimportantclassisSandwich,whichreflectsthreelevelsofinheritance(four,ifwecounttheimplicitinheritancefrom Object) and three member objects. When a Sandwich object is created in main( ), the output is:Meal()Lunch()PortableLunch()Bread()Cheese()Lettuce()Sandwich()

This means that the order of constructor calls for a complex object is as follows:The base-class constructor is called. This step is repeated recursively such that the root of the hierarchy is •constructedfirst,followedbythenext-derivedclass,etc.,untilthemost-derivedclassisreached.Member initialisers are called in the order of declaration.•The body of the derived-class constructor is called.•

The order of the constructor calls is important. When we inherit, we know all about the base class and can access any public and protected members of the base class. This means that we must be able to assume that all the members of the base class are valid when we are in the derived class. In a normal method, construction has already taken place, so all the members of all parts of the object have been built. Inside the constructor, however, we must be able to assume that all members that we use have been built. The only way to guarantee this is for the base-class constructor tobecalledfirst.Thenwhenweareinthederived-classconstructor,allthememberswecanaccessinthebaseclasshave been initialised. “Knowing that all members are valid” inside the constructor is also the reason that, whenever possible, we should initialise all member objects (that is, objects placed in the class using composition) at their point ofdefinitionintheclass(forexample,b,c,and1intheexampleabove).Ifwefollowthispractice,wewillhelpensure that all base class members and member objects of the current object have been initialised.

Page 103: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

93/JNU OLE

Summary Inheritance is a powerful feature that allows new classes to be derived from existing ones.•The Java implementation of inheritance supports polymorphism, which allows objects of different types to be •treated as if they were of the same type.Inadditiontopublic,privateanddefault(package-friendly)memberaccess,therearetwootheraccessspecifiers•that apply only to derived classes.Theprocessofaderivedclassredefiningamethodcontainedintheparentclass(withthesameparametertypes)•is called overriding the method.Some languages support multiple inheritance in which a child class may derive some of its features from one •parent class and other features from another.A derived class cannot have two parent classes, as multiple inheritance leads to problems of how to decide •which method to use for inherited methods.Polymorphism is the third essential feature of an object-oriented programming language, after data abstraction •and inheritance.Connecting a method call to a method body is called binding.•When binding is performed before the program is run (by the compiler and linker, if there is one), it is called •early binding.

References Balaguruswamy, E., 2008. • Programming with Java - A Primer, 3/e. 7th ed., Tata McGraw Hill.Deitel, P. J. & Deitel, H. M., 2010. • Java: How to Program, 8th ed., Pearson Prentice Hall.Umbarger, D., 2008. • An Introduction to Polymorphism in Java [pdf] Available at: <http://apcentral.collegeboard.com/apc/public/repository/Intro_to_Polymorphismin_Umbargar.pdf>[Accessed 3 November 2011].Javapassion.com, • Polymorphism [pdf] Available at: <http://www.javapassion.com/javase/javapolymorphism.pdf> [Accessed 3 November 2011]. • Mybringback, 2011. Learn Java- The Basics 10 - Implements an Interface (implementing in Java) [Video Online] Available at: <http://www.youtube.com/watch?v=mCHcdAnXTtc> [Accessed 3 November 2011].JavaTutorialHub, 2011. • Concept of Inheritance & Polymorphism in OOPs: Java 8 [Video Online] Available at: <http://www.youtube.com/watch?v=YY2aQokeKh4> [Accessed 3 November 2011].

Recommended ReadingSchildt, H., 2006. • Java: A Beginner’s Guide, 4th ed., McGraw-Hill Osborne Media.Hunt, J., 2002. • Java and Object Orientation, 2nd ed., Springer.Kak, A., 2003• . Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java, 1st ed., Wiley-IEEE Press.

Page 104: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

94/JNU OLE

Self AssessmentAny number of classes can be added to __________scheme to produce a hierarchy of related types.1.

inheritancea. objectb. methodc. keywordd.

The Java implementation of inheritance supports ____________, which allows objects of different types to be 2. treated as if they were of the same type

encapsulationa. classb. methodc. polymorphismd.

Any method in a derived class that overrides a method in the base class can call the corresponding base class 3. method by using the _____keyword.

basea. superb. abstractc. parentd.

Theprocessofaderivedclassredefiningamethodcontainedintheparentclassiscalled__________.4. overriding the methoda. casting between class typesb. interfacec. abstract classesd.

Which of the following statements is false?5. Connecting a method call to a method body is called binding.a. Connecting a method call to a method class is called binding.b. Inheritance is a powerful feature that allows new classes to be derived from existing ones.c. Polymorphism is the third essential feature of an object-oriented programming language, after data abstraction d. and inheritance.

____________is the third essential feature of an object-oriented programming language, after data abstraction 6. and inheritance.

Encapsulationa. Polymorphismb. Inheritancec. Bindingd.

________is a method whereby the properties of one class can be used by another without formal inheritance.7. Castinga. Overridingb. Interfacec. Chainingd.

Page 105: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

95/JNU OLE

Which of the following statements is true?8. Some languages support multiple inheritance in which a child class may derive some of its features from a. one parent class and other features from another.When binding is performed before the program is run (by the compiler and linker, if there is one), it is called b. dynamic binding.When binding is performed before the program is run (by the compiler and linker, if there is one), it is called c. static binding.A derived class has access to the base class as well.d.

A class containing abstract methods is called __________class9. basea. derivedb. parentc. abstractd.

Only the _________ constructor has the proper knowledge and access to initialise its own elements.10. base-classa. derived-classb. abstract-classc. private-classd.

Page 106: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

96/JNU OLE

Chapter VIII

Exception Handling in Java

Aim

The aim of this chapter is to:

introduce exception handling•

explain how to throw an exception•

elaborate on creating exception classes•

Objectives

The objectives of this chapter are to:

discuss rethrowing exceptions•

elucidate catching multiple exceptions•

explain the types of exceptions•

Learning outcome

At the end of this chapter, you will be able to:

comprehend catching exceptions•

enlist the types of exceptions•

analyse how to cr• eate exception classes

Page 107: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

97/JNU OLE

8.1 Introduction to Exception HandlingThe ideal time to catch an error is at compile-time, before we even try to run the program. However, not all errors can be detected at compile-time. The rest of the problems must be handled at run-time, through some formality that allows the originator of the error to pass appropriate information to a recipient who will know how to handle the difficultyproperly.

For exceptional situations, such as bad input data with the potential to bomb the program, Java uses a form of error-trapping called, exception handling. Exception handling in Java is similar to that in C++.

Dealing with errorsSupposeanerroroccurswhileaJavaprogramisrunning.Theerrormightbecausedbyafilecontainingwronginformation,aflakynetworkconnection,oruseofaninvalidarrayindexoranattempttouseanobjectreferencethat hasn’t yet been assigned to an object. Users expect that programs will act sensibly when errors happen. If an operation cannot be completed because of an error, the program ought to either:

Return to a safe state and enable the user to execute other commands, or•Allow the user to save all his or her work and terminate the program gracefully•

This may not be easy to do: the code that detects the error condition is usually far removed from the code that can roll back the data to a safe state, or the code that can save the user’s work and exit cheerfully. The mission of exception handling is to transfer control from where the error occurred to an error-handler that can deal with the situation. To handle exceptional situations in our program, we must take into account the errors and problems that may occur. The problems that we need consider are:

User input errors•Device errors•Physical limitations•Code errors•

8.2TheClassificationofExceptionsIn Java, an exception object is always an instance of a class derived from throwable.

Throwable

ExceptionError

IOExceptionRuntime

Exception

Fig. 8.1 Exception hierarchy in Java

Notice that all exceptions descend from throwable, but the hierarchy immediately splits into two branches: error and exception. The error hierarchy describes internal errors and resource exhaustion inside the Java runtime system. We should not throw an object of this type. There is little we can do if such an internal error occurs, beyond notifying the user and trying to terminate the program gracefully. These situations are quite rare.

Page 108: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

98/JNU OLE

When doing Java programming, we focus on the exception hierarchy. The exception hierarchy also splits into two branches: exceptions that derive from runtime exception and those that do not. The general rule is this:

A runtime exception happens because we made a programming error. •Any other exception occurs because a bad thing, such as an I/O error, happened to our otherwise good •program.

Exceptions that inherit from runtime exception include problems such as:A bad cast•An out-of-bounds array access•A null pointer access•

Exceptions that do not inherit from runtime exception include:Tryingtoreadpasttheendofafile•Trying to open a malformed url•Tryingtofindaclassobjectforastringthatdoesnotdenoteanexistingclass•

The rule “If it is a RuntimeException, it is our fault” works pretty well. We could have avoided that ArrayIndexOutOfBoundsException by testing the array index against the array bounds. The NullPointerException would not have happened if we would have checked whether or not the variable was null before using it.

TheJavaLanguageSpecificationcallsanyexceptionthatderivesfromtheclassErrorortheclassRuntimeExceptionan unchecked exception. All other exceptions are called checked exceptions. This is useful terminology that we will also adopt.

8.3 Advertising the Exceptions that a Method ThrowsA Java method can throw an exception if it encounters a situation it cannot handle. The idea is simple: a method will not only tell the Java compiler what values it can return, but it will also tell the compiler what can go wrong.

Forexample,codethatattemptstoreadfromafileknowsthatthefilemightnotexistorthatitmightbeempty.Thecodethattriestoprocesstheinformationinafilethereforewillneedtonotifythecompilerthatitcanthrowsomesort of IOException. The place where we advertise that our method can throw an exception is in the header of the method;theheaderchangestoreflectthecheckedexceptionsthemethodcanthrow.

For example, here is the header for a method in the BufferedReader class from the standard library. The method readsalineoftextfromastream,suchasafileornetworkconnection.publicStringreadLine()throwsIOException

The header indicates this method returns a string, but it also has the capacity to go wrong in a special way; by throwing an IOException.

When we write our own methods, we don’t have to advertise every possible throwable object that our method might actually throw. To understand when and what we have to advertise in the throws clause of the methods we write, keep in mind that an exception is thrown in any of the following four situations:

We call a method that throws a checked exception, for example, the readLine method of the BufferedReader •class.We detect an error and throw a checked exception with the throw statement •We make a programming error, such as a• [-1] = 0 that gives rise to an unchecked exception such as an ArrayIndexOutOfBoundsException.An internal error occurs in the virtual machine or runtime library.•

Page 109: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

99/JNU OLE

As with Java methods that are part of the supplied classes, we declare that our method may throw an exception with anexceptionspecificationinthemethodheader.

class MyAnimation{. . .public Image loadImage(String s) throws IOException{. . .}}

If a method might throw more than one checked exception, we must indicate all exceptions in the header. Separate them by a comma as in the following example:

class MyAnimation{. . .public Image loadImage(String s)throws EOFException, MalformedURLException{. . .}}

However, we do not need to advertise internal Java errors, that is, exceptions inheriting from Error. Any code could potentially throw those exceptions, and they are entirely beyond our control. Similarly, we should not advertise unchecked exceptions inheriting from RuntimeException.

class MyAnimation{. . .void drawImage(int i)throws ArrayIndexOutOfBoundsException // NO!!!{. . .}}

These runtime errors are completely under our control.

8.4 How to Throw an ExceptionLetussupposesomethingterriblehashappenedinourcode.Wehaveamethod,readData,i.e.,readinginafilewhose header promised

Content-length: 1024

But,wegetanendoffileafter733characters.Wedecidethissituationissoabnormalthatwewanttothrowanexception. We need to decide what exception type to throw. Some kind of IOException would be a good choice. PerusingtheJavaAPIdocumentation,wefindanEOFExceptionwiththedescription“SignalsthatanEOFhasbeenreached unexpectedly during input.” Perfect. Here is how we throw it:

Page 110: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

100/JNU OLE

throw new EOFException();or,EOFExceptione=newEOFException();throwe;

Hereishowitallfitstogether:String readData(BufferedReader in) throws EOFException{. . .while (. . .){if (ch == -1) // EOF encountered{if (n < len)throw new EOFException();}. . .}return s;}

The EOFException has a second constructor that takes a string argument. We can put this to good use by describing the exceptional condition more carefully.Stringgripe=“Content-length:“+len+“,Received:“+n;thrownewEOFException(gripe);

As we can see, throwing an exception is easy if one of the existing exception classes works for us. In this case:Find an appropriate exception class•Make an object of that class•Throw it•

Once a method throws an exception, the method does not return to its caller. This means that we do not have to worry about cooking up a default return value or an error code.

8.5 Creating Exception ClassesOur code may run into a problem that is not adequately described by any of the standard exception classes. In this case, it is easy enough to create our own exception class. Just derive it from Exception or from a child class of Exception such as IOException. It is customary to give both a default constructor and a constructor that contains a detailed message.

class FileFormatException extends IOException{public FileFormatException() {}public FileFormatException(String gripe){super(gripe);}}

Now we are ready to throw our very own exception type.String readData(BufferedReader in) throws FileFormatException{

Page 111: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

101/JNU OLE

. . .while (. . .){if (ch == -1) // EOF encountered{if (n < len)throw new FileFormatException();}. . .}return s;}

Throwable(): constructs a new throwable object with no detailed message.•Throwable(Stringmessage): constructs a new throwable objectwith the specified detailedmessage.By•convention, all derived exception classes support both a default constructor and a constructor with a detailed message.String getMessage(): gets the detailed message of the throwable object.•

8.6 Catching ExceptionsWe now know how to throw an exception. It is pretty easy. We throw it and forget it. Of course, some code has to catch the exception. Catching exceptions requires more planning.

If an exception occurs that is not caught anywhere in a non-graphical application, the program will terminate and print a message to the console giving the type of the exception and a stack trace. A graphics program (both an applet and an application) prints the same error message, but the program goes back to its user interface processing loop. (When we are debugging a graphically based program, it is a good idea to keep the console available on the screen and not minimised).

To catch an exception, we set up a try/catch block. The simplest form of the try block is as follows:try{codemore codemore code}catch (ExceptionType e){handler for this type}

Ifanyofthecodeinsidethetryblockthrowsanexceptionoftheclassspecifiedinthecatchclause,then,The program skips the remainder of the code in the try block•The program executes the handler code inside the catch clause•

If none of the code inside the try block throws an exception, then the program skips the catch clause. If any of the code in a method throws an exception of a type other than the one named in the catch clause, this method exits immediately.

Page 112: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

102/JNU OLE

To show this at work, here is some fairly typical code for reading in text:publicvoidread(BufferedReaderreader){try{boolean done = false;while (!done){String line = reader.readLine();if(line==null)//endoffiledone = true;else{process line;}}}catch (IOException exception){exception.printStackTrace();}}

Notice that most of the code in the try clause is straightforward: it reads and processes lines until we encounter the end ofthefile.AswecanseebylookingattheJavaAPI,thereisthepossibilitythatthereadLinemethodwillthrowanIOException. In that case, we skip out of the entire while loop, enter the catch clause and generate a stack trace.

Often, the best choice is to do nothing at all. If an error occurs in the readLine method, let the caller of the read method worry about it! If we take that approach, then we have to advertise the fact that the method may throw an IOException.

publicvoidread(BufferedReaderreader)throwsIOException{boolean done = false;while (!done){String line = reader.readLine();if(line==null)//endoffiledone = true;else{process line;}}}

Remember,thecompilerstrictlyenforcesthethrowsspecifier.Ifwecallamethodthatthrowsacheckedexception,we must either handle it or pass it on. Which of the two is better? As a general rule, we should catch those exceptions that we know how to handle, and propagate those that we do not know how to handle. When we propagate an exception,wemustaddathrowsspecifiertoalertthecallerthatanexceptionmaybethrown.

Page 113: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

103/JNU OLE

8.7 Catching Multiple ExceptionsWe can catch multiple exception types in a try block and handle each type differently. We use a separate catch clause for each type as in the following example:try{code that mightthrow exceptions}catch (MalformedURLException e1){// emergency action for malformed URLs}catch (UnknownHostException e2){// emergency action for unknown hosts}catch (IOException e3){// emergency action for all other I/O problems}

The exception object (e1, e2, e3) may contain information about the nature of the exception.Tofindoutmoreabouttheobject,trye3.getMessage()

to get the detailed error message (if there is one), ore3.getClass().getName()

to get the actual type of the exception object.

8.8 Rethrowing ExceptionsOccasionally, we need to catch an exception without addressing the root cause of it. This need typically occurs when we have to do some local cleanup but can’t fully resolve the problem. We then want to take our emergency action and again call throw to send the exception back up the calling chain. We can see a typical example of this in the following code.Graphics g = image.getGraphics();try{code that mightthrow exceptions}catch (MalformedURLException e){g.dispose();throw e;}

The above code shows one of the most common reasons for having to rethrow an exception that we have caught. If we do not dispose of the graphics context object in the catch clause, it will never be disposed of.

On the other hand, the underlying cause, the malformed URL exception, has not disappeared.

Page 114: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

104/JNU OLE

We still want to report it to the authorities, who presumably know how to deal with such an exception. We can also throw a different exception than the one we catch.try{acme.util.Widget a = new acme.util.Widget();a.load(s);a.paint(g);}catch (RuntimeException e){// sheesh—another ACME errorthrow new Exception(“ACME error”);}

ThefinallyclauseWhen our code throws an exception, it stops processing the remaining code in our method and exits the method. This is a problem if the method has acquired some local resource that only it knows about and if that resource must be cleaned up. One solution is to catch and rethrow all exceptions. But this solution is tedious because you need to clean up the resource allocation in two places, in the normal code and in the exception code.

Javahasabettersolution,thefinallyclause:Graphics g = image.getGraphics();try{code that mightthrow exceptions}catch(IOExceptione){show error dialog}finally{g.dispose();}

Thisprogramexecutesthecodeinthefinallyclausewhetherornotanexceptionwascaught.Thismeans,intheexample code above, the program will dispose of the graphics context under all circumstances.

Letuslookatthethreepossiblesituationswheretheprogramwillexecutethefinallyclause.Thecodethrowsnoexceptions.Inthisevent,theprogramfirstexecutesallthecodeinthetryblock.Then,it•executesthecodeinthefinallyclause.Afterwards,executioncontinueswiththefirstlineafterthetryblock.The code throws an exception that is caught in a catch clause, in our case, an IOException. For this, the program •executes all code in the try block, up to the point at which the exception was thrown. The remaining code in the try block is skipped. Then, the program executes the code in the matching catch clause, then the code in thefinallyclause.Ifthecatchclausedoesnotthrowanexception,thentheprogramexecutesthefirstlineafterthetryblock.Ifit•does, then the exception is thrown back to the caller of this method.The code throws an exception that is not caught in any catch clause. For this, the program executes all code in •the try block until the exception is thrown. The remaining code in the try block is skipped. Then, the code in thefinallyclauseisexecuted,andtheexceptionisthrownbacktothecallerofthismethod.

Page 115: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

105/JNU OLE

Wecanusethefinallyclausewithoutacatchclause.Forexample,considerthefollowingtrystatement:Graphics g = image.getGraphics();try{code that mightthrow exceptions}finally{g.dispose();}

Theg.dispose()commandinthefinallyclauseisexecutedwhetherornotanexceptionisencounteredinthetryblock. Of course, if an exception is encountered, it is rethrown and must be caught in another catch clause.

Page 116: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

106/JNU OLE

SummaryFor exceptional situations, such as bad input data with the potential to bomb the program, Java uses a form of •error-trapping called, exception handling.If an operation cannot be completed because of an error, the program ought to either: return to a safe state •and enable the user to execute other command, or allow the user to save all his or her work and terminate the program gracefully.The mission of exception handling is to transfer control from where the error occurred to an error-handler that •can deal with the situation. To handle exceptional situations in our program, we must take into account the errors and problems that may •occur. The problems that we need consider are: user input errors, device errors, physical limitations, and code errors.In Java, an exception object is always an instance of a class derived from throwable. All exceptions descend •from throwable, but the hierarchy immediately splits into two branches: error and exception.The error hierarchy describes internal errors and resource exhaustion inside the Java runtime system. •When doing Java programming, we focus on the exception hierarchy. The exception hierarchy also splits into •two branches: exceptions that derive from runtime exception and those that do not.A Java method can throw an exception if it encounters a situation it cannot handle. The idea is simple: a method •will not only tell the Java compiler what values it can return, it will also the compiler what can go wrong. Catching exceptions requires more planning. If an exception occurs that is not caught anywhere in a non-graphical •application, the program will terminate and print a message to the console giving the type of the exception and a stack trace.

ReferencesBalaguruswamy, E., 2008. • Programming with Java - A Primer, 3/e. 7th ed., Tata McGraw Hill.Samanta, D., 2004. • Object-Oriented Programming with C++ and Java, PHI Learning Pvt. Ltd.Huntrods, R. S., 2001. • Exception Handling in Java [Online]. Available at: <http://huntrods.com/teaching/exceptions/exceptions.ppt> [Accessed 20 November 2011].Javapassion.com, • Java Exception Handling [pdf] Available at: <http://www.javapassion.com/javase/javaexceptions.pdf> [Accessed 20 November 2011].Thenewboston, 2009. • Java Programming Tutorial - 82 - Exception Handling [Video Online] Available at: <http://www.youtube.com/watch?v=K_-3OLkXkzY>[Accessed3November2011].Lifemichael, 2011. • ThefinallyBlock inJavaScript [Video Online] Available at: <http://www.youtube.com/watch?v=65RPD71v6gI> [Accessed 3 November 2011].

Recommended ReadingStelting, S., 2004. • Robust Java: Exception Handling, Testing, and Debugging, Prentice Hall.Poo, D. & Kiong, D., 2010. • Object-Oriented Programming and Java. 2nd ed., Springer.Ibsen, C. & Anstey, J., 2011. • Camel in Action, 1st ed., Manning Publications.

Page 117: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

107/JNU OLE

Self AssessmentThe error hierarchy describes _________errors and resource exhaustion inside the Java runtime system.1.

externala. internalb. object-orientedc. run-timed.

A Java method can throw an exception if it encounters a situation it _________.2. cannot handlea. can handleb. can derivec. can compiled.

The mission of exception handling is to _______ control from where the error occurred to an error-handler that 3. can deal with the situation

managea. changeb. transferc. handled.

Which of the following statements is false?4. Our code may run into a problem that is not adequately described by any of the standard exception a. classesOnce a method throws an exception, the method does not return to its callerb. A Java method can throw an exception if it encounters a situation it can handle. c. When doing Java programming, we focus on the exception hierarchyd.

A ________exception happens because we made a programming error.5. runtimea. nullpointerb. uncheckedc. throwabled.

The place where we advertise that our method can throw an exception is in the ______of the method.6. stringa. hierarchyb. bodyc. headerd.

Which of the following statements is true?7. Users expect that programs will act insensibly when errors happen.a. The ideal time to catch an error is at run-time, before we even try to run the program. b. In Java, an exception object is always an instance of a class derived from throwable.c. When we write our own methods, we have to advertise every possible throwable object that our method d. might actually throw.

Page 118: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

108/JNU OLE

In Java, an exception object is always an instance of a class derived from _______.8. objecta. throwableb. programc. systemd.

Whenwepropagateanexception,wemustaddathrowsspecifiertoalertthecallerthatanexceptionmaybe9. ________.

throwna. handledb. rethrownc. cancelledd.

If we call a method that throws ________exception, we must either handle it or pass it on.10. uncheckeda. checkedb. runtimec. nullpointerd.

Page 119: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

109/JNU OLE

Application I

Inventory Management System

This software is designed to manage your inventory system, with a facility of adding, modifying, deleting, viewing, searching, and analysing an item stored in an inventory.

#include<iostream.h>#include<conio.h>#include<iomanip.h>#include<fstream.h>#include<graphics.h>#include<dos.h>#include<string.h>#include<stdio.h>#include <time.h>fstreaminoutfile;//Menu Global Item#definepixTOrc(x)(8*(x-1))//convertpixelintorowandcolformat#defineINC5//IncrementDistanceBetweenMenuItems#defineROW15//RowValueforMenuItem#defineCOL8//ColumnValueforMenuItem// To display the Inventory Main menu optionstypedef char option[15];option mainMenu[]= { “New Record”, “Display”, “Search”, “Updation”, “Deletion”, “Analysis”, “Exit”};

/*-------------------Inventory Class--------------------*/class Inventory{ char itemNo[2],itemName[20]; int qty; double price,amt; public: char *getno(){return itemNo;} char *getitem(){ return itemName;} double getamt(){return amt;} void getdata(); void showdata(int,int); voidshowspecific(); voidalterspecific(char*,char*);};void Inventory :: getdata(){ gotoxy(30,12); cout<<”Enter Item Number : ?”; cin>>itemNo; gotoxy(30,14);

Page 120: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

110/JNU OLE

cout<<”Enter Item Name : ?”; cin>>itemName; gotoxy(30,16); cout<<”Enter Quantity : ?”; cin>>qty; gotoxy(30,18); cout<<”Enter Price : ?”; cin>>price; amt = price * qty;}void Inventory :: showdata(int x,int y){ gotoxy(x,y); cout.setf(ios::left,ios::adjustfield); cout<<setw(3)<<itemNo; cout.setf(ios::left,ios::adjustfield); cout<<setw(13)<<itemName; cout<<setw(4)<<qty; cout.setf(ios::right,ios::adjustfield); cout.setf(ios::showpoint); cout.setf(ios::fixed,ios::floatfield); cout<<setprecision(2)<<setw(8)<<price; cout.setf(ios::right,ios::adjustfield); cout.setf(ios::showpoint); cout.setf(ios::fixed,ios::floatfield); cout<<setprecision(2)<<setw(15)<<amt;}voidInventory::showspecific(){ gotoxy(30,13); cout<<”--Search Item Found--”; gotoxy(30,15); cout<<”Item No : “; cout.setf(ios::left,ios::adjustfield); cout<<itemNo; gotoxy(30,17); cout<<”Item Name : “; cout.setf(ios::left,ios::adjustfield); cout<<itemName; gotoxy(30,19); cout<<”Quantity : “; cout<<qty; cout.setf(ios::right,ios::adjustfield); cout.setf(ios::showpoint); cout.setf(ios::fixed,ios::floatfield); gotoxy(30,21); cout<<”Price : “; cout<<setprecision(2)<<price; gotoxy(30,23); cout<<”Amount : “; cout.setf(ios::right,ios::adjustfield); cout.setf(ios::showpoint); cout.setf(ios::fixed,ios::floatfield); cout<<setprecision(2)<<amt;}

Page 121: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

111/JNU OLE

voidInventory::alterspecific(charitmno[2],charitmname[20]){ strcpy(itemNo,itmno); strcpy(itemName,itmname); gotoxy(30,16); cout<<”Enter Quantity : ?”; cin>>qty; gotoxy(30,18); cout<<”Enter Price : ?”; cin>>price; amt = price * qty;}/*---------------Inventory Codes End------------------*//*--------------Menu and all other functions Code--------------*///Displays Graphic text in delaying fashionvoid displayMe(int x,int y,const char *ch,int delayTime){ char d[2]; int len=strlen(ch); for(int i=0;i<=len;i++) { d[0]=ch[i]; d[1]=’

(Source: Railway Seat Reservation Question Which Comes In Sapient [Online] Available at: <http://www.sourcecodesworld.com/source/show.asp?ScriptID=604> [Accessed 25 November 2011])

QuestionsWhat is a class?1. SolutionClassisuserdefineddatatypethatcontainsorholdsbothdataandmemberfunction.Itisthecollectionofdifferent data type.

What is the difference between class and structure?2. SolutionStructure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public. Class: Class is a successor of Structure. By default all the members inside the class are private. In structures there is no reusability, encapsulation and abstraction. But with class we can achieve the concept of reusability, encapsulation and abstraction. C++ introduced inheritance concept to achieve reusability. we can use the base classcontentinderivedclassdependsupontheaccessspecifiertype.

What is the return value for getch()?3. Solutiongetch()functionisspecifiedinConio.hheaderfile,andgetsacharacterfromthekeyboard.Itsprototypeis:intgetch(void); It obtains a character from stdin. Input is unbuffered, and this routine will return as soon as a character is available without waiting for a carriage return. The character is not echoed to stdout.

Page 122: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

112/JNU OLE

Application II

Railway seat reservation

DescriptionIn a train compartment there are 67 seats...13 rows of 5 (3 by2) seats and the last row has 2 sets. A person cannot book more than 5 seats. If a person is booking then it should be such that maximum people of the group get to sit in the same row.

Code for the program#include<iostream.h>#include<conio.h>#include<stdio.h>struct rail{ int seatNo; int isEmpty;}seat[67];void reserve(int n);int arrRowState[15];void main(){ for(int i = 0 ; i <67 ; i++) { seat[i].seatNo=(i+1); seat[i].isEmpty=1; } for(i=0 ; i<13 ; i++) arrRowState[i]=5;

arrRowState[13]=2; arrRowState[14]=67; char res=’y’; do { int n; clrscr(); cout<<”Enter d no of seats u want to reserve : “; cin>>n; reserve(n); cout<<”Do u want to reserve more seats?”; res=getchar(); }while(res!=’n’);}void reserve(int n){ if(n>arrRowState[14]) { cout<<”Too large group to accomodate”; getch(); return; }

Page 123: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

113/JNU OLE

intflag=0; int seatbook; for(inti=0;flag==0&&i<=13;i++) { if(arrRowState[i] >= n) { flag=1; // cout<<”Following Seats Alloted”; seatbook=(((i)*5)+(6-arrRowState[i])); for(int j = 0 ; j < n ; j++) { cout<<”“<<seatbook+j<<”“; seat[(seatbook+j)].isEmpty=0; } arrRowState[i]=arrRowState[i]-n; arrRowState[14]=arrRowState[14]-n; } } if(flag==0) { while(n!=0) { int max,rowNo=0; max=arrRowState[0]; for( int j = 0 ; j<14 ; j++) { if(arrRowState[j] > max) { max=arrRowState[j]; rowNo=j; } } if(n>max) { n=n-max; seatbook=(((rowNo)*5)+(6-arrRowState[rowNo])); arrRowState[rowNo]=arrRowState[rowNo]-max; for( int j = 0 ; j<max ; j++) { cout<<”“<<(seatbook+j)<<”“; seat[(seatbook+j)].isEmpty=0; } } else { reserve(n); n=0; } }

Page 124: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

114/JNU OLE

} getch();}

(Source: Railway Seat Reservation Question Which Comes In Sapient [Online] Available at: <http://www.sourcecodesworld.com/source/show.asp?ScriptID=1248> [Accessed 25 November 2011])

QuestionsWhat does void main mean?1. What is the difference between function and member function?2. Isitpossibletotake“mainfunction”asoftypefloat,char,etc.?3.

Page 125: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

115/JNU OLE

Application III

Java Card

Java Card refers to a technology that allows Java-based applications (applets) to run securely on smart cards and similar small memory footprint devices. Java Card is the tiniest of Java targeted for embedded devices. Java Card givestheuserabilitytoprogramthedeviceandmakethemapplicationspecific.ItiswidelyusedinSIMcards(usedinGSMmobilephones)andATMcards.ThefirstJavaCardwasintroducedin1996bySchlumberger’scarddivision which later merged with Gemplus to form Gemalto.

JavaCardproductsarebasedontheJavaCardPlatformspecificationsdevelopedbySunMicrosystems,asubsidiaryofOracleCorporation.Many Java card products also rely on theGlobalPlatform specifications for the securemanagement of applications on the card (download, installation, personalisation, deletion). The main design goals of the Java Card technology are portability and security.

PortabilityJavaCardaimsatdefiningastandardsmartcardcomputingenvironment,allowingthesameJavaCardapplettorunon different smart cards, much like a Java applet that runs on different computers. As in Java, this is accomplished usingthecombinationofavirtualmachine(theJavaCardVirtualMachine)andawell-definedruntimelibrary,which largely abstracts the applet from differences between smart cards. Portability remains mitigated by issues ofmemorysize,performance,andruntimesupport(Forexample,forcommunicationprotocolsorcryptographicalgorithms).

SecurityJava Card technology was originally developed for the purpose of securing sensitive information stored on smart cards. Security is determined by various aspects of this technology.

Data encapsulationData is stored within the application and Java Card applications are executed in an isolated environment (the Java Card VM), separate from the underlying operating system and hardware.

Applet FirewallUnlike other Java VMs, a Java Card VM usually manages several applications, each one controlling sensitive data. Differentapplicationsarethereforeseparatedfromeachotherbyanappletfirewallwhichrestrictsandchecksaccessof data elements of one applet to another.

CryptographyCommonly used encryption algorithms such as DES, Triple DES, AES, RSA (including elliptic curve cryptography) are supported. Other cryptographic services like signing, key generation and key exchange are also supported.

AppletThe applet is a state machine which processes only incoming command requests and responds by sending data or response status words back to the interface device.

(Source: Java Card – Technology for Today’s World [Online] Available at: <http://www.articlesbase.com/software-articles/java-card-technology-for-todays-world-2709902.html> [Accessed 3 November 2011].)

QuestionsWhat does Java Card mean? 1. When was the Java Card introduced in the market?2. What does ‘portability’ mean with reference to Java Card?3. What do you mean by security in Java Card? 4.

Page 126: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

116/JNU OLE

Bibliography

ReferencesArnold, 2000• . The Java Programming Language, Pearson Education India.Balagurusamy, E., 2006. • Object Oriented Programming with C++, 3rd ed., Tata McGraw Hill.Balaguruswamy, E., 2008. • Programming with Java - A Primer, 3/e. 7th ed., Tata McGraw Hill.Brown, L., Basic Object-Oriented Programming in Java [pdf] Available at: <http://notes.corewebprogramming.•com/student/Java-OOP.pdf> [Accessed 24 November 2011].C++ Programming [13] - Classes (part 1),• 2010. [Video Online] Available at: <http://www.youtube.com/watch?v=3x0lPQROfxg> [Accessed 14 November 2011].C++ Tutorial 11: Classes and Objects in C++• [Video Online] Available at: <http://www.youtube.com/watch?v=5cZAmJyMyjA> [Accessed 14 November 2011].Classes and Objects in Java• [Online]. Available at:<http://docstore.mik.ua/orelly/java/javanut/ch03_01.htm> [Accessed 19 November 2011]Dale, N. B. & Weems, C., 2007. • Programming and problem solving with Java, 2nd ed., Jones & Bartlett Learning. Deitel, P. J. & Deitel, H. M., 2010. • Java: how to program, 8th ed., Pearson Prentice Hall.Elzwai,2010.WhatisJava[VideoOnline]Availableat:<http://www.youtube.com/watch?v=pxbb8vthXKQ&•feature=related> [Accessed 3 November 2011].Exforsys Inc., 2007. • C++ Objects and Classes [Online] Available at: <http://www.exforsys.com/tutorials/c-plus-plus/c-plus-plus-objects-and-classes.html> [Accessed 14 November 2011].FreeComputerTutor, 2010. • Object oriented programming [Video Online] Available at: <http://www.youtube.com/watch?v=hX1Q9wQ5QMk> [Accessed 3 November 2011].Huntrods, R. S., 2001. • Exception Handling in Java, [Online]. Available at: <http://huntrods.com/teaching/exceptions/exceptions.ppt> [Accessed 20 November 2011].Intap.net. • What is an object? [Online] Available at: <http://www.intap.net/~drw/cpp/cpp06_01.htm> [Accessed 14 November 2011].Jana, D., 2005, • C++ and Object-Oriented Programming Paradigm, 2nd ed., PHI Learning Pvt. Ltd.Javabeginner.com, 2008, • Java Classes and Objects [Online]. Available at: <http://www.javabeginner.com/learn-java/java-classes-and-objects> [Accessed 19 November 2011].Javapassion.com,• Java Exception Handling [pdf] Available at: <http://www.javapassion.com/javase/javaexceptions.pdf> [Accessed 20 November 2011].Javapassion.com, • Polymorphism [Online] Available at: <http://www.javapassion.com/javase/javapolymorphism.pdf> [Accessed 3 November 2011].JavaTutorialHub, 2011. • Concept of Inheritance & Polymorphism in OOPs: Java 8 [Video Online] Available at: <http://www.youtube.com/watch?v=YY2aQokeKh4> [Accessed 3 November 2011].Keogh, J., 2004. • Object Oriented Programming: Principles and Fundamentals, Dreamtech Press.Lifemichael, 2011. • ThefinallyBlock inJavaScript [Video Online] Available at: <http://www.youtube.com/watch?v=65RPD71v6gI> [Accessed 3 November 2011]Msdn.microsoft.com, 2011. • C++ Exception Handling [Online] Available at: <http://msdn.microsoft.com/en-us/library/4t3saedz.aspx>[Accessed3November2011].Mulholland, A. & Murphy, G., 2003. • Java 1.4 Game Programming, Word Ware Publishing. Mybringback, 2011. • Learn Java- The Basics 10- Implements an Interface (implementing in java) [Video Online] Available at: <http://www.youtube.com/watch?v=mCHcdAnXTtc> [Accessed 3 November 2011].

Page 127: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

117/JNU OLE

Nirosh, 2011, • Introduction to Object-Oriented Programming Concepts and More [Online] Available at: <http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx#Abstract> [Accessed 3 November 2011].Object Oriented Programming using Java• [pdf] Available at: <http://math.hws.edu/eck/cs124/downloads/OOP2_from_Univ_KwaZulu-Natal.pdf> [Accessed 24 November 2011].Parsons, D., 2002. • Object Oriented Programming with C++, 2nd ed., Cengage Learning EMEA.Pitts, R.I., 2000• . Introduction to Polymorphism in C++ [Online] Available at : <http://www.cs.bu.edu/teaching/cpp/polymorphism/intro/>[Accessed 3 November 2011].Samanta, D., 2004. • Object-Oriented Programming with C++ and Java, PHI Learning Pvt. Ltd.ssby79, 2010. • Java Tutorial: Creating Objects [Video Online] Available at: <http://www.youtube.com/watch?v=IQmOONWhhYY> [Accessed 3 November 2011].Stroustrup. B., 2002. • A Tour of C++ [Online] (Updated 18January 2002] Available at <http://www.informit.com/articles/article.aspx?p=25003&seqNum=3> [Accessed 3 November 2011].Tenoul.com. • C++ Object Oriented: Readme First [Online] Available at: <http://www.tenouk.com/cplusplustutorial.html> [Accessed 3 November 2011].Thenewboston, 2009. • Java Programming Tutorial - 17 – Constructors [Video Online] Available at: <http://www.youtube.com/watch?v=tPFuVRbUTwA> [Accessed 3 November 2011].Thenewboston, 2009. • Java Programming Tutorial - 82 - Exception Handling [Video Online] Available at: <http://www.youtube.com/watch?v=K_-3OLkXkzY>[Accessed3November2011].Thomas, C., 2009. • An Introduction to Object-Oriented Programming with Java, McGraw-Hill Higher Education.Umbarger, D., 2008. • An Introduction to Polymorphism in Java [pdf] Available at: <http://apcentral.collegeboard.com/apc/public/repository/Intro_to_Polymorphismin_Umbargar.pdf>[Accessed 3 November 2011]Venugopal, K. R., 1997. Mastering C++, Muhammadali Shaduli.•VTC, 2011. • C++ Fundamentals: 06. Classes Objects [Video Online] Available at: <http://www.youtube.com/watch?v=UH3tRiX8bdo> [Accessed 3 November 2011].VTC, 2011. • C++ Fundamentals: 51. Exception Handling [Video Online] Available at: <http://www.youtube.com/watch?v=MMGEc3angZ8&feature=results_video&playnext=1&list=PLB08C597637C40FC4> [Accessed 3 November 2011].Williams, A., 2001. Introduction to C++ Templates [pdf] Available at: <http://www.justsoftwaresolutions.co.uk/•articles/intrototemplates.pdf> [Accessed 3 November 2011].www.tihl.info, 2009. • 002 - The Java Virtual Machine [Video Online] Available at: <http://www.youtube.com/watch?v=K8I1OqXkYwc> [Accessed 3 November 2011].Xoax.net, 2009• . C++ Console Lesson 19: Function Templates [Video Online] Available at: <http://www.youtube.com/watch?v=0e1ia9wfPnQ> [Accessed 3 November 2011].Xoax.net, 2009. • C++ Console Lesson 38: Simple Inheritance [Video Online] Available at: <http://www.youtube.com/watch?v=UIrDafFNr2U> [Accessed 3 November 2011].Xoax.net, 2009. • C++ Console Lesson 42: Virtual Member Functions [Accessed 3 November 2011].

Recommended ReadingAnderson, J. & Franceschi, H. 2008. • Java 6 illuminated: an active learning approach. Jones & Bartlett Learning.Barnes, D. & Barnes, D. J., 2000. • Object-oriented programming with Java: an introduction, Prentice Hall.Barnes, D. J. & Kolling, M., 2008. • Objects First With Java: A Practical Introduction Using BlueJ. 4th ed., Prentice Hall.Bronson, G. J., 2005. • Object-Oriented Program Development Using Java: A Class-Centered Approach, 2nd ed., Course Technology.

Page 128: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

118/JNU OLE

Farrell, J., 2008. • Object Oriented Programming using C++, 4th ed., Course Technology, USA; Cengage Learning.Farrell, J., 2008• . Object-Oriented Programming Using C++, 4th ed., Cengage Learning.Horstmann, C. S. & Cornell, G., 2001. • Core Java 2: Fundamentals. Prentice Hall PTR.Hunt, J., 2002. • Java and Object Orientation, 2nd ed., Springer.Ibsen, C. & Anstey, J., 2011. • Camel in Action, 1st ed., Manning Publications.Johnsonbaugh, R. & Kalin, M., 1999. • Object-Oriented Programming in C++, 2nd ed., Prentice Hall.Josuttis, N.M., 2002. • Object-Oriented Programming in C++, 1st ed., WileyKak, A., 2003. • Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java, 1st ed., Wiley-IEEE Press.Kak, A., 2003. • Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java, 1st ed., Wiley-IEEE Press.Koffman, E.B., 2005. • Objects, Abstraction, Data Structures and Design: Using C++, Wiley.Lafore, R., 1998. • Object Oriented Programming in C++. 3rd ed., Macmilian Computer Publishing.Lafore, R., 2001. • Object-Oriented Programming in C++. 4th ed., Sams.Lafore, R.• , 2002. Object Oriented Programming in C++, 4th ed., Pearson Education India; Dorling Kindersley (India) Pvt. Ltd.Poo, D. & Kiong, D., 2010. • Object-Oriented Programming and Java, 2nd ed., Springer.Schildt, H., 2006. • Java: A Beginner’s Guide, 4th ed., McGraw-Hill Osborne Media.Sierra, K., 2005. • Head First Java, 2nd ed., O’Reilly Media.Skinner, M. T., 1992. • The advanced C++ book, Volume 1, Silicon Press.Stelting, S., 2004. • Robust Java: Exception Handling, Testing, and Debugging, Prentice Hall.Stroustrup, B., 2000. • The C++ Programming Language: Special Edition, 3rd ed., Addison-Wesley Professional.

Page 129: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

119/JNU OLE

Self Assessment Answers

Chapter Ia1. c2. a3. b4. c5. a6. c7. d8. a9. b10.

Chapter IIa1. c2. a3. c4. d5. b6. a7. c8. d9. b10.

Chapter IIIb1. c2. a3. a4. c5. b6. a7. d8. a9. c10.

Chapter IVa1. b2. b3. d4. c5. a6. d7. a8. d9. c10.

Page 130: C++ and Javajnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem... · II/JNU OLE Contents Chapter I..... 1

C++ and Java

120/JNU OLE

Chapter Va1. b2. c3. d4. a5. b6. c7. d8. a9. b10.

Chapter VIb1. a2. c3. a4. d5. c6. c7. a8. a9. d10.

Chapter VIIa1. d2. b3. a4. b5. b6. c7. a8. d9. a10.

Chapter VIIIb1. a2. c3. c4. a5. d6. c7. b8. a9. b10.