object oriented programming - jaipur national universityjnujprdistance.com/assets/lms/lms...

152
Object Oriented Programming

Upload: others

Post on 21-May-2020

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

Page 2: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Board of Studies

Prof. H. N. Verma Prof. M. K. GhadoliyaVice- Chancellor Director, Jaipur National University, Jaipur School of Distance Education and Learning Jaipur National University, JaipurDr. Rajendra Takale Prof. and Head AcademicsSBPIM, Pune

___________________________________________________________________________________________

Subject Expert Panel

Dr. Ramchandra G. Pawar Ashwini PanditDirector, SIBACA, Lonavala Subject Matter ExpertPune

___________________________________________________________________________________________

Content Review Panel

Gaurav Modi Shubhada PawarSubject Matter Expert Subject Matter Expert

___________________________________________________________________________________________Copyright ©

This book contains the course content for Object Oriented Programming.

First Edition 2013

Printed byUniversal Training Solutions Private Limited

Address05th Floor, I-Space, Bavdhan, Pune 411021.

All rights reserved. This book or any portion thereof may not, in any form or by any means including electronic or mechanical or photocopying or recording, be reproduced or distributed or transmitted or stored in a retrieval system or be broadcasted or transmitted.

___________________________________________________________________________________________

Page 3: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

I

Index

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

List of FiguresII. ..........................................................VI

List of TablesIII. ......................................................... VII

AbbreviationsIV. ......................................................VIII

ApplicationV. ............................................................. 134

BibliographyVI. ......................................................... 138

Self Assessment AnswersVII. ................................... 140

Book at a Glance

Page 4: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

II

Contents

Chapter I ....................................................................................................................................................... 1Object Oriented Programming with Java ................................................................................................. 1Aim ................................................................................................................................................................ 1Objectives ...................................................................................................................................................... 1Learning outcome .......................................................................................................................................... 11.1 Introduction to OOP ................................................................................................................................. 21.2 Object Oriented Programming Concepts ................................................................................................. 31.3 Object Oriented Programming ................................................................................................................. 51.4 Programming Paradigm ........................................................................................................................... 51.5 Functional Programming ......................................................................................................................... 61.6 Logic Programming ................................................................................................................................. 71.7 Object Orientation as a New Paradigm: The Big Picture ........................................................................ 71.8 Messages and Responsibilities ................................................................................................................. 81.9 Classes and Instances ............................................................................................................................... 81.10 Objects and Classes ................................................................................................................................ 91.11 Encapsulation ......................................................................................................................................... 9 1.11.1 Messages .............................................................................................................................. 10 1.11.2 Classes .................................................................................................................................. 101.12 Types .................................................................................................................................................... 12Summary ..................................................................................................................................................... 14References ................................................................................................................................................... 14Recommended Reading ............................................................................................................................. 14Self Assessment ........................................................................................................................................... 15

Chapter II ................................................................................................................................................... 17Classes, Objects and Methods ................................................................................................................... 17Aim .............................................................................................................................................................. 17Objectives .................................................................................................................................................... 17Learning outcome ........................................................................................................................................ 172.1 Introduction ............................................................................................................................................ 182.2 Defining a Class ..................................................................................................................................... 182.3 Fields Declaration .................................................................................................................................. 182.4 Methods Declaration .............................................................................................................................. 192.5 Creating Objects ..................................................................................................................................... 212.6 Accessing Class Members ...................................................................................................................... 222.7 Constructors ........................................................................................................................................... 24Summary ..................................................................................................................................................... 26References ................................................................................................................................................... 26Recommended Reading ............................................................................................................................. 26Self Assessment ........................................................................................................................................... 27

Chapter III .................................................................................................................................................. 29Inheritance .................................................................................................................................................. 29Aim .............................................................................................................................................................. 29Objectives .................................................................................................................................................... 29Learning outcome ........................................................................................................................................ 293.1 Introduction to Inheritance ..................................................................................................................... 30 3.1.1 Example of Inheritance .......................................................................................................... 30 3.1.2 Derivation Syntax .................................................................................................................. 31 3.1.3 Effects of Inheritance ............................................................................................................. 313.2 Protected Access .................................................................................................................................... 313.3 Overriding Methods ............................................................................................................................... 32 3.3.1 Dynamic Method Dispatching ............................................................................................... 33

Page 5: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

III

3.3.2 The Super Keyword ............................................................................................................... 33 3.3.3 Final Methods and Final Classes ........................................................................................... 333.4 Constructor Chaining ............................................................................................................................. 343.5 Inheritance and Finalization ................................................................................................................... 353.6 Abstract Classes ..................................................................................................................................... 363.7 Interfaces ................................................................................................................................................ 36 3.7.1 The Implements Declaration .................................................................................................. 373.8 Casting between Class Types ................................................................................................................. 37Summary ..................................................................................................................................................... 38References ................................................................................................................................................... 38Recommended Reading ............................................................................................................................. 38Self Assessment ........................................................................................................................................... 39

Chapter IV .................................................................................................................................................. 41Polymorphism ............................................................................................................................................ 41Aim .............................................................................................................................................................. 41Objectives .................................................................................................................................................... 41Learning outcome ........................................................................................................................................ 414.1 Introduction to Polymorphism ............................................................................................................... 424.2 Upcasting Revisited ............................................................................................................................... 424.3 Forgetting the Object Type..................................................................................................................... 434.4 Method Calling Binding ........................................................................................................................ 444.5 Producing the Right Behaviour .............................................................................................................. 454.6 Extensibility ........................................................................................................................................... 474.7 Overriding vs Overloading .................................................................................................................... 504.8 Abstract Classes and Methods ............................................................................................................... 514.9 Constructors and Polymorphism ............................................................................................................ 53 4.9.1 Order of Constructor Calls ..................................................................................................... 54Summary ..................................................................................................................................................... 56References ................................................................................................................................................... 56Recommended Reading ............................................................................................................................. 56Self Assessment ........................................................................................................................................... 57

Chapter V .................................................................................................................................................... 59Exception Handling ................................................................................................................................... 59Aim .............................................................................................................................................................. 59Objectives .................................................................................................................................................... 59Learning outcome ........................................................................................................................................ 595.1 Introduction to Exception Handling ....................................................................................................... 60 5.1.1 Dealing with Errors ................................................................................................................ 605.2 The Classification of Exceptions ........................................................................................................... 605.3 Advertising the Exceptions that a Method Throws ................................................................................ 615.4 How to Throw an Exception .................................................................................................................. 635.5 Creating Exception Classes .................................................................................................................... 645.6 Catching Exceptions .............................................................................................................................. 645.7 Catching Multiple Exceptions ................................................................................................................ 665.8 Rethrowing Exceptions .......................................................................................................................... 67Summary ..................................................................................................................................................... 69References ................................................................................................................................................... 69Recommended Reading ............................................................................................................................. 69Self Assessment ........................................................................................................................................... 70

Page 6: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

IV

Chapter VI .................................................................................................................................................. 72Object Oriented Programming ................................................................................................................. 72Aim .............................................................................................................................................................. 72Objectives .................................................................................................................................................... 72Learning outcome ........................................................................................................................................ 726.1 Introduction to OOP ............................................................................................................................... 73 6.1.1 Class ...................................................................................................................................... 73 6.1.2 Object ..................................................................................................................................... 73 6.1.3 Method ................................................................................................................................... 746.2 Basic Concepts of Object Oriented Programming ................................................................................. 74 6.2.1 Objects ................................................................................................................................... 74 6.2.2 Classes ................................................................................................................................... 75 6.2.3 Data Abstraction and Encapsulation ...................................................................................... 75 6.2.4 Inheritance ............................................................................................................................. 75 6.2.5 Polymorphism ........................................................................................................................ 76 6.2.6 Dynamic Binding ................................................................................................................... 77 6.2.7 Message Passing .................................................................................................................... 776.3 Paradigms of Programming Languages ................................................................................................. 77 6.3.1 Imperative Paradigms ............................................................................................................ 78 6.3.2 Declarative Paradigm ............................................................................................................. 786.4 Programming .......................................................................................................................................... 79 6.4.1 Procedural Programming ....................................................................................................... 79 6.4.2 Modular Programming ........................................................................................................... 79 6.4.3 Data Abstraction .................................................................................................................... 80 6.4.4 Object Oriented Programming ............................................................................................... 806.5 Objects .................................................................................................................................................. 81 6.5.1 Object: The Soul of Object Oriented Programming .............................................................. 81 6.5.2 The Object Orientation .......................................................................................................... 816.6 Classes.................................................................................................................................................... 82 6.6.1 A Complete View of a Class .................................................................................................. 83 6.6.2 Scope Operator ...................................................................................................................... 85 6.6.3 Scope of Class and its Members ............................................................................................ 866.7 Object Oriented Programming ............................................................................................................... 886.8 Object Oriented Programming Characteristics ...................................................................................... 906.9 Advantages of Object Oriented Programming ....................................................................................... 91Summary ..................................................................................................................................................... 92References ................................................................................................................................................... 92Recommended Reading ............................................................................................................................. 92Self Assessment ........................................................................................................................................... 93

Chapter VII ................................................................................................................................................ 95Classes and Objects.................................................................................................................................... 95Aim .............................................................................................................................................................. 95Objectives .................................................................................................................................................... 95Learning outcome ........................................................................................................................................ 957.1 Introduction to Classes ........................................................................................................................... 967.2 Specifying a Class .................................................................................................................................. 977.3 Creating Objects ..................................................................................................................................... 987.4 Defining Member Functions .................................................................................................................. 987.5 Static Data Members .............................................................................................................................. 997.6 Static Member Functions ..................................................................................................................... 100 7.6.1 Const Member Functions ..................................................................................................... 1017.7 Pointer to Members .............................................................................................................................. 1017.8 Constructor ........................................................................................................................................... 101 7.8.1 Copy Constructor ................................................................................................................. 102

Page 7: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

V

7.9 Destructors ........................................................................................................................................... 103Summary ................................................................................................................................................... 105References ................................................................................................................................................. 105Recommended Reading ........................................................................................................................... 105Self Assessment ......................................................................................................................................... 106

Chapter VIII ............................................................................................................................................. 108Operator Overloading ............................................................................................................................. 108Aim ............................................................................................................................................................ 108Objectives .................................................................................................................................................. 108Learning outcome ...................................................................................................................................... 1088.1 Introduction to Operator Overloading ................................................................................................. 1098.2 How to Overload Operators ................................................................................................................. 1098.3 Overloading Unary Operators ...............................................................................................................1108.4 Overloading Binary Operators ..............................................................................................................1118.5 Rules for Overloading Operators ..........................................................................................................1138.6 Types Conversions ................................................................................................................................113Summary ....................................................................................................................................................117References ..................................................................................................................................................117Recommended Reading ............................................................................................................................117Self Assessment ..........................................................................................................................................118

Chapter IX ................................................................................................................................................ 120Inheritance, Multiple Inheritance and Polymorphism ......................................................................... 120Aim ............................................................................................................................................................ 120Objectives .................................................................................................................................................. 120Learning outcome ...................................................................................................................................... 1209.1 Introduction to Inheritance ................................................................................................................... 1219.2 Defining Derived Classes .................................................................................................................... 1219.3 Single Inheritance ................................................................................................................................ 1219.4 Multiple Inheritances ........................................................................................................................... 1269.5 Polymorphism ...................................................................................................................................... 129Summary ................................................................................................................................................... 131References ................................................................................................................................................. 131Recommended Reading ........................................................................................................................... 131Self Assessment ......................................................................................................................................... 132

Page 8: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

VI

List of Figures

Fig. 1.1 Inheritance ....................................................................................................................................... 4Fig. 1.2 Objects .............................................................................................................................................. 9Fig. 1.3 Messages ......................................................................................................................................... 10Fig. 2.1 Creating object references ............................................................................................................. 21Fig. 2.2 Assigning one object reference variable to another ........................................................................ 22Fig. 3.1 Accessibility in an inheritance relationship .................................................................................... 32Fig. 3.2 Constructor chaining ....................................................................................................................... 35Fig. 3.3 The relationship between an abstract class and its derived classes ................................................ 36Fig. 4.1 Inheritance diagram ........................................................................................................................ 45Fig. 4.2 Addition of methods and classes to the instrument ........................................................................ 48Fig. 4.3 Instrument class into abstract class ................................................................................................. 52Fig. 5.1 Exception hierarchy in Java ............................................................................................................ 60Fig. 6.1 Property inheritance ........................................................................................................................ 76Fig. 6.2 Polymorphism ................................................................................................................................. 76Fig. 6.3 Message passing ............................................................................................................................. 77Fig. 6.4 Language paradigm ........................................................................................................................ 78Fig. 6.5 Programming paradigms ................................................................................................................. 80Fig. 6.6 Objects and interfaces ..................................................................................................................... 81Fig. 6.7 Communication between objects .................................................................................................... 83Fig. 6.8 An object ......................................................................................................................................... 90Fig. 7.1 Representation of a class ................................................................................................................ 96Fig. 9.1 Adding more members to a class (by public derivation) .............................................................. 123Fig. 9.2 Adding more members to a class (by private derivation) ............................................................. 125Fig. 9.3 Multiple inheritance ...................................................................................................................... 126Fig. 9.4 Polymorphism ............................................................................................................................... 130

Page 9: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

VII

List of Tables

Table 3.1 Access to class A’s members ........................................................................................................ 32Table 6.1 Procedural and object oriented paradigms ................................................................................... 78Table 6.2 Functional and logical paradigms ................................................................................................ 79Table 8.1 Operators that cannot be overloaded ...........................................................................................113Table 8.2 where a friend cannot be used .....................................................................................................113

Page 10: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

VIII

Abbreviations

ADT - Abstract Data TypesAPI - Application Programming InterfaceI/O - Input/outputOOP - Object Oriented ProgrammingProlog - Programming in LogicURL - Universal Resource Locator

Page 11: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

1

Chapter I

Object Oriented Programming with Java

Aim

The aim of this chapter is to:

introduce the concept of OOP•

explain the theory of inheritance in Java •

elaborate the concept of abstraction •

explain polymorphism in Java•

Objectives

The objectives of this chapter are to:

get an overview of encapsulation used in Java•

explainthesignificanceofeventsinJava•

discuss programming paradigms in Java•

discuss functional programming•

Learning outcome

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

understand the messages and responsibilities of Java •

describe objects and classes in Java •

evaluate various types of the Java•

Page 12: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

2

1.1 Introduction to OOPObject Oriented Programming, also known as OOP, is a computer science term which is used to describe a computer application that is 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 theobjectsarenotdependentoneachother,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,itcanalsobeanalyzedandmaintainedwithoutalargeamountofdifficulty.However, there are some people who feel that OOP is more complicated than older programming methods.

To understand object oriented programming, there are a few concepts we need to become familiar with. A. The first concept that we need to learn is called a “class”

Aclasscreatestheattributesofathing,anditwillalsodefinetheprocessesthatthethingcancarryout.For•example, a class called “cats” will have the attributes which are commonly found with cats, such as the ability to purr.A class will bring about modularity within the objected oriented computer application. Someone who is not a •programmershouldbeabletofindaclassThe reason for this is because the attributes of the class should be something that will make sense to them.•It is also important for the code of a class to be self contained to a certain degree.•

When code is written with relevant names, it will be easier to understand. Making sure the code is self-contained will allow one part of the application to be updated without needing to change the other parts. It is this modularity that makes OOP an effective programming method. It will also help the application solve the problems that it was designed for.

B. The next concept that we need to be familiar with is an “object” Anobjectcanbedefinedasaspecificinstanceofaclass.•As an example, while the class Cats will provide all the attributes that are found in all cats, the “object” named •Betsyisaspecificcat.While it shares the same attributes which are found in all cats, it has fur with a unique colour.•In object oriented programming, a programmer would say that the object Betsy is a run-time instance of the •class Cats.

Aclassmayalsobedividedintosub-groups.Certainvariationsofaclassmaynotbeaspecificobject.TheclassCatsmay have a sub-group which consists of multiple cat breeds. For example, if Betsy were a Persian cat, it would be an instance of the Persian cat sub-group. some attributes with the parent class, but it will also have unique attributes as well. Every object within an OOP language will share.

C. The next concept that we want to be familiar with is “method” Amethodmayalsobecalleda“message”andcanbedefinedastheabilitiesofanobject.•Because Betsy is a cat, Betsy can purr. Because of this, “purr” is a method that Betsy has.•Betsy may have a number of other methods. •When a method is used within an object oriented programming language, it will only affect a single object. This •is true even if the method is designed for the entire class.

Page 13: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

3

While all cats can purr, we will need only one cat to do it. •Methods can further be broken down into commands, call-backs, or queries. •A query will tell us about the state of the object, and a command will cause that object to carry out a task. •

A call-back is a method that is composed of a part within an object. The part will notify its parent that an event has taken place, and the object may need to react to the eve

1.2 Object Oriented Programming ConceptsThree 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. They 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.Asthenameimplies,apropertyisaspecificattributewhichisconnectedtoanobject.•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 colour.In contrast, another cat breed may choose a different Colorfur trait. •It is also possible for the sub-group to add new associates. •IfaspecificcatClasssub-groupwantstosetadefaulteyecolour,thiscanbeinheritedaswell.•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.•Inheritancedefinesrelationshipsamongclassesinanobject-orientedlanguage.•In the Java programming language, 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, •which is every class in the Java API libraries.Java.lang.Objectdefinesthecoresetofbehavioursthatallclasseshaveincommon.•Aswemovedownthehierarchy,eachclassaddsitsownsetofclass-specificfieldsandmethodstowhatit•inherits from its superclass or superclasses.Thejava.awt.swing.JFrameclassinheritsfieldsandmethodsfromjava.awt.Frame,whichinheritsfields,and•methodsfromjava.awt.Container,whichinheritsfieldsandmethodsfromjava.awt.Component,whichfinallyinheritsfromjava.lang.Object,andeachsubclassaddsitsownfieldsandmethodsasneeded.

Page 14: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

4

Java.lang.Objectclone()equals()finalize()getClass()hashCode()notify()notifyAll()Object()toString()wait()wait(long timeout)wait(long timeout, int nanos)

java.lang.String

java.awt.event.WindowAdapter

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.util.EventObject

Fig. 1.1 Inheritance

AbstractionAbstractioncanbedefinedastheprocessinwhichanapplicationwillignorethecharacteristicsofasub-group•and work 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.

PolymorphismPolymorphismcanbedefinedasabehaviourwhichisdependentontheclasstowhichitisconnected.•As an example, 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.

Page 15: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

5

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 categorized as being protected, public, or private.•

EventAneventcansimplybedefinedasanythingthathappenstoanobject.•Generally, an event is something that will cause 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 •programmingcommunityaboutwhetheritisbeneficialorrisky.One example of a program which deals with multiple inheritances is 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.

1.3 Object Oriented ProgrammingObject-orientation is a set of tools and methods that enable software engineers to build reliable, user friendly, and maintainable,welldocumented,reusablesoftwaresystemsthatfulfilstherequirementsofitsusers.Itisclaimedthatobject-orientation provides software developers with new mind tools to use in solving a wide variety of problems. Object-orientation provides a new view of computation.

A software system is seen as a community of objects that cooperate with each other by passing messages in solving a problem. An object-oriented programming language provides support for the following object-oriented concepts:

Objects and Classes•Inheritance•Polymorphism •Dynamic binding•

1.4 Programming ParadigmObject-oriented programming is one of several programming paradigms. Other programming paradigms include theimperativeprogrammingparadigm(asexemplifiedbylanguagessuchasPascalorC),thelogicprogrammingparadigm(Prolog),andthefunctionalprogrammingparadigm(exemplifiedbylanguagessuchasML,HaskellorLisp).

Logic and functional languages are said to be declarative languages. We use the word paradigm to mean “any example or model”. This usage of the word was popularised by the science historian Thomas Kuhn. He used the term to describe a set of theories, standards and methods that together represent a way of organising knowledge a way of viewing the world. Thus a programming paradigm is a

Page 16: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

6

. . . Way of conceptualising what it means to perform computation and how tasks to be carried out on a computer should be structured and organised.

We can distinguish between two types of programming languages: Imperative languages•Declarative languages•

Imperative language Declarative language

Imperative knowledge describes how-to knowledge•Traditional imperative programming languages •such as FORTRAN, and C, which require the programmer to specify an algorithm to be runImperative programs make the algorithm explicit •and leave the goal implicitImperative languages requires to write down a step-•by-step recipe specifying how something is to be done

Declarative knowledge is what-is •knowledgeDeclarative program describes •what something is like, rather than how to create itDeclarative programs make •the goal explicit and leave the algorithm implicit

For example: to calculate the factorial function in an imperative language we would write something like

public int factorial(int n) {int ans=1;for (int i = 2; i <= n; i++){ans = ans * i;{return ans;{

Given above is a procedure (a set of steps) when followed will produce the answer.

1.5 Functional ProgrammingFunctional programming is a programming paradigm that treats computation as the evaluation of mathematical functions.Functionalprogrammingemphasizesthedefinitionoffunctions,incontrasttoproceduralprogramming,which emphasizes the execution of sequential commands.

The following is the factorial function written in a functional language called Lisp:

(defun factorial (n)(if (<= n 1) 1 (* n (factorial (- n 1)))))

Itdefinesthefactorialfunctionratherthangivethestepstocalculateit.Thefactorialofnisdefinedas1ifn<=1else it is n ∗factorial(n−1)

Page 17: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

7

1.6 Logic ProgrammingProlog (PROgramming in LOGic) is the most widely available language in the logic programming paradigm. It is based on the mathematical ideas of relations and logical inference.

Prolog is a declarative language meaning that rather than describing how to compute a solution, a program consists of a data base of facts and logical relationships (rules) which describe the relationships which hold for the given application. Rather then running a program to obtain a solution, the user asks a question. When asked a question, the run time system searches through the data base of facts and rules to determine (by logical deduction) the answer.Logic programming was an attempt to make a programming language that enabled the expression of logic instead ofcarefullyspecifiedinstructionsonthecomputer.InthelogicprogramminglanguagePrologsuppliesadatabaseof facts and rules; we can then perform queries on the database. This is also an example of a declarative style of programmingwherewestateordefinewhatweknow.

In the following example, we declare facts about a domain. We can then query these facts we can ask, for example, are sally and tom siblings?

sibling(X,Y) :– parent(Z,X), parent(Z,Y).parent(X,Y) :– father(X,Y).parent(X,Y) :– mother(X,Y).mother(trude, sally).father(tom, sally).father(tom, erica).father(mike, tom).

The factorial function is written in prolog as two rules. Again, notice the declarative nature of the program

fac(0,1).fac(N,F) :– N > 0.M is N – 1,fac(M, Fm),F is N * Fm.

1.7 Object Orientation as a New Paradigm: The Big PictureIt is claimed that the problem-solving techniques used in object-oriented programming more closely models the way humans solve day-to-day problems. So let’s consider how we solve an everyday problem:

For example:SupposewewanttosendflowerstoafriendnamedRobinwholivesinanothercity.Tosolvethisproblem,wewillsimplywalktoournearestfloristrunby,let’ssay,Fred.WewilltellFredthekindsofflowerstobesentandtheaddresstowhichtheyshouldbedelivered.Wewillbeassuredthattheflowerswillbedelivered.

Now, let’s examine the mechanisms used to solve our problem. Wefirst found an appropriate agent (Fred, in this case) and passed amessage to this agent containing a•request.It is the responsibility of Fred to satisfy the request.•There is a method (an algorithm or set of operations) used by Fred to do this.•We need not know the particular methods used to satisfy the request such, information are hidden from view.•Wewanttoknowthedetails,butoninvestigationwemayfindthatFreddeliveredaslightlydifferentmessage•toanotherfloristinthecitywhereRobinlives.Thatfloristthenpassesanothermessagetoasubordinatewhomakesthefloralarrangement.Theflowers,alongwithyetanothermessage,arepassedontoadeliverypersonandsoon.Thefloristsalsohave•interactionswithwholesalerswho,inturn,hadinteractionswithflowergrowersandsoon.

Page 18: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

8

Thisleadstoourfirstconceptualpictureofobject-orientedprogramming:Anobject-orientedprogramisstructuredas community of interacting agents called objects. Each object has a role to play. Each object provides a service or performs an action that is used by other members of the community.

1.8 Messages and ResponsibilitiesMembers of an object-oriented community make requests to each other. The next important principle explains the use of messages to initiate action.

Action is initiated in object-oriented programming by the transmission of a message to an agent (an object) responsible for the actions. The message encodes the request for an action and is accompanied by any additional information (arguments/ parameters) needed to carry out the request. The receiver is the object to whom the message is sent. If the receiver accepts the message, it accepts responsibility to carry out the indicated action. In response to a message, the receiver will perform some method to satisfy the request.

There are some important issues pointed below:The client sending the request need not know the means by which the request is carried out. In this we see the •principle of information hiding.Anotherprincipleimplicitinmessagepassingistheideaoffindingsomeoneelsetodothework,i.e.,reusing•components that may have been written by someone else. The interpretation of the message is determined by the receiver and can vary with different receivers. For example,ifwesentthemessage“deliverflowers”toafriend,shewillprobablyhaveunderstoodwhatwasrequiredandflowerswouldstillhavebeendeliveredbutthemethodsheusedwouldhavebeenverydifferentfromthatusedbytheflorist.In object-oriented programming, behaviour is described in terms of responsibilities. •Client’s requests for actions only indicate the desired outcome. The receivers are free to pursue any technique •that achieves the desired outcomes.Thinking in this way allows greater independence between objects. •Thus,objectshaveresponsibilitiesthattheyarewillingtofulfillonrequest.•The collection of responsibilities associated with an object is often called a protocol.•

1.9 Classes and InstancesAll objects are instances of a class. The method invoked by an object in response to a message is determined by the class of the receiver. All objects of a given class use the same method in response to similar messages.

Fredisaninstanceofacategoryorclassofpeople,i.e.,Fredisaninstanceofaclassofflorists.•Thetermfloristrepresentsaclassorcategoryofallflorists.•Fred is an object or instance of a class. •We interact with instances of a class but the class determines the behaviour of instances.•We can tell a lot about how Fred will behave by understanding how Florists behave.•Weknow,forexample,thatFred,likeallfloristscanarrangeanddeliverflowers.•

Real-world objects share two characteristics. They all have state and behaviour.

For example, dogs have state (name, colour, breed, and hungry) and behaviour (barking, fetching, wagging tail). Students have state (name, student number, courses they are registered for, gender) and behaviour (takes tests, attend courses, write tests, party).

Page 19: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

9

Methods(behavior)

Variables(state)

Fig. 1.2 Objects

Fundamentals of objects and classesWe move now from the conceptual picture of objects and classes to a discussion of software classes and objects.

Objects are closely related to classes. •A class can contain variables and methods. •

1.10 Objects and ClassesObjectsIn object-oriented programming we create software objects that model real world objects. Software objects are modelled after real-world objects in that they too have state and behaviour. A software object maintains its state inoneormorevariables.Avariableisanitemofdatanamedbyanidentifier.Asoftwareobjectimplementsitsbehaviour with methods. A method is a function associated with an object.

Definition: An object is a software bundle of variables and related methods.An object is also known as an instance. •An instance refers to a particular object. • For example, Karuna’s bicycle is an instance of a bicycle it refers to a particular bicycle.Sandile Zuma is an instance of a Student. •The variables of an object are formally known as instance variables because they contain the state for a particular •object or instance.In a running program, there may be many instances of an object. • For example, there may be many Student objects.Each of these objects will have their own instance variables and each object may have different values stored in •their instance variables. For example, each Student object will have a different number stored in its StudentNumber variable.

1.11 EncapsulationObject diagrams show that an object’s variables make up the center, or nucleus, of the object. Methods surround and hide the object’s nucleus from other objects in the program. Packaging an object’s variables within the protective custody of its methods is called encapsulation.

Page 20: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

10

Message

Object B

Object A

Fig. 1.3 Messages

Encapsulating related variables and methods into a neat software bundle is a simple yet powerful idea that provides twobenefitstosoftwaredevelopers:

ModularityThe source code for an object can be written and maintained independently of the source code for other objects. Also, an object can be easily passed around in the system. We can give our bicycle to someone else, and it will still work.

Information-hidingAn object has a public interface that other objects can use to communicate with it. The object can maintain private information and methods that can be changed at any time without affecting other objects that depend on it.

1.11.1 MessagesSoftware objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of B’s methods, object A sends a message to object B.

For example: The three parts for the message System.out.println {‘‘Hello World’’}; are:The object to which the message is addressed (System.out)•The name of the method to perform (println)•Any parameters needed by the method (“Hello World!”)•

1.11.2 ClassesIn object-oriented software, it’s possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips and so on.

A class is a software blueprint for objects. A class is used to manufacture or create objects. The class declares the instance variables necessary to contain the state of every object. The class would also declare and provide implementations for the instance methods necessary to operate on the state of the object.

Definition: Aclassisablueprintthatdefines“thevariablesandthemethodscommontoallobjectsofacertainkind”.

Page 21: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

11

After we create the class, we can create any number of objects from that class. A class is a kind of factory for constructing objects. The non-static parts of the class specify, or describe, what variables and methods the objects will contain.

This is a part of the explanation of how objects differ from classes: Objects are created and destroyed as the program runs, and there can be many objects with the same structure, if they are created using the same class.

Aclassisastructurethatdefinesthedataandthemethodstoworkonthatdata.

When we write programs in the Java language, all program data is wrapped in a class, whether it is a class we write or a class we use from the Java platform API libraries.

TheExampleProgramclassfromthesimpleprograminthefirstlessonofPart1isaprogrammer-writtenclassthatusesthe java.lang.System class from the Java platform API libraries to print a character string to the command line.

class ExampleProgram {public static void main(String[] args) { System.out.println(“I’m a simple Program”);}}

ClassesintheJavaplatformAPIlibrariesdefineasetofobjectsthatshareacommonstructureandbehaviour.

Thejava.lang.Systemclassusedintheexampledefinessuchthingsasstandardinput,output,anderrorstreams,andaccesstosystemproperties.Incontrast,thejava.lang.Stringclassdefinescharacter strings.

In the example, we do not see an explicit use of the String class, but in the Java language, a character string can be used anywhere a method expects to receive a String object.

During execution, the Java platform creates a String object from the character string passed to the System.out.println call, but our program cannot call any of the String class methods because it did not instantiate the String object. If we want access to the String methods, we can rewrite the example program to create a String object as follows.

This way, we can call a method such as the String.concat method that adds text to the original string as shown below:

class ExampleProgram { public static void main(String[] args) { String text = new String(“I’m a simple Program “); System.out.ptringln(text); String text2 = text.concat( “that uses classes and objects”); System.out.println(text2); }}

The output looks like this:I’m a simple ProgramI’m a simple Program that uses classes and objects

Page 22: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

12

1.12 TypesJava,likemostprogramminglanguagesclassifiesvaluesandexpressionsintotypes.Forexample,String’sandint’sare types.

Atypebasicallyspecifiestheallowedvaluesandallowedoperationsonvaluesofthattype.

Definition: 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 •memoryaddresses,instructioncode,characters,integersandfloating-pointnumbers.Types inform programs and programmers how they should treat those bits. •

For example,theintegersareatypewithvaluesintherange−2,147,483,648to+2,147,483,647andvariousallowed operations that include addition, subtraction, modulus etc.

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

A. 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.

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

C. 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.

D. 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 we 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. The primitive types can be used in various combinations to create other, composite types.

Everytimewedefineaclass,weareactuallydefininganewtype.Forexample,theStudentclassdefinedaboveintroduces a new type.

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 fore.g.intx=8declaresxtobeoftypeint.Allobjectsthatwedeclarealsohavetobeofaspecifiedtypethetypeof an object is the class from which it is created.

Page 23: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

13

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 a newobjectofthespecifiedtypeandrunstheStudentconstructor.

The constructor’s job is to properly initialise the 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 we do not specify initial values, the compiler automatically assigns one: Instance variables of numerical type (int, double, etc.) are automatically initialized to zero; Boolean variables are initialized to false; and char variables, to the Unicode character with code number zero. The default initial value of object types is null.

Page 24: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

14

SummaryObject Oriented Programming, also known as OOP, is a computer science term which is used to describe a •computer application that is 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. •Three of the most basic concepts for object oriented programmings are Classes, Objects, and Methods. •Inheritance will allow a sub-group to make a connection with the associates of its parent class. For example, •lets say the class Cats decides to create a method called purr() and a property named Colorfur.Asthenameimplies,apropertyisaspecificattributewhichisconnectedtoanobject.•Abstractioncanbedefinedastheprocessinwhichanapplicationwillignorethecharacteristicsofasub-group•and work on a general level when it is needed.Encapsulation will allow a class to hide information from objects that may use the code.•Polymorphismcanbedefinedasabehaviourwhichisdependentontheclasstowhichitisconnected•Aneventcansimplybedefinedasanythingthathappenstoanobject.•A multiple inheritance can create a number of perplexing situations. •Becauseofthis,thereisdebateintheprogrammingcommunityaboutwhetheritisbeneficialorrisky.•Object-orientation is a set of tools and methods that enable software engineers to build reliable, user friendly, •andmaintainable,welldocumented,reusablesoftwaresystemsthatfulfilstherequirementsofitsusers.It is claimed that object-orientation provides software developers with new mind tools to use in solving a wide •variety of problems.An object-oriented programming language provides support for the following object-oriented concepts: objects •and classes, inheritance, polymorphism, and dynamic bindingAlong with the object-oriented programming the other paradigms include the imperative programming paradigm •(asexemplifiedbylanguagessuchasPascalorC),thelogicprogrammingparadigm(Prolog),andthefunctionalprogrammingparadigm(exemplifiedbylanguagessuchasML,HaskellorLisp).

ReferencesC. Thomas Wu, 2009. • An Introduction to Object-Oriented Programming with Java. McGraw-Hill Higher Education.Mulholland, A. and Murphy, G., 2003. • Java 1.4 Game Programming. Wordware Publishing.Wu, T., 2009. • An Into To Oop with Java, 4E. Tata McGraw-Hill.

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

Page 25: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

15

Self AssessmentWhat is the full form of OOP?1.

Object Organisation Processa. Object Orbit Prob. Object Oriented Programmingc. Object Organic Programmed.

With OOP, every object can handle data, get messages, and transfer messages to other _________.2. objectsa. programb. processc. subroutined.

________canbedefinedasaspecificinstanceofaclass.3. Objecta. Programb. Classc. Methodd.

Every object within an__________ language will share some attributes with parent class, but it will also have 4. unique attributes as well.

C++a. OOPb. Cc. Javad.

A method may also be called a “__________”.5. codea. memob. communicationc. messaged.

A____________ is a method that is composed of a part within an object.6. call-backa. call-rearb. call inc. send outd.

Three of the most basic concepts for ________ are classes, objects, and methods.7. codinga. programmingb. object oriented programming’sc. javad.

Page 26: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

16

Object-oriented concept that helps objects work together is____________.8. inheritancea. heritageb. enhancementc. hashingd.

Inheritancedefinesrelationshipsamong______________inanobject-orientedlanguage.9. diagramsa. methodsb. classesc. object’sd.

_______________canbedefinedastheprocessinwhichanapplicationwillignorethecharacteristicsofa10. sub-group and work on a general level when it is needed.

Inheritancea. Methodsb. Classesc. Abstractiond.

Page 27: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

17

Chapter II

Classes, Objects and Methods

Aim

The aim of this chapter is to:

introduce the concept of class objects, class and methods•

explainfielddeclaration•

elaborate the concept of class•

Objectives

The objectives of this chapter are to:

introduce methods declaration•

explain the method of creating objects•

discuss how to create object references•

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•

access the class members•

Page 28: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

18

2.1 IntroductionJava is a true object oriented language and therefore, the underlying structure of all Java programs is classes. Anything wewishtorepresentinaJavaprogrammustbeencapsulatedinaclassthatdefinesthestate and behaviour of the basic 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 functions that work on them. In Java, the data items are called are called fields and the functions are called methods. Calling a specificmethodinanobjectisdescribedassendingtheobjectamessage.

Aclassisessentiallyadescriptionofhowtomakeanobjectthatcontainsfieldsandmethods.Itprovidesasortoftemplate for an object and behaves like a basic data type int.ItisthereforeimportanttounderstandhowthefieldsandmethodsaredefinedinaclassandhowtheyareusedtobuildJavaprogramthatincorporatesthebasicOOPconcepts such as encapsulation, inheritance and polymorphism.

2.2 Defining a ClassAclassisauser-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.

2.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 29: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

19

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.

2.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.

Examples:(int m. float x. float y) // Three parameters( ) // 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;int width;void getData (int x, int y) // Method declaration{ length = x; width = y; }

}

Page 30: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

20

Note that the method has a return type of void because it does not return nay value. We pass two integer values to the method 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. Also note that the parameter list is empty.

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 31: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

21

For example:class Access{

int x;void method1 ( ){

int y ;x = 10; // legaly = x; // legal

}Void method 2 ( ){

Int z;X = 5 // legalZ = 10 ; // legal Y = 1 ; // illegal

}}

2.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.

Objects in Java are created using the new operator. The newoperatorcreatesanobjectofthespecifiedclassandreturns a reference to that object. Here is an example of creating an object of type Rectangle.

Rectangle rect1; // declare the objectrect1 = new Rectangle ( ); // 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. 2.1 Creating object references

Both statements can be combined into one as shown below:Rectangle rect1 = new Rectangle ( );The method Rectangle ( ) is the default constructor of the class. We can create any number of objects of Rectangle. Example:Rectangle rect1 = new Rectangle ( );Rectangle rect2 = new Rectangle ( );and so on.

Page 32: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

22

It is important to understand that each object has a 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.

Rectangle R1 = new Rectangle (); Rectangle R2 = R1;

R1

Rectangle Object

R1

Fig. 2.2 Assigning one object reference variable to another

Both, R1 and R2 refer to the same object.

2.6 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;

Note that the two objects rect1 and rect2 store different values as shown below: rec1 rec2rect1.length 15 rect2.length 20rect1.width 10 rect2.width 12

Page 33: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

23

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:

void getData (int x, 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

Program 2.1 below illustrates the concepts discussed above.

Program 2.1 Application of classes and objects

Page 34: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

24

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 2.1 would output the followingArea1 = 150Area2 = 240

2.7 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 initialize all the variables of all the objects.

The second approach takes the help of a method like getData to initialize 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 initialize 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 35: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

25

class Rectangle{

int length;int width;Rectangle (int x , int y) // Constructor method{

length = x;width = y;

}int rectArea ( ){

return (length*width);}

}

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

Program 2.2 Application of constructors

class Rectangle{

int length, width;Rectangle(intx,inty) //Definingconstructor{

length = x;width = y;

}int rectArea ( ){

return (length * width);}

}class RectangleArea{

public static void main (string args[ ] ){ Rectangle rect1 = new Rectangle (15, 10); // Calling constructor

int area1 = rect1.Area ( ); System.out.println (“Area1 = “+ area1); }}

Output of program 2.2:Area1 = 150

Page 36: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

26

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.

ReferencesClasses and Objects in Java• , [online]. Available at: <http://www.google.co.in/url?sa=t&source=web&cd=2&ved=0CCIQFjAB&url=http%3A%2F%2Fwww.buyya.com%2F254%2FLectures%2FRajLec7.ppt&rct=j&q=classes%20and%20objects%20in%20java&ei=TsarTfeHL4n0vQPw5PT_CQ&usg=AFQjCNEtrpUizb_l_kpICBPLDaklD23Rfw&sig2=R9TRHATEAa2rWQ29N3a6vg&cad=rja>. [Accessed 8 April 2011]Classes and Objects in Java• , [online]. Available at: <http://docstore.mik.ua/orelly/java/javanut/ch03_01.htm>. [Accessed 8 April 2011]Javabeginner.com, 2008, • Java Classes and Objects, [online]. Available at: < http://www.javabeginner.com/learn-java/java-classes-and-objects>. [Accessed 8 April 2011]

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

Page 37: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

27

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 themClasses 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 statement is true?7. Aclassisauser-definedobjecttypewithatemplatethatservestodefineitspropertiesa. 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 objectc. It is important to understand that each object has a its own copy of the instance variables of its objectd.

Page 38: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

28

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 39: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

29

Chapter III

Inheritance

Aim

The aim of this chapter is to:

introduce the concept of inheritance•

explain the effects of inheritance•

identify the overriding methods•

Objectives

The objectives of this chapter are to:

introduce protected access•

explain the dynamic method dispatching•

discuss the concept of interfaces•

derive the syntax of inheritance•

Learning outcome

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

understand the concept of super keyword and constructor chaining•

describe abstract classes•

access the casting between class type•

identifythefinalmethodsandfinalclasses•

Page 40: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

30

3.1 Introduction to InheritanceInheritance 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, theyalsoidentifyandabstractcommonfeaturesofsimilartypesinasuperclass.Oncethesuperclassisdefined,eachsubclassisdefinedasa“kindof”thesuperclass,sothatitcantheninheritthecommonfeatures.Theprogrammerneed only specify the behaviour 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.

3.1.1 Example of InheritanceAn example of inheritance where a programmer might identify a need for two types of text objects would be CompactText and WordProcText. CompactText emphasises storage efficiency rather than functionality andWordProcText is used for word processing that contains font information. While the differences between the text objectsaresignificantenoughtowarrantimplementingthemasdifferentclasses,thesimilaritiesthatexistbetweenthem suggest the presence of certain shared properties and the possibility of their belonging to one superclass.

Inthiscase,ratherthancreatingtwolargelysimilarclassdefinitions,asuperclasscalledTextObject canbefirstdefined.This establishes a common interface for the two. From this base class, the classes CompactText and WordProcText are derived. Each derived type inherits its interface and implementation from the base type. For example, all of the classes have a length( ) method. The base class might or might not provide a default implementation for this method. If the base class does provide a default implementation, the derived classes can inherit the implementation as their own. A derived class can override or extend the implementation of an inherited method as appropriate. A derived class may not change the interface of a method. CompactText might use the implementation of the length( )methoddefinedinTextObject, while WordProcText might override this implementation with its own.

Perhaps, it is only later that an EncodedText type is needed. If an inheritance relationship exists, then implementing the new type becomes much simpler. Whether or not derived classes are created at the same time as their base class, each of the derived types extends the interface or implementation of the base class.

Establishing a sensible hierarchy of related types is one of the most challenging aspects of object-oriented program design. It is not easy to generalise a base type in a manner that not only abstracts the common behavior of the types already known, but also provides a good basis for the later derivation of new types. An important reward for utilising inheritance is a dramatic increase in code reuse, which can save a programmer time and valuable resources.

Page 41: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

31

3.1.2 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.

3.1.3 Effects of InheritanceIn Java, private methods of the base class are not inherited (the derived class cannot call them anyway), but everything else is inherited.

A derived-type object can be said to have a dual identity. It is a type of both its new class and its parent type. For example, if class Bass is derived from Fish, an object of type Bass is both a Bass and a Fish. However, the reverse is not necessarily true. The programmer, in this case, must force a conversion from base class type to derived class type with an explicit cast:

BaseClass Obj1; /*...*/DerivedClass Obj2=(DerivedClass) Obj1;

3.2 Protected AccessIn addition to public, privateanddefault(package-friendly)memberaccess,therearetwootheraccessspecifiersthat apply 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:

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.

Page 42: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

32

Fig.3.1belowshowstherelationshipbetweenclasseswithdifferentaccessspecifiers.

Fig. 3.1 Accessibility in an inheritance relationship

Access specifier Accessible by classesPublic A, B, C, D, EProtected A, B, C, DDefault A, B, CPrivate protected A, B, Dprivate A

Table 3.1 Access to class A’s members

3.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:

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.

Package Stuff Package Things

Class A

Class C

Class B Class D

Class E

(derived)

Page 43: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

33

3.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.

3.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:

public class WordProcText extends TextObject{ public int length () { int len = 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()

3.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 be too complicated to implement.

Methods labeled final, private, or static are not subject to dynamic lookup because they 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 not-overrideable for reasons of complexity or safety

Page 44: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

34

3.4 Constructor ChainingWhen a derived-type object is instantiated, it is sometimes desirable to have its constructor call a particular overload of its parent class. This is done with what looks like a call to the method super( ). Often this is used to pass a particular variableupintoaparentclass’sconstructor.Thismustbethefirststatementinaconstructor.

If the programmer does not include a super( ) call, the compiler will provide one. The only exception to this occurs when a constructor calls another constructor via the form this( ). In this case, the compiler knows that the firstconstructorwillcallsuper( ).

Constructors do not use dynamic lookup simply because each class has its own constructor.

Consider the following two classes:

public class A{ A(int ix){...} A(floatfx){...}//overloaded}public class B extends A{ B(int ix){...}}

The keyword super can be used to specify which of A’s constructors to call from B’s constructor:

class B extends A {{ B(int ix) { super(ix);// calls A(int ix) }}

This use of super( )islegalonlyasthefirststatementofaconstructor.Ifaconstructorcallsneithersuper( ) nor this( ), the compiler implicitly calls the base class’s no-parameterconstructorasseeninthefigureshownbelow.

Page 45: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

35

Fig. 3.2 Constructor chaining

Onecommonmistakeistodefineaparticularconstructorinaparentclass,andthenderivefromitwithoutcallingsuper( ).Inthiscase,thecompilerwouldcalltheparentclass’sno-parameterconstructor,butwouldnothavedefinedone. This can produce some mystifying error messages.

The appropriate overload must exist in the parent class. Recall that if any constructor is written, the compiler will not provide the default no-parameter version.

The following will produce a compiler error:

class A { int value; A(int input) { value = input; }}class B extends A { int myvalue;}

3.5 Inheritance and FinalizationIf a parent class contains a finalize( ) method, it must be called explicitly by the derived class’s finalize( ) method. Unlike C++, Java destructors are not called automatically. If it is needed, the derived class’s finalize( ) method must call it manually with:

super.finalize();

class A { A () {. . .} A(floatxx){...} } Compiler calls class B extends A A () here } B () { . . . } B(floatfx) {super(fx);...} B (int ix) { this () ; but not here . . . } }

Page 46: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

36

3.6 Abstract Classes

class A { int value; A(int input) { value = input; }}class B extends A { int myvalue;}

Methods declared with the keyword abstractdefineaskeletonforamethodbutdonotimplementit.Thisrequiresa derived class to provide the code for this class. A class with one or more abstract methods must itself be declared abstract and cannot be instantiated. It can only be used for derivation.

C++ programmers will recognise this as a pure virtual function that makes an abstract class. A method can be declared abstract with no brackets to enclose any code.

Fig. 3.3 The relationship between an abstract class and its derived classes

A generic shape cannot exist. Each subtype implements its own area( ) method.

3.7 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 inheritancerequires.Whenaparentclassistobedefinedasabstract,insteadofdefiningoneormoremethodsasabstract,theclasscanbedefinedwiththekeywordinterface instead of class.Thisdefinestheminimumsetofmethods a class must contain.

An interface type is named for derivation with the keyword implements instead of extends. All of its methods are implicitlypublicandabstract.Ifdesired,theycanbedeclaredthatwayforclarity.Also,anydatadefinedinaninterfacemustbeconstant(i.e.,finalstatic).

abstract float area () ;

class Shape

(derived)

Circle Square Triangle

Page 47: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

37

3.7.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 inheritances are 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.

The implementsdeclarationinfig.3.3,seenasawayofderivingfromaninterface, also means that the new class can be treated as being of that new type. Though a class can have only one parent class, it can implement any number of classes, and thus behave as more than one type of object. For example:

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.

3.8 Casting between Class TypesThe Java run-time system keeps track of the type of each object. While this implies some memory space overhead for each object, the programmer can achieve a type-safe run-time environment. The Java language makes some of its run-time typing power available to the programmer through the instanceof operator. The form of an instanceof expression is as follows:

object-expression instanceof class-name

The left-hand term is any expression that evaluates to a class type. The right-hand term is the name of a class or interface. An instanceof expression returns true if the actual type of the object on the left-hand side is of the type named by the right-hand side, and false otherwise. The object is of the named type if it is of exactly the named type orisofatypethatdirectlyorindirectlyextendstheidentifiedtype.

The instanceof operator can be use for safe casting between class types:

if (tobj instanceof CompactText){ CompactText ct = (CompactText) tobj;}

Page 48: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

38

SummaryInheritance 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. An example of inheritance where a programmer might identify a need for two types of text objects would be •CompactText andWordProcText.CompactText emphasises storageefficiency rather than functionality andWordProcText is used for word processing that contains font information.An important reward for utilising inheritance is a dramatic increase in code reuse, which can save a programmer •time and valuable resources.In Java, private methods of the base class are not inherited, but everything else is inherited. •A derived-type object can be said to have a dual identity. It is a type of both its new class and its parent type. •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.Theprocess of a derived class redefining amethod contained in the parent class is called overriding the•method.Methodsdeclaredwiththekeywordabstractdefineaskeletonforamethodbutdonotimplementit.•Interface is a method whereby the properties of one class can be used by another without formal inheritance.•

ReferencesBalaguruswamy, E., 2008. • Programming with Java - A Primer, 3/e. 7th ed., Tata McGraw Hill publishing company limited.Lavender, G., 1999. • Inheritance in Java, [online] Available at:<http://www.cs.utexas.edu/~lavender/courses/tutorial/java-06.pdf>. [Accessed on 11 April 2011]Javabeginner.com, 2008, • Java inheritance, [online]. Available at :< http://www.javabeginner.com/learn-java/java-classes-and-objects>. [Accessed 8 April 2011]

Recommended ReadingHorstmann, C. S. & Cornell, G., 2007. • Core Java(TM), Volume I—Fundamentals. 8th ed., Prentice Hall.Shaw, P., 2010. • Java inheritance FAQ (Code Style FAQ ebook series). 1st ed.,One Percent Better.Waldo, J., 2010. • Java: The Good Parts. 1st ed., O’Reilly Media.

Page 49: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

39

Self AssessmentAny number of classes can be added to an __________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.

Which one of the following is the most challenging aspects of object-oriented program design?3. To use a parent type variable to point to a derived type objecta. To generalise a base type b. Establishing a sensible hierarchy of related typesc. To think predominantly from the bottom up during the design phased.

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

basica. superb. parentc. childd.

Theprocessofaderivedclassredefiningamethodcontainedintheparentclass(withthesameparametertypes)5. is called____________.

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

Which of the following statements is false?6. An interface type is named for derivation with the keyword implements instead of extendsa. A class with one or more abstract methods must itself be declared abstract and can be instantiatedb. The appropriate overload must exist in the parent class. c. Constructors do not use dynamic lookup simply because each class has its own constructor. d.

An important reward for utilizing inheritance is a dramatic ______in code reuse, which can save a programmer 7. time and valuable resources.

decreasea. increaseb. breakthroughc. falld.

Page 50: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

40

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

Which of the following statement is true?9. Methodsdeclaredwiththekeywordabstractdefineaskeletonforamethodandalsoimplementit.a. A class with one or more abstract methods must itself be declared abstract and cannot be instantiatedb. An interface type is named for derivation with the keyword implements instead of declarationc. Though a class can have only two parent class, it can implement any number of classes, and thus behave as d. more than one type of object.

A derived-type object can be said to have a ________identity.10. singlea. multipleb. optionalc. duald.

Page 51: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

41

Chapter IV

Polymorphism

Aim

The aim of this chapter is to:

introduce the concept of polymorphism•

explain the method calling binding•

discuss the order of constructor calls•

Objectives

The objectives of this chapter are to:

explain upcasting•

illustrate the concept of extensibility•

highlight abstract classes and methods•

Learning outcome

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

understand the concept of constructors and polymorphism•

describe the differences between overriding and overloading•

know the program for forgetting the object type•

Page 52: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

42

4.1 Introduction to 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 behaviors. Implementation hiding separates the interface from the implementation by making the details private. This sort of mechanical organization 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’re 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.

4.2 Upcasting RevisitedTaking an object reference and treating it as a reference to its base type is called upcasting, because of the way inheritance trees are drawn with the base class at the top.

Example://: c07:music:Music.java// Inheritance & upcasting.class Note { private int value; private Note(int val) { value = val; } publicstaticfinalNote MIDDLE_C = new Note(0), C_SHARP = new Note(1), B_FLAT = new Note(2);} // Etc.

class Instrument { public void play(Note n) { System.out.println(“Instrument.play()”); }}// Wind objects are instruments// because they have the same interface:class Wind extends Instrument { //Redefineinterfacemethod: public void play(Note n) { System.out.println(“Wind.play()”); }}public class Music { public static void tune(Instrument i) { // ... i.play(Note.MIDDLE_C); }public static void main(String[] args) { Windflute=newWind(); tune(flute);//Upcasting}} ///:~

Page 53: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

43

The method Music.tune( ) accepts an Instrument reference, but also anything derived from Instrument. In main( ), we can see this happening as a Wind reference is passed to tune( ), with no cast necessary. This is acceptable; the interface in Instrument must exist in Wind, because Wind is inherited from Instrument. Upcasting from Wind to Instrument may “narrow” that interface, but it cannot make it anything less than the full interface to Instrument.

4.3 Forgetting the Object TypeThe program above might seem strange. Why should anyone intentionally forget the type of an object? This is what happens when we upcast, and it seems like it could be much more straightforward if tune( ) simply takes a Wind reference as its argument. This brings up an essential point: If we did that, we’d need to write a new tune( ) for every type of Instrument in our system. Suppose we follow this reasoning and add Stringed and Brass instruments:

//: c07:music2:Music2.java// Overloading instead of upcasting.class Note { private int value; private Note(int val) { value = val; } publicstaticfinalNote MIDDLE_C = new Note(0), C_SHARP = new Note(1), B_FLAT = new Note(2);} // Etc.

class Instrument { public void play(Note n) { System.out.println(“Instrument.play()”); }}

class Wind extends Instrument { public void play(Note n) { System.out.println(“Wind.play()”); }}class Stringed extends Instrument { public void play(Note n) { System.out.println(“Stringed.play()”); }}

class Brass extends Instrument { public void play(Note n) { System.out.println(“Brass.play()”); }}

Page 54: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

44

public class Music2 { public static void tune(Wind i) { i.play(Note.MIDDLE_C); } public static void tune(Stringed i) { i.play(Note.MIDDLE_C); } public static void tune(Brass i) { i.play(Note.MIDDLE_C); } public static void main(String[] args) { Windflute=newWind(); Stringed violin = new Stringed(); Brass frenchHorn = new Brass(); tune(flute);//Noupcasting tune(violin); tune(frenchHorn); }} ///:~

This works, but there’s a major drawback:Wemustwritetype-specificmethodsforeachnewInstrumentclassweadd.Thismeansmoreprogramminginthefirstplace,butitalsomeansthatifwewanttoaddanewmethodliketune( ) or a new type of Instrument, we’ve got a lot of work to do. Add the fact that the compiler won’t give us any error messages if we forget to overload one of our methods and the whole process of working with types becomes unmanageable.

It would be better if we could just write a single method that takes the base class as its argument, and not any of the specificderivedclasses.That’sexactlywhatpolymorphismallowsustodo.

The twistThedifficultywithMusic.javacanbeseenbyrunningtheprogram.TheoutputisWind.play().Thisisclearlythedesired output, but it doesn’t seem to make sense that it would work that way. Look at the tune( ) method:

public static void tune(Instrument i) { // ... i.play(Note.MIDDLE_C);}

It receives an Instrument reference. So how can the compiler possibly know that this Instrument reference points to a Wind in this case and not a Brass or Stringed? The compiler can’t. To get a deeper understanding of the issue, it’s helpful to examine the subject of binding.

4.4 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’s 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.

Page 55: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

45

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,thecompilerstilldoesn’tknowtheobjecttype,butthemethod-callmechanismfindsoutandcallsthecorrectmethod body. The late-binding mechanism varies from language to language, but we can imagine that some sort of type information must be installed in the objects.

All method binding in Java uses late binding unless a method has been declared final. This means that ordinarily we don’t need to make any decisions about whether late binding will occur—it happens automatically.

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,soit’sbesttoonlyusefinalasadesigndecision,andnotasanattempt to improve performance.

4.5 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 visualize, 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’s 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. 4.1 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);andyetit’sfinebecauseaCircle is a Shape by inheritance. So the compiler agrees with the statement and doesn’t issue an error message.

Page 56: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

46

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).

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()”); }}public class Shapes { public static Shape randShape() { switch((int)(Math.random() * 3)) { default: case 0: return new Circle(); case 1: return new Square(); case 2: return new Triangle(); }}public static void main(String[] args) { Shape[] s = new Shape[9]; // Fill up the array with shapes: for(int i = 0; i < s.length; i++) s[i] = randShape(); // Make polymorphic method calls: for(int i = 0; i < s.length; i++) s[i].draw(); }} ///:~

Page 57: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

47

The base class Shape establishes the common interface to anything inherited from Shape—that is, all shapes can bedrawnanderased.Thederivedclassesoverridethesedefinitionstoprovideuniquebehaviorforeachspecifictype of 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 wecallthismethodwenevergetachancetoseewhatspecifictypeitis,sinceyoualwaysgetbackaplainShape reference.

main( ) contains an array of Shape referencesfilledthroughcallstorandShape( ). At this point, we know we have Shapes,butwedon’tknowanythingmorespecificthanthat(andneitherdoesthecompiler).However,whenwestep through this array and call draw( )foreachone,thecorrecttype-specificbehaviormagicallyoccurs,aswecan see 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.

4.6 ExtensibilityNow let’s 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’s the diagram:

Page 58: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

48

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. 4.2 Addition of methods and classes to the instrument

All these new classes work correctly with the old, unchanged tune( ) method. Even if tune( )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()”); } public String what() { return “Percussion”; } public void adjust() {}}

Page 59: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

49

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 = new Instrument[5]; int i = 0; // Upcasting during addition to the array: orchestra[i++] = new Wind(); orchestra[i++] = new Percussion(); orchestra[i++] = new Stringed(); orchestra[i++] = new Brass(); orchestra[i++] = new Woodwind(); 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.

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.”

Page 60: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

50

4.7 Overriding vs OverloadingIn the following program, the interface of the method play( ) is changed in the process of overriding it, which means that we haven’t 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’s 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’s another confusing aspect thrown in here. In InstrumentX, the play( ) method takes an int that has the identifierNoteX. That is, even though NoteXisaclassname,itcanalsobeusedasanidentifierwithoutcomplaint.But in WindX, play( ) takes a NoteXreferencethathasanidentifiern. (Although we could even say play(NoteX NoteX) 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. Since NoteX contains intdefinitions,thismeansthattheint version of the now-overloaded play( ) method is called, and since that has not been overridden the base-class version is used.

The output is:

InstrumentX.play()

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

Page 61: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

51

4.8 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. That is, Instrument is meant to express only the interface, and not a particular implementation, so creating an Instrument object makes no sense, and we’ll 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’s 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, theclassmustbequalifiedasabstract. (Otherwise, the compiler gives us an error message.)

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’s 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’s what it looks like:

Page 62: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

52

Fig. 4.3 Instrument class into abstract class

Here’stheorchestraexamplemodifiedtouseabstractclassesandmethods:

//: 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() {}}

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()

Page 63: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

53

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 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++] = new Wind(); orchestra[i++] = new Percussion(); orchestra[i++] = new Stringed(); orchestra[i++] = new Brass(); orchestra[i++] = new Woodwind(); tuneAll(orchestra); }} ///:~

We can see that there’s really no change except in the base class.

It’s 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.

4.9 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’s important to understand the way constructors work in complex hierarchies and with polymorphism. This understanding will help us avoid unpleasant entanglements.

Page 64: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

54

4.9.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’s 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’s take a look at an example that shows the effects of composition, inheritance, and polymorphism on the order of construction:

//: c07:Sandwich.java// Order of constructor calls.

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()”); }}class Sandwich extends PortableLunch { Bread b = new Bread(); Cheese c = new Cheese(); Lettuce l = new Lettuce(); Sandwich() { System.out.println(“Sandwich()”); }public static void main(String[] args) { new Sandwich(); }} ///:~

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

Page 65: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

55

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 1. constructedfirst,followedbythenext-derivedclass,etc.,untilthemost-derivedclassisreached.Member initialisers are called in the order of declaration.2. The body of the derived-class constructor is called.3.

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’re 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.Thenwhenwe’reinthederived-classconstructor,allthememberswecanaccessinthebaseclasshave been initialised. “Knowing that all members are valid” inside the constructor is also the reason that, whenever possible, we should initialize all member objects (that is, objects placed in the class using composition) at their point ofdefinitionintheclass(e.g.,b, c, and 1 in the example above). If we follow this practice, we will help ensure that all base class members and member objects of the current object have been initialised

Page 66: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

56

SummaryPolymorphism 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. The polymorphic method call allows one type to express its distinction from another, similar type, as long as •they’re 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.Taking an object reference and treating it as a reference to its base type is called upcasting, because of the way •inheritance trees are drawn with the base class at the top.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’s called early binding. Late binding, 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. AllmethodbindinginJavauseslatebindingunlessamethodhasbeendeclaredfinal.Thismeansthatordinarily•we don’t need to make any decisions about whether late binding will occur—it happens automatically.A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods, •theclassmustbequalifiedasabstract.If we inherit from an abstract class and we want to make objects of the new type, we must provide method •definitionsforalltheabstractmethodsinthebaseclass.A 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.

ReferencesBalaguruswamy, E., 2008. • Programming with Java - A Primer, 3/e. 7th ed., Tata McGraw Hill publishing company limited.Umbarger, D., 2008. • An Introduction to Polymorphism in Java, [online]. Available at:< http://apcentral.collegeboard.com/apc/public/repository/Intro_to_Polymorphismin_Umbargar.pdf>.[Accessed 12 April 2011]Javapassion.com, • Polymorphism, [online]. Available at: <http://www.javapassion.com/javase/javapolymorphism.pdf>. [Accessed 12 April 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 67: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

57

Self AssessmentAll derived-class methods that match the signature of the base-class declaration will be called using the:1.

Dynamic binding mechanisma. Error-time binding mechanismb. Static binding mechanismc. Early binding mechanismd.

Connecting a method call to a method body is called ______.2. connectiona. bindingb. inheritingc. upcastingd.

Taking an object reference and treating it as a reference to its base type is called:3. Linkinga. Extensibilityb. Bindingc. Upcastingd.

Encapsulation creates new _____types by combining characteristics and behaviors.4. objecta. classb. datac. functiond.

Which of the following statements is FALSE?5. The order of the constructor calls is important. a. When we inherit, we know all about the base class and can access any public and protected members of b. the base class. AllmethodbindinginJavausesearlybindingunlessamethodhasbeendeclaredfinal.c. The late-binding mechanism varies from language to language, but we can imagine that some sort of type d. information must be installed in the objects.

Which of the following statement is true?6. When binding is performed before the program is run it’s called late bindinga. When a language implements late binding, there must be some mechanism to determine the type of the b. object at error-time and to call the appropriate method.Wedeclareamethodfinalasitpreventsanyonefromoverloadingthatmethod.c. The methods that manipulate the base-class interface will not need to be changed at all to accommodate d. the new classes.

Page 68: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

58

All method binding in Java uses late binding unless a method has been declared ________.7. importanta. finalb. publicc. privated.

Late binding is also called: 8. dynamic binding mechanisma. error-time binding mechanismb. static binding mechanismc. early binding mechanismd.

Which of the following method is incomplete it has only a declaration and no method body?9. Abstract methoda. Interface methodb. Overloading methodc. Overriding methodd.

A derived class has access to its own members only, and not to those of the _____class.10. declareda. methodb. basec. objectd.

Page 69: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

59

Chapter V

Exception Handling

Aim

The aim of this chapter is to:

introduce the concept of exception handling•

explain how to throw an exception•

discuss about advertising the exceptions that a method throws•

Objectives

The objectives of this chapter are to:

get an overview of rethrowing exceptions•

explaintheconceptofthefinallyclause•

describetheclassificationofexceptions•

Learning outcome

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

understand the concept of catching exceptions•

deal with errors•

know to c• reate exception classes

Page 70: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

60

5.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++.

5.1.1 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•

5.2 The Classification of ExceptionsIn Java, an exception object is always an instance of a class derived from throwable.

Throwable

ExceptionError

IOExceptionRuntime

Exception

Fig. 5.1 Exception hierarchy in Java

Page 71: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

61

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.

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;•tryingtofinda• class object for a string that does not denote an existing class.

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 had checked whether or not the variable was null before using it.

TheJavaLanguageSpecificationcallsanyexceptionthatderivesfromtheclassError or theclass RuntimeException an unchecked exception. All other exceptions are called checked exceptions. This is useful terminology that we will also adopt.

5.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, it will also the compiler what can go wrong.

For example,codethatattemptstoreadfromafileknowsthatthefilemightnotexistorthatitmightbeempty.Thecodethattriestoprocesstheinformationinafilethereforewillneedtonotifythecompilerthatitcanthrowsome sort of IOException.

The place where we advertise that our method can throw an exception is in the header of the method; the header changestoreflectthecheckedexceptionsthemethodcanthrow.For example, here is the header for a method in the BufferedReaderclassfromthestandardlibrary.Themethodreadsalineoftextfromastream,suchasafileor network connection.

public String readLine( ) throws IOException

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:

Page 72: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

62

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.•

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 throws 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.

Page 73: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

63

5.4 How to Throw an ExceptionLet us suppose something terrible has happened in our code. We have a method, readData,thatisreadinginafilewhose 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. Perusing the JavaAPIdocumentation,wefindanEOFException with the description “Signals that an EOF has been reached unexpectedly during input.” Perfect. Hereis how we throw it:

throw new EOFException();or,EOFException e = new EOFException();throw e;

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.

String gripe = “Content-length: “ + len + “, Received: “ + n;throw new EOFException(gripe);

As we can see, throwing an exception is easy if one of the existing exception classes works for us. In this case:findanappropriateexceptionclass•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.

Page 74: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

64

5.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 FileForma-tException

{. . .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(String message):• constructs a new Throwable objectwith thespecifieddetailedmessage.Byconvention, 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.

5.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 nongraphical 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 minimized.)

Page 75: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

65

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.

To show this at work, here is some fairly typical code for reading in text:

public void read(BufferedReader reader){

try{

boolean done = false;while (!done){

String line = reader.readLine();if(line==null)//endoffile

done = 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 theendofthefile.AswecanseebylookingattheJavaAPI,thereisthepossibilitythatthereadLine method will throw an IOException. 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.

Page 76: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

66

public void read(BufferedReader reader) throws IOException{

boolean done = false;while (!done){

String line = reader.readLine();if(line==null)//endoffile

done = true;else{

process line;}

}}

Remember,thecompilerstrictlyenforcesthethrowsspecifiers.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 propagatethosethatwedonotknowhowtohandle.Whenwepropagateanexception,wemustaddathrowsspecifierto alert the caller that an exception may be thrown.

5.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,try

e3.getMessage()

to get the detailed error message (if there is one), or

e3.getClass().getName()

to get the actual type of the exception object.

Page 77: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

67

5.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.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”);

}

The finally ClauseWhen 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 (IOException e){

show error dialog

Page 78: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

68

}finally{

g.dispose();}

This program executes the code in the finally clause whether or not an exception was caught. This means, in the example code above, the program will dispose of the graphics context under all circumstances.

Let us look at the three possible situations where the program will execute the finally clause.Thecodethrowsnoexceptions.Inthisevent,theprogramfirstexecutesallthecodeinthe• try block. Then, it executes the code in the finallyclause.Afterwards,executioncontinueswiththefirstlineafterthetry block.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 the finally clause.If the • catchclausedoesnotthrowanexception,thentheprogramexecutesthefirstlineafterthetry block. If it 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 the finally clause is executed, and the exception is thrown back to the caller of this method.

We can use the finally clause without a catch clause. For example, consider the following try statement:

Graphics g = image.getGraphics();try{

code that mightthrow exceptions

}finally{

g.dispose();}

The g.dispose() command in the finally clause is executed whether or not an exception is encountered in the try block. Of course, if an exception is encountered, it is rethrown and must be caught in another catch clause.

Page 79: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

69

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 require more planning. If an exception occurs that is not caught anywhere in a nongraphical •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 publishing company limited.Javapassion.com, [online]. • Java Exception Handling. Available at : http://www.javapassion.com/javase/javaexceptions.pdf. [Accessed on 15 April 2011].

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

Page 80: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

70

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 if false?4. Our code may run into a problem that is not adequately described by any of the standard exception a. classes.Once a method throws an exception, the method does not return to its caller.b. 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 hierarchy.d.

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 81: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

71

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

When we propagate an exception, we must add a throws9. specifiertoalertthecallerthatan:exception may be throwna. exception may be handledb. exception may be rethrownc. exception may be cancelledd.

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

Page 82: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

72

Chapter VI

Object Oriented Programming

Aim

The aim of this chapter is to:

state the basic concepts of object oriented programming •

discuss different language paradigms•

explain the data abstraction and encapsulation in detail•

Objectives

The objectives of this chapter are to:

elucidate the complete view of class•

determine the characteristics of object oriented programming•

explain object orientation•

Learning outcome

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

understand the advantages of object oriented programming•

evaluate the scope of class and its members•

recognise• the scope of operator

Page 83: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

73

6.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 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,itcanalsobeanalysedandmaintainedwithoutmuchdifficulty.However,there are some people who feel that OOP is more complicated than older programming methods.

To understand object oriented programming, there are a few concepts that we need to become familiar with. These are discussed below.

6.1.1 Class

Aclasscreatestheattributesofathing,anditwillalsodefinetheprocessesthatthethingcancarryout.For•example, a class called “cats” will have the attributes which are commonly found with cats, such as the ability to purr.A class will bring about modularity within the object oriented computer application. Someone who is not a •programmershouldbeabletofindaclass.The reason for this is because the attributes of the class should be something that will make sense to them.•It is also important for the code of a class to be self contained to a certain degree.•When code is written with relevant names, it will be easier to understand.•Make sure the code is self-contained which will allow one part of the application to be updated without the •need to change the other parts.It is this modularity that makes OOP an effective programming method. It will also help the application solve •the problems that it was designed for.

6.1.2 Object

Anobjectcanbedefinedasaspecificinstanceofaclass.•As an example, while the class Cats will provide all the attributes that are found in all cats, the “object” named •Betsyisaspecificcat.While it shares the same attributes which are found in all cats, it has fur with a unique colour.•In object oriented programming, a programmer would say that the object Betsy is a run-time instance of the •class Cats.A class may also be divided into sub-groups.•Certainvariationsofaclassmaynotbeaspecificobject.•The class Cats may have a sub-group which consists of multiple cat breeds.•For example, if Betsy were a Persian cat, it would be an instance of the Persian cat sub-group.•Every object within an OOP language will share some attributes with the parent class, but it will also have •unique attributes as well.

Page 84: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

74

6.1.3 Method

Amethodmayalsobecalleda“message”andcanbedefinedastheabilitiesofanobject.•Because Betsy is a cat, Betsy can purr. Because of this, “purr” is a method that Betsy has.•Betsy may have a number of other methods.•When a method is used within an object oriented programming language, it will only affect a single object. This •is true even if the method is designed for the entire class.While all cats can purr, we will only need one cat to do it.•Methods can further be broken down into commands, call-backs, or queries.•A query will tell us about the state of the object, and a command will cause that object to carry out a task.•A call-back is a method that is composed of a part within an object.•The part will notify its parent that an event has taken place, and the object may need to react to the event.•

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

Objects Classes

Inheritance PolymorphismDynamicbinding

Messagepassing

Dataabstraction

andencapsulation

6.2.1 Objects

An 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.

Page 85: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

75

6.2.2 Classes

We have studied that objects contain data, and code to manipulate that data. •Theentiresetofdataandcodeofanobjectcanbemadeauser-defineddatatypewiththehelpofaclass.In•other words, objects are variables of the type class. Onceaclasshasbeendefined,wecancreateanynumberofobjectsbelongingtothatclass.Eachobjectis•associated with the data of type class with which they are created. A class is thus 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.•Iffruithasbeendefinedasaclass,thenthestatementfruitmango;• will create an object mango belonging to the class fruit.

6.2.3 Data Abstraction and Encapsulation

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. 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,weightand•cost, 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).•

6.2.4 Inheritance

Inheritance 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 86: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

76

Bird

AttributesFeathersLay eggs

Robin Swallow Penguin Robin

NonflyingBirdFlying Bird

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

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

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

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

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

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

Fig. 6.1 Property inheritance

6.2.5 Polymorphism

Polymorphism is another important OOP concept. Polymorphism, a Greek term, means 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.Thefiguregivenbelow illustrates thata single functionnamecanbeused tohandledifferentnumberand•different types or arguments. This is something similar to a particular world having several 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

Draw()

Circle-object

Draw(circle)Box-object

Draw(box)Triangle-object

Draw(triangle)

Fig. 6.2 Polymorphism

Page 87: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

77

6.2.6 Dynamic Binding

Binding 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 depends on the dynamic type of that reference.•Considertheprocedure“draw”inthefig6.2.Byinheritance,everyobjectwillhavethisprocedure.Itsalgorithm•is,however,uniquetoeachobjectandsothedrawprocedurewillberedefinedineachclassthatdefinestheobject.At run-time, the code matching the object under current reference will be called.•

6.2.7 Message Passing

An 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. Example is as shown below:

employee.salary (name);

object

message

information

Fig. 6.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.

6.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, 1988], paradigms are “patterns of thought for problem solving”. Languageparadigmswereassociatedwithclassesoflanguages.Firsttheparadigmsaredefined.Thereafter,•programminglanguagesaccordingtothedifferentparadigmsareclassified.Thelanguageparadigmsaredividedinto two parts: imperative and declarative paradigms asshowninfig.6.4.Imperative languages can be further classified into procedural and object oriented approach.Declarative•languagescanbeclassifiedintofunctionallanguagesandlogicallanguages.Inthefigurebelow,theexamplesof languages in each category are also given.

Page 88: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

78

Language Paradigm

Imperative Paradigm Declarative Paradigm

Procedural

C, Pascal C++, Simula, Java Lisp Prolog

Object Oriented

Functional Logical

Fig. 6.4 Language paradigm

6.3.1 Imperative Paradigms

The 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 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 a 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. In this language the execution of a program is modelled as a series of states of variable locations. We have two kinds of statements. 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? In this language,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 6.1 Procedural and object oriented paradigms

6.3.2 Declarative Paradigm

In 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.

Page 89: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

79

Thelanguageexecutorappliesafixedmethodtotheserelationstoproduceadesiredresult.Itismainlyusedin•solvingartificialintelligenceandconstraint-satisfactionproblems.Declarativeparadigmisfurtherdividedintotwo categories: functional and logical paradigms.

Functional Paradigm Logical Paradigm

In this paradigm, a programme consists of a col-lection 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/claus-es (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 program-ming language.

Table 6.2 Functional and logical paradigms

6.4 ProgrammingProgramming is an art, which has been through many evolutions. The basic idea for evolution was to develop simpler,maintainable,dependable,efficient,reusableprograms.Letusnowtracetheevolutionofobjectorientedprogramming in detail.

6.4.1 Procedural Programming

In this paradigm, we divide a problem into sub-problems recursively and then we• write a procedure for each sub-problem. Procedures communicate with each other by parameters. In this paradigm, data structures are declared locally or globally. The procedures can contain local data. Pascal and C support this programming approach. For example, if we •want to implement a stack, we divide the problem into smaller problems like how to push value in a stack, how topopavalueandhowtofindwhetherstackisfullorempty.Then we write functions for push, pop, stack empty and stack full and call these functions using its parameters •to implement a stack in a program. The stack size is declared in main program using a data structure (may be an array).

6.4.2 Modular Programming

In this style, the program is divided into modules. Each module will contain all the procedures, which are •related to each other and the data on which they act. Modular programming is the other name for data hiding principle. The reason for this name is that the data in a module cannot be accessed by the procedures in another module •unlessithasbeenspecifiedthatitcanbedoneso.Modularsupportsthisnotion.Forexample,thecompletesetof operations of a stack including the data structure and functions may reside in a module.Theadvantagesofthisparadigmarethatwecanhavedifferentfilesforasimpleprogram.Eachfilecanbe•separatelycompiledandexecutablefilecanbemadefromthem.So,ifthereisanyerrorinonemodule,theentireprogram need not be compiled. Only the module in which the error has occurred can be recompiled separately. This will reduce the total compilation time.Cenablesmodularprogrammingbyprovidingprovisionforincludingfilesandseparatecompilationfacilities.•The context of module is supported by the class concept of C++.

Page 90: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

80

6.4.3 Data Abstraction

Data Abstraction = Modular programming + Data hiding principle.

This concept is supported byC++. InC++, classes can be defined inwhich the data can be specified as•Private. Thisprivatedatacanbeaccessedonlybythememberfunctionsoftheclass.Then,wecandefinetheclassas•auserdefineddatatypewhichistheothernameofDataAbstraction.So,inthisparadigm,wehavetodecidethe types we want and then, we have to provide a full set of operations for each type. Forexample,inthedatastructureofstack,thedatastoredinitcannotbeaccessedormodifiedbyanyother•classexceptthefunctionsofstackclass.Then,itcanbeclassifiedasDataAbstraction.

6.4.4 Object Oriented Programming

Whenwedefinedatatypes(userdefineddatatypes)wemayfindsimilarityamongthem.Also,whenwethink•ofdefininganewclass,wemayfindthatthereisanotherclasswhichisalreadyprocessingmostofthefeaturesof the class, we wish to have. Undersuchasituation,wecandefineaclasswithonlyadditionalfeaturesandexplicitlystatethatitincludesall•thefeaturesofanotherclasswhichhasbeenalreadydefined.Thisconceptisknownasinheritance.Theobjectoriented programming paradigm is made up of abstraction and inheritance.

So, OOP = Data Abstraction + Inheritance.

In this paradigm, we have to decide the classes we want; provide a full set of operations for each class and •then we have to make commonality explicit by using inheritance. Brief recapitulations of these programming paradigms are given in the following diagram:

Procedural programming

•Local and global data •Use of stack for parameter passing •Languages that support the paradigm: C, Pascal

Modular programming

•Separate compilation of modules •Data Abstraction =Data hiding principles •Languages that support this paradigm: ADA, C++

Object-oriented programming

•Data abstraction, Inheritance, Polymorhism •Languages that support this paradigm: C++, JAVA

Other Programming Paradigms

•Functional programming -LISP •Logic Programming - Prolog •Concurrent programming •Distributed component programming, etc.

Fig. 6.5 Programming paradigms

Page 91: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

81

6.5 Objects Here, we will discuss about object and its orientation.

6.5.1 Object: The Soul of Object Oriented Programming

Object oriented Programming and Design is all about objects. Traditionally, code and data are apart. For example, •in the “C” language, units of code are called functions or operations, while units of data are called structures. Functions and structures are not formally connected in “C”. A “C” function can operate on more than one •type of structure, and more than one function can operate on the same structure. However, it is not true for object oriented programs. In object oriented programming, the data and the operations are merged into a single indivisible unit – an object.An object has both state (data) and behaviour (operations on data). In that way, objects are not much different •from ordinary physical entities. It is easy to see how a mechanical device embodies both state and behaviour. For example, a simple non moving entity: an ordinary bottle combines state (how full the bottle is? Is it open? How much warm its contents are? Withbehaviour(theabilitytodispenseitscontentsatvariousflowrates,tobeopenedorclosedtowithstand•temperatures). It is this resemblance of objects to real things that provides objects much of their power and appeal.Theynotonlycanmodelcomponentsofrealsystems,butalsofulfilassignedrolesascomponentsinsoftware systems. Therefore, object based programming scheme has many advantages.Anobjecthasitswell-definedboundaryinwhichitperformsitsfunctionswhileinteractingwithotherobjects•with its external interface. Objects interact with each other via messages. (Please refer to Fig. 6.6). The concept of object being an entity •can be described as, when we refer to some object in real world we know it will be in some state (in time and place).

Message for Object 2

Object 1(Attributes)

Object 2(Attributes)

Object 3(Attributes)

Message for Object 1

Message for Object 1

Message for

Object 3Message for Object 2

Message for Object 3

External Interface via messages

External Interfacevia messages

Fig. 6.6 Objects and interfaces

6.5.2 The Object Orientation

Suppose, we want to add two number say, 1 and 2, in an ordinary, non-object oriented computer language like •C. We can write this as:

a = 1;b = 2;c = a + b;

Page 92: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

82

The above code implies that takes a number ‘a’, which has the value 1, and number ‘b’, which has the value 2, •and adds them together using the C language’s built-in addition capability. Take the result, which happens to be 3 in this case, and places it into the variable called ‘c’.Now, here’s the same thing expressed in C++, which is a pure object oriented language:•

a = 1;b = 2;c = a + b;

In C++, this says, take the object ‘a’ which has the value 1, and send it the message “+”, which includes the •argument ‘b’ which, in turn, has the value 2. Object ‘a’, receives this message and performs the action requested to produce a resultant object which in this case has a value 3 and assign this object to object ‘c’.The reason is that objects greatly simplify matters when the data get more complex. Suppose we wanted a data •typecalledlist,whichisalistofnames.InC,listwouldbedefinedasastructure.

struct list {<definitionofliststructuredatahere>};list a, b, c;a = “Object Oriented”;b = “Programming”;

Let’s try to add these new a and b in the C language:• c = a + b;

The C compiler will generate an error when it tries to compile this because it does not understand what to do •with addition of two strings. C compilers just understand how to add number, but a and b are not numbers.OnecandothesamethinginC++,butthistime,listisdefinedandimplementedasaclasscalleda“String”.•

list a, b, c; a = “Object-Oriented”; b = “Programming”; c = a + b

Thefirstthreelinessimplycreatelistobjects‘a’and‘b’fromthegivenstrings.Theadditionmayworkifthe•listclasswascreatedwithafunction/methodwhichspecifically“knows”howtohandlethemessage“+”.Forexample, the message plus might simply be used for concatenation of two strings. Thus, the value of c may be “Object oriented Programming”.

6.6 ClassesA class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created.

Class is composed of three things: a name, attributes, and operations. A class is a group of objects that share commonpropertiesandrelationshipsasshowninfigurebelow.

Page 93: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

83

Object

Data

Member Function

Member Function

Object

Data

Member Function

Member Function

Object

Data

Member Function

Member Function

Fig. 6.7 Communication between objects

A typical class declaration would look like:

Class item{int number;floatcost;public:voidgetData(inta,floatb);void putData(void); }

For instance, a software model of a car, a car “class”, might contain data about the type of car and abilities such asaccelerateordecelerate.Aclassisaprogrammerdefineddatatypethathasdata,itsmembers,andabilities,itsmethods. An object is a particular instance of a class. This is best understood by an analogy with a built-in data type such as int (integer).

int x; /* declares x to be a variable of type int.*/car impala; /* declares impala to be an object of class car.*/

6.6.1 A Complete View of a ClassA class is a logical method to organise data and functions in the same structure.

They are declared using keyword class, whose functionality is similar to that of the C keyword struct, but with the possibility of including functions with a variety of scope as members, instead of only data. Now let us have a view of a complete class:

Page 94: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

84

class class_name {permission_label_1:member1;permission_label_2:member2;...} object_name;

Intheaboveexample,class_nameisanamefortheclass(userdefinedtype)andtheoptionalfieldobject_nameisone,orseveral,validobjectidentifiers.

The body of the declaration can contain members, that can be either data or function declarations, and optionally permission labels, that can be any of these three keywords: private, public or protected. They make reference to the permission which the following members acquire:

Private members of a class are accessible only from other members of their same class or from their “friend” •classes.Protected members are accessible from members of their same class and friend classes, and also from members •of their derived classes.Public members are accessible from anywhere the class is visible.•If we declare members of a class before including any permission label, the members are considered private, since •it is the default permission that the members of a class declared with the class keyword acquire. For example:

class crectangle {int x, y;public:void set_values (int,int);int area (void);} rect;

Declares class crectangle and an object called rect of this class (type). This class contains four members: two variables of type int (x and y) in the private section (because private is the default permission) and two functions in the public section: set_values ( ) and area ( ), of which we have only included the prototype. In the previous example, where crectanglewastheclassname(i.e.,theuser-definedtype),andrectwasanobjectoftypecrectangle.Nowconsiderthe following declaration of a variable: int a;Whatisthedifferencebetweenobjectdeclarationandvariabledeclaration?Afteranalysiswewillfindthatintisthe class name (type) and a is the object name (variable).

On successive instructions in the body of the program we can refer to any of the public members of the object rect as if they were normal functions or variables, just by putting the object’s name followed by a point and then the class member. For example: rect.set_value (3,4); myarea = rect.area( );

but we will not be able to refer to x or y since they are private members of the class and they could only be referred from other members of that same class .Example

Page 95: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

85

# include <iostream.h>class crectangle {int x, y;public:void set_values(int, int);int area (void) {return(x*y);}};void crectangle:: set_values (int a, int b) {x = a ;y = b ;}int main ( ) {crectangle rect;rect.set_values (3, 4 );cout << “area: “ << rect.area ( ) ;}

Output: rect area : 12

6.6.2 Scope Operator

In the previous example, we have used the operator • : :ofscopeinthedefinitionofset_values().Noticethatwehavedefinedthebehaviouroffunctionarea()withinthedefinitionofthecrectangleclass–givenitsextremesimplicity. Whereas,set_values()hasonlyitsprototypedeclaredwithintheclassbutitsdefinitionisoutside.So,inthis•outside declaration, we must use the operator of scope “::”.Thescopeoperator(::)specifiestheclasstowhichthememberbeingdeclaredbelongs,grantingexactlythe•samescopepropertiesasifitwasdirectlydefinedwithintheclass.The reason why we have made x and y private members (remember that if nothing else is said all members •ofaclassdefinedwithkeywordclasshaveprivateaccess)itisbecausewehavealreadydefinedafunctiontointroduce those values in the object (set_values( )) and therefore the rest of the program does not have a way to directly access them. One of the greater advantages of a class is that we can declare • several different objects from it. For example, if we consider the previous example of class crectangle, we could have declared the object rectb in addition to the object rect.

Page 96: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

86

Example # include <iostream.h>class crectangle {int x, y ;public :void set_values (int, int) ;int area (void) {return (x * y) ; }};void crectangle :: set_values (int a, int b) {x = a;y = b ;}int main ( ) {crectangle rect, rectb;rect.set_values (3,4);rectb.set_values (5,6);cout << “rect area: “ << rect.area( ) << endl;cout << “rectb area: “ << rectb.area( ) << endl;}

Output: rect area: 12, rectb area: 30The call to rect.area ( ) does not give the same result as the call to rectb.area ( ). This is because each object of •class crectangle has its own variables x and y, and its own functions set_value ( ) and area ( ). On that, is based the concept of object and object oriented programming. In that the data and functions are properties •of the object, instead of the usual view of objects as function parameters in structured programming. In this concrete case, the class crectangle, of which there are two objects: • rect and rectb, each one with its own member variables and member functions.

6.6.3 Scope of Class and its MembersThescopeofaclassmemberdependsuponitsaccess-specifier(private,public,protected).

Scope of private and protected membersThe private and protected members of a class can be accessed only by the member function of the class. These members cannot be accessed directly by using the object names. In other words, the names of the private and protected members of the class cannot appear except in the body of the class, let us see an example to understand this.

Page 97: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

87

Example # include <iostream.h>class x{private :int a;void fc (void){cout << a; // private data member (a) used by a member function}public :int i;void fcc1 (void){cout < 2*i;a=13; // private data member (a) used by a member function}};x Ob1;int main ( ),{Ob1.i= 10;Ob1.fcc1( );Ob1.a = 5; // invalid. a is private data memberOb1.fc( ); //invalid fc( ) is a private member function........…....}

Scope of public membersThe scope of public members depends upon the object being used for referencing them. If the referencing object is a global object, then the object of public members is also global and if the referencing object is a local object, then the scope of public members is local.

Page 98: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

88

Example

#include <iostream.h>class x{private:int a ;void fc(void){ cout << a;}public :12Object-orientedint i ;void fcc1( void){ cout << 2*i;a = 13;fc( );}};x Ob1; // global object Ob1int main( ){ x Ob2; // local (to main( )) object Ob2Ob1.i = 10; // Ob1 is global & available to mainOb1.fcc1( );Ob2.i = 20; // Ob2 is local object available to main( )Ob2.fcc( );}void func1( ){ x Ob3;Ob1.i = 12; // Ob1 is global and hence also available to func1( )Ob1.fcc1( ); // validOb2.i = 25; // invalid Ob2 is not available to func1( )Ob2.fcc1( ) ; // invalidOb3.i = 15; // valid. Ob3 is locally available to func1( )Ob3.fcc1( ); // valid...............................}

In the above example, Ob1 is a global object, and so the public members of Ob1 can be accessed from any of the functions in the program. Ob2 is a local object, local to function main ( ), and thus, the public members of Ob2 can be accessed only in main ( ) and not in func1 ( ) and not anywhere else.

6.7 Object Oriented ProgrammingLet us study object oriented programming in detail. Whenever we have a problem in hand, we have a very •natural tendency to differentiate the problem space and solution space of the problem, i.e., the place where the problemexistsandtheplacewherewetrytofindoutanswer.When we use computer to solve a problem, then computer is the “solution space”, i.e., the place where we model •that problem and the “problem space” is the place where the problem that is being solved exists.All programming languages offer some level of abstraction, and the complexity level for its solution space. A •problem that we are able to solve by any programming language is directly related to the kind and quality of abstraction done by it.

Page 99: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

89

What is it that we are abstracting?For example, assembly language is an abstraction of the machine instruction set. Many higher level languages •(such as Fortran, BASIC, and C) were abstractions of assembly language. These languages were improvements over assembly language, but their primary underlying abstraction model still required us to think in terms of the structure of the computer rather than the structure of the problem we are trying to solve. It was the job of the programmer to establish the association between the machine and the Problem by proposing •the suitable modules, data structures and algorithms. The effort required to perform this mapping is extrinsic totheprogramminglanguage.Also, thiskindofmappingproducesprogramsthataredifficult towriteandexpensive to maintain.Thus, the focus of such programming paradigms is on processing, that is, the algorithms were needed to perform •the desired computation on structured data. The programming languages support this paradigm by providing functions and facilities for passing arguments to these functions and returning values from functions. In other words, emphasis was to:

decide the structure of data �decide which procedures are required (what is needed?) �use the best algorithm available (How to achieve it?) �

For example, A Square root function is:Givenadouble-precisionfloating-pointargument,itproducesthesquareroot.

double sqrt (double arg){// code for calculation}void f() // function does not return a value{double root2 = sqrt (2);// Get and then print the square root}

Code written within curly brackets express group. They indicate start and end of function bodies. From the point •of view of programming, functions are used to create order in a maze of algorithms. The alternative to modelling the machine is to model the problem we are trying to solve. The object oriented •approach goes a step further by providing tools for the programmer to represent solution entities with respect to the problem space. This representation is enough to show that the programmer is not constrained to any particular type of problem. We refer to the entities in the problem space and they are allowed to adapt itself to the terminology used for •theproblem.Itmayappeartobeamoreflexibleandpowerfullanguageabstractionthanwhatwehavehadbefore. Thus, the idea behind object oriented programming is to allow us to describe the problem in the terminology of •the problem, rather than in terms of the computer where the solution will run. There is still a connection back to the computer, but how? All the programming languages have traditionally divided the world into two parts: • data and operations on data. The data is a static entity and can be changed only by the valid operations. The functions that can operate ondatahaveafinitelifecycleofitsownandcanaffectthestateofdataovertheirlifetime.Suchadivisionis,of course, on the basis the way computers work.The operations or functions have meaning only when they can act on data or modify it. At some point, all •programmers, including object oriented programmers must lay out the data structures that their programs will useanddefinethefunctionsthatwillactonthedata.

Page 100: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

90

A procedural programming language like C, may offer various kinds of support for organising data and functions. •Functions and data structures are the basic elements of procedural design. But object oriented programming tries to model the design of the program as real world philosophy. It groups •operations and data into modular units called objects and lets you combine objects into structured networks to form a complete program. In an object oriented programming language, objects and object interactions are the basic elements of design.

6.8 Object Oriented Programming CharacteristicsThe 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.Thedataisthuswell•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. 6.8 An object

Anobjectorientedprogrammingsystemiscomposedofmultipleobjects(seefig.6.2).Whenoneobjectneeds•informationfromanotherobject,arequestissentaskingforspecificinformation,(forexample,areportobjectmay need to 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 is that: “As the user of an object, we never need to peek inside •the box (object).”Allcommunicationsamongtheobjectsisdoneviamessages.Messagesdefinetheinterfacetotheobject.The•object that a message is sent to 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 in thefirstplacedecidedtochangesomeofthesedetails,thenwemaybeintrouble.Our software may not be working 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 have taught us that software do change. A popular saying is that “software is not written, it is re-written.” Please remember that 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.

Page 101: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

91

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 that is 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. Let us take an 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. The concept involves the concepts of inheritance and polymorphism.

6.9 Advantages of Object Oriented ProgrammingThe popularity of object oriented programming (OOP) was because of its methodology, which allowed breaking complex and large software programs to 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 software built around OOP are modular, because they are built on objects and we know 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.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:• Softwarebuiltonobjectorientedprogrammingcanbeflexible 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 102: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

92

SummaryObject Oriented Programming, also known as OOP, is a computer science term which is used to describe a •computer application that is 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. Thescopeofaclassmemberdependsuponitsaccess-specifierwhichareprivate,public,protected).•The popularity of object oriented programming (OOP) was because of its methodology, which allowed breaking •complex and large software programs to simpler, smaller and manageable components

ReferencesNirosh, 2011, • Introduction to Object oriented Programming Concepts and More, [Online] (Updated 25 January 2011). Available at: <http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx#Abstract > [Accessed 23rd March 2011].Balagurusamy. E., 2006. • Object Oriented Programming with C++. 3rd ed., Tata McGraw-Hill Publishing Company Limited.

Recommended ReadingLafore.R.• , 2002. Object Oriented Programming in C++, 4th ed., Pearson Education India.Farrell. J., 2008. • Object Oriented Programming using C++, 4th ed., Course Technology, USA; Cengage Learning.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 21 March 2011].

Page 103: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

93

Self Assessment_________isdefinedasanidentifiableentitywithsomecharacteristicandbehaviour.1.

Objecta. Classb. Datac. Named.

Whatareuser-defineddatatypesthatbehavelikethebuilt-intypesofaprogramminglanguage?2. Dataa. Keywordsb. Classesc. Objectsd.

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

Which statement 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-classdefinesonlythosefeaturesthatareuniquetoit.d.

Which statement 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.

Page 104: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

94

Match the following:7. 1. Object oriented Programming and

Design is all about A. Class

2. OOP = B. Modular programming + Data hiding principle3. Data Abstraction = C. objects4. It is the blueprint from which the

individual objects are created.D. Data Abstraction + Inheritance

1-C, 2-D, 3-B, 4-Aa. 1-D, 2-C, 3-B, 4-Ab. 1-B, 2-A, 3-D, 4-Ac. 1-B, 2-C, 3-A, 4-Dd.

Class is composed of _________ things.8. twoa. threeb. fourc. fived.

Which of the following is false?9. The data is a static entity and can be changed only by the valid operations.a. An object oriented programming system is composed of multiple objects.b. Abstraction refers to the act of representing essential features without including the background details or c. explanations.A class is simply a representation of a type of program.d.

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

Page 105: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

95

Chapter VII

Classes and Objects

Aim

The aim of this chapter is to:

introduce the concept of classes•

explain the method of specifying a class•

discuss the differences between class and structure•

Objectives

The objectives of this chapter are to:

get an overview of static data members•

explain the concept of constructor•

describe the process of accessing class members•

Learning outcome

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

understand the concept of destructors•

comprehend the pointer to members and static member functions•

definem• ember functions

Page 106: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

96

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

Class is aAuserdefineddatatypewithdataelementsandoperations•The data members that describe the state of the object.•Theoperationsthatdefinesthebehaviouroftheobject.•Typicallyaclassisusedtointroduceanewuserdefineddatatypeanddefineabstractionsthatdonotmap•naturallyintopredefinedorderiveddatatypes.

Class nameAttributes

Operations

Fig. 7.1 Representation of a class

Attributes denote static and dynamic properties. An operation denotes a Attributes service that a class offers to its clients (objects). For example: A Zoo Animal class, an employee class etc.

C Structures: It is one of the unique features of the C language is structures. They provide a method for packing together data of different type. A structure is a convenient tool for handling a group of logically related data items. Itisauser-defineddatatypewithatemplatethatservestodefineitsdataproperties.Oncethestructureisdefined,we can create 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;};

The keyword struct declares studentasanewdatatypethatcanholdthreefieldsofdifferentdatatypes.Thesefieldsareknownasstructuremembersorelements.Theidentifierstudent,whichisreferredtoasstructurenameorstructure tag, can be used to create variables of type student.

Page 107: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

97

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.•Structures like class can not be inherited.•Structures can not have constructors & destructors.•

7.2 Specifying a ClassA class is a way to bind the data and its associated functions together. It allows the data (and functions) to be hidden, 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; //privatebydefault public: voidgetdata(inta,floatb); //functionsdeclaration void putdata (void); // using prototype}: // ends with semicolon

We usually give a class some meaningful name, such as item,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() for displaying their values.

Page 108: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

98

7.3 Creating ObjectsOnce a class has been declared, we can create variables of that type by using the class name. for example:

item x; // memory for x is created

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: item x,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.

7.4 Defining Member FunctionsMemberfunctionscanbedefinedintwoplaces:

Outsidetheclassdefinition•Insidetheclassdefinition•

Outside the class definitionMemberfunctionsthataredeclaredinsideaclasshavetobedefinedseparatelyoutsidetheclass.Theirdefinitionsare very much lime 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 complier which class the function belongs to. The generalformofamemberfunctiondefinitionis:

return-type class-name :: function-name (argument declaration){ function body}

Page 109: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

99

The membership label class-name:: tells the complier that the function function-name belongs to the class class-name.Thatis,thescopeofthefunctionisrestrictedtotheclass-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.•

Inside the class definitionAnothermethodofdefiningamemberfunctionistoreplacethefunctiondeclarationbytheactualfunctiondefinitioninsidetheclass.Forexample,wecoulddefinetheitemclassasfollows:

class item{ int number;floatcost; public:voidgetdata(inta,floatb);//declarations // inline function void purdata (void) { cout << number << “\n”; cout << cost << “\n”; }};

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

7.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 110: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

100

void getdata (int a) { number = a; count ++; } void getcount (void) { cout << “count: “; cout << count <<”\n”;};int item :: count;int main (){

item a, b, c; // count is intialised to zeroa.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: 0After reading datacount: 3count: 3count: 3

Note that the type and scope of each static membervariablemustbedefinedoutsidetheclassdefinition.Thisisnecessary because the static data members are stored separately rather than a part of an object, they are also known as class variables.

7.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 objects0 as follows:•

Class-name:: function-name;

Page 111: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

101

7.6.1 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:

void mul (int, int) const;double get_balance () const;

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

7.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 & to a “fully operator” class member name. A class member pointer can be declared using the operator:: * with the calss name. For example, given the class

class a{ private: int m; public: void show ();};

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.

7.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.

Aconstructorisdeclaredanddefinedasfollows:// class with a constructorclass integer{ int m, n; public:

Page 112: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

102

interger (void); // constructor declared ……….. ………..};interger :: integer (void) // constructor declared{ m=0; n=0;}

Whenaclasscontainsaconstructorliketheonedefinedabove,itisguaranteedthatanobjectcreatedbytheclasswill be initialised automatically. For example, the declaration:

integer int1; // object int1 created

not only creates the object int1 of type integer but also initialises its data members m and n to zero.

A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A::A().Ifnosuchconstructorisdefined,thenthecompliersuppliesadefaultconstructor.Thereforeastatementsuch as:A a;invokes the default constructor of the complier 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.•

7.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>using namespace std;class code{ int id; public: code() {} //constructor code(int a) {id = a;} // constructor again code(code & x) { id = x.id; // copy in the value

Page 113: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

103

} void display(void) { cout << id; }};int main{}{ code A(100); // object A is created and initialised code B(A); // copy constructor called code C=A; // copy constructor called again code D; // D is created, not initialised D = A; // copy constructor not called cout << “\n id of A: “; A.display(); cout << “\n id of B: “; B.display(); cout << “\n id of C: “; C.display(); cout << “\n id of D: “; D.display(); return 0;}

The ouput of the program is:id of A: 100id of B: 100id of C: 100id of D: 100

Whennocopyconstructorisdefined,thecompliersuppliesitsowncopyconstructor.

7.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 complier 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(int i=0; i<d1; i++) delete p[1] delete p;}

The example below illustrates that the destructor has been invoked implicitly by the complier.

#include <iostream>using namespace std;int count = 0;class alpha

Page 114: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

104

{ public: alpha() { count++; cout << “\nNo. Of object created” << count; } ∼alpha() { cout << “\nNo. Of object destroyed” <<count; }};int main(){ cout <<”\n\nENTER MAIN\n”; alpha A1, A2, A3, A4; { cout << “\n\nENTER BLOCK\n”; alphs A5; } { cout << “\n\nENTER BLOCK2\n”; alpha A6; } cout << “\n\nRE-ENTER MAIN\n”; return 0;}

Output of the program:

ENTER MAIN

No. of object created 1No. of object created 2No. of object created 3No. of object created 4

ENTER BLOCK1

No. of object created 5No. of object destroyed 5

ENTER BLOCK 2

No. of object created 5No. of object destroyed 5

RE-ENTER MAIN

No. of object destroyed 4No. of object destroyed 3No. of object destroyed 2No. of object destroyed 1

Page 115: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

105

SummaryThe basic building blocks of object oriented programming are classes and objects.•Attributes denote static and dynamic properties. An operation denotes a 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. 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. •An important difference between a member function and a normal function is that a member function incorporates •a membership ‘identify label’ in the headerAstaticmembervariablehascertainspecialcharacteristics.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.

ReferencesBalaguruswamy, E., 2006. • Object Oriented Programming with C++. 3rd ed., Tata McGraw Hill Publishing Company Limited.C++ Objects and Classes• . Available at: < http://www.exforsys.com/tutorials/c-plus-plus/c-plus-plus-objects-and-classes.html>. [Accessed 15 April 2011].What is an object?• [Online]. Available at: <http://www.intap.net/~drw/cpp/cpp06_01.htm> [Accessed 15 April 2011].

Recommended ReadingBalagurusamy, E., 2006. • Object Oriented Programming with C++. 3rd ed., Tata McGraw Hill Publishing Company Limited.Lafore, R., 2001. • Object-Oriented Programming in C++. 4th ed., Sams.Koffman, E.B., 2005. • Objects, Abstraction, Data Structures and Design: Using C++. Wiley.

Page 116: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

106

Self AssessmentWhich is an important difference between a member function and a normal function?1.

Member function incorporates a membership ‘identify label’ in the headera. Member function incorporates a membership ‘identify label’ in the bodyb. Member function incorporates a membership ‘object label’ in the headerc. Member function incorporates a membership ‘structure label’ in the headerd.

Which of the following 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.

Thetypeandscopeofeachstaticmembervariablemustbedefined_________theclassdefinition.3. outsidea. insidea. afterb. beforec.

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.

Which of the following is the function of constructor?5. To initialise the members of its classa. To initialise the objects of its functionsb. To declare the objects of its classc. To 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.

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

Page 117: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

107

Which of the following 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/an ___________.

membera. functionb. objectc. tilded.

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

Page 118: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

108

Chapter VIII

Operator Overloading

Aim

The aim of this chapter is to:

introduce the concept of operator overloading•

enlist the rules of operator overloading•

discuss the type of conversions •

Objectives

The objectives of this chapter are to:

highlight loading operators•

introduce the concept of overloading unary operator•

explain the process of overloading binary operator•

Learning outcome

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

understand the concept of overloading operator•

describe the overloading of unary and binary operators•

defin• e the rules of overloading operators

Page 119: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

109

8.1 Introduction to Operator OverloadingOperator overloading is one of the many exciting features of C++ language which enhances the extensibility. C++ triestomaketheuser-defineddatatypesbehaveinmuchthesamewayasthebuilt-intypes.C++hastheabilitytoprovide the operators with a special meaning for a data type. The mechanism of giving such special meanings to an operator is known as operator overloading.

The law of conservation of complexity says that every application must have an inherent amount of irreducible complexity. Ultimately, complexity isn’t actually reduced; it is moved. The advantage of operator overloading is that it moves the complexity from the many users to the few servers. Operator overloading allows existing C++ operatorstoberedefinedsothattheyworkonobjectsofuserdefinedclasses.

Operator overloading means giving different meaning to existing operators like +, -, *, / etc. It does not mean •a radical change but a slight difference in default behaviour of the operator.Needtochangesomeoperatorsarisewhenwewanttodooperationsonuserdefinedclasseslikeforexample•wedefineaclassA.ThenweinstantiatedaandaafromA.Now we want to add a to aa. Normal a + aa does not have any meaning, because a and aa are not derived from •standarddatatypesandbehaviourofoperator‘+’isnotdefinedforourclassA.To overcome such problems, C++ has provided us with ‘operator overloading’. We can overload the ‘+’ operator •and tell it how to add objects of type class A.In C++, one can overload only following operators:+ - * / ^ & | ~ != < > + = -= *= %= ^= &=|= << >> >>= <<= == != <= >= &&|| ++ -- ->* , -> [] () new deleteIt is not possible to change the precedence of these operators, nor can the expression syntax be changed. For •example,itisnotpossibletodefineaunary%orabinary!It isnotpossible todefinenewoperator tokens,butwecanuse thefunctioncallnotationwhen thissetof•operators is not adequate.

8.2 How to Overload OperatorsTo overload an operator, we must specify its relationship to the class to which the operator is applied. This is done with the help of a special function, called operator function, which describes the task. The general form of an operator function is:

return type classname :: operator op(arglist){ Functionbody //taskdefined}

Where return typeisthetypeofvaluereturnedbythespecifiedoperationandop is the operator being overloaded. The op is preceded by the keyword operator. operator.op is the function name.Operator functions are declared in the class using prototypes as follows:

vector operator+(vector); // vector additionvector operator-() // unary minusfriend vector operator+(vector, vector); // vector additionfriend vector operator-(vector); // unary minusvector operator-(vector &a); //subtractionint operator ==(vector); //comparisonfriend int operator == (vector, vector) // comparison

Vector is a data type of class and may represent both, magnitude and direction or a series of points called elements.

Page 120: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

110

The process of overloading involves the following steps:Createaclassthatdefinesthedatatypethatistobeusedintheoverloadingoperation.•Declare the operator function operator op() in the public part of the class. It may be either a member function •or a friend function.Definetheoperatorfunctiontoimplementtherequiredoperations.•

Overloaded functions can be invoked by expressions such as:op x or x opFor unary operators and x op yfor binary operators, op x (or x op) would be interpreted as:operator op (x)

8.3 Overloading Unary OperatorsLet us consider the unary minus operator. A minus operator when used as a unary, takes just one operand. We know that this operator changes the sign of an operand when applied to a basic data item. We will see here how to overload this operator so that it can be applied to an object in a much similar way as is applied to an int or float variable. The unary minus when applied to an object should change the sign of each of its data items. Program below shows how the unary minus operator is overloaded.# include <iostream>using namespace tsd;class space{ int x; int y; int z;public: void getdata(int a, intb, int c); void display(void); void operator-(); // overload unary minus};void space :: getdata( int a, int b, int c){ x= a; y = b; z = c;}void space :: display(void){ cout << x<< “ “; cout << y<< “ “; cout << z<< “\n “;}Void space :: operator-(){ x = -x; y = -y; z = -z;}int main(){ space S;

Page 121: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

111

S.getdata(10, -20, 30); cout << “S: “; S.display(); -S; // activates operator-() function cout <<”S: “; S.display(); return 0;} The output of the program is:

S: 10 -20 30S: -10 20 -30

Remember, a statement likeS2 = -S1;

Willnotwork,becausethefunctionoperator-()doesnotreturnanyvalue.Itcanworkifthefunctionismodifiedto return an object.

8.4 Overloading Binary OperatorsThe mechanism used for overloading a unary operator is also used for overloading the binary operator. The statement below shows to add two number using a friend function.

C = sum(A, B); // functional notation.

The functional notation can be replaced by natural looking expressions.C = A+B // arithmetic notation

By overloading the + operator using an operator+() function. The program below shows how this is accomplished.

# include <iostream>using namespace std;class complex{ floatx; //realpart flaoty; //imaginarypartpublic: complex(){} //constructor 1 complex(floatreal,floatimag) //constructor2 { x = real; y= imag;} complex operator+(complex); void display(void);};complex complex :: operator+(complex c){ complex temp; // temporary temp.x= x+c.x; // these are temp.y=y+c.y; //floatadditions return(temp);}void compex ::display(void)

Page 122: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

112

{ cout << x<< “+j” <<y<< “\n”;}int main(0{ complex C1, C2, C3; // invokes constructor1 C1 = complex (2.5, 3.5); // invokes constructor2 C2 = complex (1.6, 2.7); C3 = C1+C2;

cout <<”C1 = “; C1.display(); cout <<”C2 = “; C2.display(); cout <<”C3 = “; C3.display(); return0;}

Output of the program is:

C1 = 2.5 + j3.5C2 = 1.6 +j2.7C3 = 4.1 = j6.2

Let us have a close look at the function operator+() and see how the operator overloading is implemented.

complex complex ::operator+(complex c){ complex temp; temp.x = x+c.x; temp.y= y+c.y; return(temp);}

We should note the following features of this function:It receives only one complex type argument explicitly•It returns a complex type value•It is a member function of complex•

The function is expected to add two complex values and return a complex value as a result, but receives only one value as argument. Where does the other value come from? Now let us look at the statement that invokes this function:

C3 = C1+ C2; // invokes operator+(0 function

We know that a member function can be invoked only by an object of the same class. Here, the object C1 takes the responsibility of invoking the function and C2 plays the role of an argument that is passed to the function. The above invocation statement is equivalent to.

C3= C1.operator+(C2); // usual function call syntax

Therefore, in the operator+() function, the data members of C1 are accessed directly and the data members of C2 are accessed using the dot operator. Thus, both the objects are available for the function. For example, in the statement:

Page 123: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

113

temp.x = x + c.x;

c.x refers to the object C2 and x refers to the object C1.temp.x is the real part of temp that has been created specially to hold the results of addition of C1 and C2. The function returns the complex temp to be assigned to C3.

8.5 Rules for Overloading OperatorsAlthoughitlookssimpletoredefinetheoperators,therearecertainrestrictionsandlimitationsinoverloadingthem.Some of them are listed below:

Only the existing operator can be overloaded. New operators cannot be created.•Theoverloadedoperatormusthaveatleastoneoperandthatisofunder-definedtype.•Wecannotchangethebasicmeaningofanoperatorforexample:theplus(+)cannotberedefinedtosubtract•one value from the other.There are some operators that cannot be overloaded.•We cannot use friend functions to overload certain operators. However, member functions can be used to •overload them.Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit •values, but, those overloaded by means of a friend function, take one reference argument.Binary operators overloaded through a member function take one explicit argument and those which are •overloaded through a friend function take two explicit arguments.When using binary operators overloaded through a member function, the left hand operand must be an object •of the relevant class.Binary arithmetic operators such as +,-.*, and / must explicitly return a value. They must not attempt to change •their own arguments.

Size of Size of operator. Membership operator.* Pointer-to-member operator:: Scope resolution operator?: Conditional operator

Table 8.1 Operators that cannot be overloaded

= Assignment operator( ) Function call operator[ ] Subscripting operator-> Class member access operator

Table 8.2 where a friend cannot be used

8.6 Types ConversionsWe know that when constants and variables of different types are mixed in an expression, C applies automatic type conversion to the operands as per certain rules. Similarly, an assignment operation also causes the automatic type conversion. The type of data to the right of an assignment operator is automatically converted to the type of the variable on the left. For example, the statements.int m;floatx=3.14159;m = x;

convert x to an integer before its value is assigned to m. Thus, the fractional part is truncated. The type conversions are automatic as long as the data types involved are built-in types.

Page 124: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

114

User-defined data typesConsider the following statement that adds two objects and then assigns the result to a third object.

v3 = v1 + v2 // v1, v2, v3 are class type objects

When the objects are of the same class type, the operations of addition and assignment are carried out smoothly andthecomplierdoesnotmakeanycomplaints.Sincetheuser-defineddatatypesaredesignedbyustosuitourrequirements, the complier does not support automatic type conversions for such data types. We must, therefore design the conversion routines by ourselves, if such operations are required. Three types of situations might arise in the data conversion between incompatible types:

Basic to class typeThe conversion from basic type to class type is easy to accomplish. For example, a constructor is used to build a vector object from an int type array. Similarly, we use another constructor to build a string type object from a char* type variable. These are the examples where constructor performs a defacto type conversion from the argument’s type to constructor’s class type.

Consider the following constructor:

string :: string(char *a){ length = strlen(a); P = new char[length+1] strcpy(P,a);}

This constructor builds a string type object from a char* type variable a. The variables length and p are data members of the class string.Oncethisconstructorhasbeendefinedinthestringclass,itcanbeusedfroconversionfrom char* type to string type. Example:

string s1, s2;char*name1 = “IBM PC”;char* name2 = “Apple Computer”;s1 = string(name1);s2 = name2;

The statements1 = string(name1);

First converts name1 from char* type to string type and then assigns the string type values to the object s1. The statements2 = name2;Also does the same job by invoking the constructor implicitly.

Class to basic typeTheconstructorfunctionsdonotsupportsconversionofclasstobasictype.Luckily,C++allowsustodefineanoverloaded casting operator that could be used to convert a class type to basic type. The general form of an overloaded casting operator function, usually referred to as a conversion function, is:

Page 125: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

115

operator typename(){ ……….. ……….. (function statements) ………..}

This function converts a class type data to typename. For example, the operator double()converts a class object double, the operator int() converts a class type object to type int, and so on.Consider the following conversion function:vector :: operator double(){ double sum = 0; for(int i=0; i<size; i++) sum = sum + v[i]*v[i]; return sqrt(sum);}

This functions converts a vector to the corresponding scalar magnitude (magnitude of a vector is given by the square root of the sum of the squares of its components). The operator double() can be used as follows:

double length = double(V1);Ordouble length = V1;where V1 is an object of type vector. Both the statements have exactly the same effect. When the complier encounters a statement that requires the conversion of a class type to a basic type, it quietly calls the casting operator function to do the job.

The casting operator function should satisfy the following conditions:It must be a class member•It must not specify a return type•It must not have any arguments•

Since it is a member function, it is invoked by the object and therefore, the values used for conversion inside the function belong to the object that invoked the function. This means that the function does not need an argument.

One class to another class typeThere are situations where we would like to convert one class type data to another class type. For example:

objX = objY; //objects of different types

objX is an object of class X and objY is an object of class Y. The class Y type data is converted to the class X type data and the converted value is assigned to the objX. Since the conversion takes place from class Y to classX, Y is known as the source class and X is known as the destination class.

Such conversions between objects of different classes can be carried out by either a constructor or a conversion function. The complier treats them the same way. Our decision to choose the form to use depends upon where we want the type-conversion function to be located in the source class or in the destination class. We know that the casting operator function

Operator typename()

Page 126: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

116

Convertstheclassobjectofwhichitisamembertotypename.Thetypenamemaybeabuit-intypeorauser-definedone. In case of conversions between objects, typename refers to the destination class. Therefore, when a class needs to be converted, a casting operator function can be used. The conversion takes place in the source class and the result is given to the destination class object.

Now consider a single-argument constructor function, which serves as an instruction for converting the argument’s type to the class type of which it is a member. This implies that the argument belongs to the source class and is passed to the destination class for conversion. This makes it necessary that the conversion constructor be placed in the destination class.

Page 127: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

117

SummaryOperatoroverloadingallowsexistingC++operatorstoberedefinedsothattheyworkonobjectsofuserdefined•classes.The advantage of operator overloading is that it moves the complexity from the many users to the few •servers. To overload an operator, we must specify its relationship to the class to which the operator is applied. This is •done with the help of a special function called operator function, which describes the task. Vector is a data type of class and may represent both magnitude and direction or a series of points called •elements.Theprocessofoverloadinginvolvesthefollowingsteps:createaclassthatdefinesthedatatypethatistobe•used in the overloading operation. Declare the operator function operator op() in the public part of the class. Itmaybeeitheramemberfunctionorafriendfunction,anddefinetheoperatorfunctiontoimplementtherequired operations.When constants and variables of different types are mixed in an expression, C applies automatic type conversion •to the operands as per certain rules. An assignment operation also causes the automatic type conversion. •The type of data to the right of an assignment operator is automatically converted to the type of the variable •on the left. Three types of situations might arise in the data conversion between incompatible types: conversion from basic •type to class type, conversion from class to basic type, and conversion from one class type to another class type.

ReferencesBalaguruswamy, E., 2006. • Object Oriented Programming with C++. 3rd ed., Tata McGraw Hill publishing company limited.Milea, A., 2009. • Operator overloading [online]. Available at: < http://www.cprogramming.com/tutorial/operator_overloading.html>. [Accesses on 18 April 2011].Devarticles.com, 2011. Operator overloading in C++ [online]. Available at: < http://www.devarticles.com/c/a/•Cplusplus/Operator-Overloading-in-C-plus/>. [Accesses on 18 April 2011].

Recommended ReadingBalagurusamy, E., 2006. • Object Oriented Programming with C++.3rd ed., Tata McGraw Hill Publishing Company Limited.Loudon, K., 2003. • C++ Pocket Reference. 1st ed., O’Reilly Media.Hubbard, J., 2000. • Schaum’s Outline of Programming with C++. 2nd ed., McGraw-Hill.

Page 128: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

118

Self AssessmentVector is a data type of class and may represent both, magnitude and direction or a series of points called 1. ________.

objectsa. functionsb. membersc. elementsd.

Which of the following statements is false?2. The constructor functions supports conversion of class to basic type. a. The conversion from basic type to class type is easy to accomplish.b. The mechanism used for overloading a unary operator is also used for overloading the binary operator. c. A minus operator when used as a unary takes just one operand.d.

To overload an operator we must specify what it means in ___________to the class to which the operator is 3. applied.

additiona. relationshipb. compatibilityc. supportd.

Operator overloading allows existing C++ operators to be redefined so that they work on objects 4. of_____________.

binarydefinedclassesa. operatordefinedclassesb. userdefinedclassesc. unarydefinedclassesd.

The advantage of operator overloading is that, it moves the ________from the many users to the few servers. 5. complexitya. simplicityb. compatibilityc. supportd.

Which of the following statement is true?6. C++allowsustodefineanoverloadedcastingoperatorthatcouldbeusedtoconvertaclasstypetoclassa. type. When the objects are of the same class type, the operations of subtraction and assignment are carried out b. smoothly and the complier does not make any complaints. The type of data to the right of an assignment operator is automatically converted to the type of the variable c. on the left. C++ has the ability to provide the operators with a special meaning for a object type.d.

Page 129: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

119

Binary operators overloaded through a member function take one explicit argument and those which are 7. overloaded through a _________function take two explicit arguments.

objecta. friendb. datac. classd.

Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit 8. values, but, those overloaded by means of a friend function, take one ___________argument.

referencea. classb. abstractc. memberd.

When using binary operators overloaded through a member function, the left hand operand must be an object 9. of the_________________.

member classa. function classb. data classc. relevant classd.

Sincetheuser-defineddatatypesaredesignedbyustosuitourrequirements,thecomplierdoesnotsupport10. ___________ type conversions for such data types.

manuala. automaticb. relevantc. explicitd.

Page 130: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

120

Chapter IX

Inheritance, Multiple Inheritance and Polymorphism

Aim

The aim of this chapter is to:

introduce the concept of inheritance•

definethederivedclasses•

discuss the features of inheritance•

Objectives

The objectives of this chapter are to:

introduce polymorphism•

explain the concept of single inheritance•

discusstheprocessofdefiningthederivedclass•

Learning outcome

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

understand the concept of multiple inheritance•

describe the single inheritance with the public as well as privation derivation•

define• the features of inheritance

Page 131: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

121

9.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 features specifictothenewlycreatedderivedclass.

Forexample,aprogrammercancreateabaseclassnamedfruitanddefinederivedclassesasmango,orange,banana,etc. Each of these derived classes, (mango, orange, banana, etc.) has all the features of the base class (fruit) with additionalattributesorfeaturesspecifictothesenewlycreatedderivedclasses.Mangowouldhaveitsowndefinedfeatures,orangewouldhaveitsowndefinedfeatures,bananawouldhaveitsowndefinedfeatures,etc.

Features of inheritance: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.•

9.2 Defining Derived ClassesAderivedclasscanbedefinedbyspecifyingitsrelationshipwiththebaseclassinadditiontoitsowndetails.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:

class ABC: private XYZ // private derivation{ members of ABC};

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.

9.3 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>using namespace std;

Page 132: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

122

class B{ 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;}void B :: show_a(){ cout << “a=” << a<< “\n”;}void D :: mul (){ c= b*get_a();}void D :: display (){ cout << “a = “ << get_a() << “\n”; cout << “b = “ << b << “\n”; cout << “c = “ << c << “\n”;}//-------------------------------------------------------------------------------------------------int main (){ D d; d.get_ab(); d.mul(); d.show_a(); d.display();

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

Page 133: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

123

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 that what it contains at the timeofdeclarationasshowninthefiguregivenbelow.

Class D

Private Section

Public SectionInheritedfrom B

C

b

Bget_ab()

get_a()

show_a()

mul()

display()

Fig. 9.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():void show_a(){ cout <<”a=” << a<< “\n”;}void mul()

Page 134: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

124

{ 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; void get_ab();void get_a(); void show_a();};

class D: private B // private derivation{ int c; public: void mul (); void display ();};

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

Page 135: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

125

Class D

Private Section

Public Section

Inheritedfrom B

C

b

Bget_ab()

get_a()

show_a()

mul()

display()

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

The statements such as

d.get_ab(); // get_ab is privated.get_a(); // so also get_a()d.show_a(); // and show_a()

will not work. However, these functions can be used inside mul() and display() like the normal functions as shown below:

void mul(){ get_ab(); c = b *get_a();}

void display (){ show_a() // outputs value of ‘a’ cout << “ b=” <<b<< “\n” << “c = “ <<c<<”\n\n”;}

Page 136: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

126

9.4 Multiple InheritancesAclasscaninherittheattributesoftwoormoreclassesasshowninthefiguregivenbelow.Thisisknownasmultipleinheritances. Multiple inheritances allow us to combine the features of several existing classes as a starting point for definingnewclasses.Itislikeachildinheritingthephysicalfeaturesofoneparentandtheintelligenceofanother.

B-1 B-2

D

B-n

Fig. 9.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) ……………….};

Where, visibility may be either public or private. The base classes are separated by commas.

For example:class P: public M, public N{ public: void display(void);};

ClassesMandNhavebeenspecifiedasfollows:

class M{ protected: int m;public : void get_m(int);};void M :: get_m(int x){ m = x;

Page 137: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

127

}class N{ protected:

int n; public: void get_n(int);};void N :: get_n(int y){ n=y;}

The derived class P, as declared above, would, in effect, contain all the members of M and N in addition to its own members as shown below:

class P{ protected

int m;int n;

// from M // from N

public:void get_m(int);void get_n(int);void display(void);

// from M // from N // own member};

Thememberfunctiondisplay()canbedefinedasfollows:

void P:: display(void){ cout << “m=”<<m<<”\n”; 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();}

Page 138: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

128

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

# include <iostream>Using namespace std;class M{ protected: int m; public: void get_m(int);};

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

class P : public M, public N{ public: void display(void);};

void M :: get_m(int x){ m = x;}

void N :: get_n(int y){ n=y};

void P :: display(void){ cout << “m= ” << m<< “\n”; cout << “n= ” << n<< “\n”; cout << “m*n = ” << m*n<< “\n”;}

int main (){ P p; p.get_m(10); p.get_m(20); p.display();

return 0;}

Page 139: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

129

Output of program is:

m = 10n = 20m*n = 200

9.5 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 complier at the compile time and, therefore, complier 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: void show () {…….} // show () in base class};class B : public A{ int y; public: void shoe () {……} // show () in derived class};

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. Ithappenswiththemechanismknownasvirtualfunctionasshowninthefigurebelow.

Page 140: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

130

Polymorphism

Compile timepolymorphism

Run timepolymorphism

Functionoverloading

OperatorOverloading

Virtualfunctions

Fig. 9.4 Polymorphism

At run time, when it is known what class objects are under consideration, the appropriate version of the function is invoked. Since the function is linked with a particular class much later than 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 141: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

131

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, which is known as multiple inheritances. Multiple •inheritancesallowustocombinethefeaturesofseveralexistingclassesasastartingpointfordefiningnewclasses. 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 publishing company limited.Pitts, R.I., 2000. • Introduction to Polymorphism in C++ [online]. Available at :< http://www.cs.bu.edu/teaching/cpp/polymorphism/intro/>. [Accessed on 18 April 2011]Tenoul.com. • C++ Object Oriented: Readme First [online]. Available at :< http://www.tenouk.com/cplusplustutorial.html>. [Accessed on 18 April 2011]

Recommended ReadingBalagurusamy, E., 2006. • Object Oriented Programming with C++. 3rd ed., Tata McGraw Hill Publishing Company Limited.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

Page 142: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

132

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

overriddena. overloadedb. object orientedc. inheritedd.

Multiple inheritance allows us to combine the features of several existing classes as a starting point for:2. definingnewobjectsa. definingnewfunctionsb. definingnewclassesc. definingnewmethodsd.

Which of the following statements is FALSE?3. Inheritance helps the code to be reworked in many situations. 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 143: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

133

____________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 144: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

134

Application I

Inheritance in C++Program below shows how to calculate volume of cube using the features of inheritance.1.

#include<iostream>using namespace std; class shape{ private : double length; protected: double breadth; public : double len() { return(length); } shape(double length1,double breadth1) { length=length1; breadth=breadth1; } //shape() { }}; class shape1{ public: double height; shape1(double height1) { height=height1; } //shape1() { }}; class cuboid : public shape, private shape1{ public: cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1) { cout << “ A constructor is called “ << endl; } double volume()

Page 145: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

135

{ return(height*breadth*len()); } double bre() { return(breadth); } double ht() { return(height); }}; int main(){ cuboid c1(2.4,3.5,6.7); cout << “The length of the cuboid is : “ << c1.len() << endl; cout << “The breadth of the cuboid is : “ << c1.bre() << endl; cout << “The height of the cuboid is : “ << c1.ht() << endl; cout << “The volume of the cuboid is : “ << c1.volume() << endl; return(0);}

Identify the lines in the program which states that class cuboid inherits class shape as public and class shape1 2. as private.Identify the lines in the program which declares the constructor of the class cuboid3.

AnswersOutput of the Program: 4.

class cuboid : public shape, private shape15.

cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1) { cout << “ A constructor is called “ << endl; }

Page 146: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

136

Application II

Classes and objects in C++Imagine a company that manufactures shoe boxes hires you to write a program that would help design and 1. identify those shoe boxes. What according to you would be the key aspects for designing the shoe boxes?2. Is the program applicable for one shoe box for every object?3.

Page 147: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

137

Application III

Exception handling in JavaWhat would be the output of the programs given below?1.

// File Name : ExcepTest.java

import java.io.*;

public class ExcepTest{

public static void main(String args[]){

try{

int a[] = new int[2];

System.out.println(“Access element three :” + a[3]);

}catch(ArrayIndexOutOfBoundsException e){

System.out.println(“Exception thrown :” + e);

}

System.out.println(“Out of the block”);

}

}

Is there anything wrong with the following exception handler as written? Will this code compile?2. try {

} catch (Exception e) { } catch (ArithmeticException a) { }

Is the following code legal?

try { }finally{ }

Page 148: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

138

Bibliography

ReferencesAndrew Mulholland, Glenn Murphy, 2003. • Java 1.4 Game Programming. Wordware Publishing.Balaguruswamy, E., 2006. • Object Oriented Programming with C++. 3rd ed., Tata McGraw Hill publishing company limited.Balaguruswamy, E., 2008. • Programming with Java - A Primer, 3/e. 7th ed., Tata McGraw Hill publishing company limited.C. Thomas Wu, 2009. • An Introduction to Object-Oriented Programming with Java. McGraw-Hill Higher Education.Classes and Objects in Java• , [online]. Available at:<http://docstore.mik.ua/orelly/java/javanut/ch03_01.htm>. [Accessed 8 April 2011]Devarticles.com, 2011. • Operator overloading in C++ [online]. Available at :< http://www.devarticles.com/c/a/Cplusplus/Operator-Overloading-in-C-plus/>. [Accesses on 18 April 2011].Exforsys Inc., 2007. • C++ Objects and Classes [online] (Updated on 3 February 2011). Available at :< http://www.exforsys.com/tutorials/c-plus-plus/c-plus-plus-objects-and-classes.html>. [Accessed on 15 April 2011].Huntrods, R.S., 2001. • Exception Handling in Java, [online]. Available at :< http://www.google.co.in/url?sa=t&source=web&cd=6&ved=0CEIQFjAF&url=http%3A%2F%2Fhuntrods.com%2Fteaching%2Fexceptions%2Fexceptions.ppt&rct=j&q=exception%20handling%20in%20java&ei=WWquTe_oJpD8vQO__q2GDw&usg=AFQjCNHNUEuhfQK7gwAN5FttP5FgEUeBKg&sig2=Tft21iWa3iGoVdK7h1RQrw&cad=rja>. [Accessed on 15 April 2011].Intap.net. • What is an object? [Online]. Available at :< http://www.intap.net/~drw/cpp/cpp06_01.htm>. [Accessed on 15 April 2011].Javabeginner.com, 2008, • Java Classes and Objects, [online]. Available at:< http://www.javabeginner.com/learn-java/java-classes-and-objects>. [Accessed 8 April 2011]Javabeginner.com, 2008, • Java inheritance, [online]. Available at :< http://www.javabeginner.com/learn-java/java-classes-and-objects>. [Accessed 8 April 2011]Javapassion.com, [online]. • Java Exception Handling. Available at :http://www.javapassion.com/javase/javaexceptions.pdf. [Accessed on 15 April 2011].Javapassion.com, • Polymorphism, [online]. Available at: <http://www.javapassion.com/javase/javapolymorphism.pdf>. [Accessed 12 April 2011]Lavender, G., 1999. • Inheritance in Java, [online] Available at:<http://www.cs.utexas.edu/~lavender/courses/tutorial/java-06.pdf>. [Accessed on 11 April 2011]Milea, A., 2009. • Operator overloading [online]. Available at : < http://www.cprogramming.com/tutorial/operator_overloading.html>. [Accesses on 18 April 2011].Msdn.microsoft.com, 2011, • C++ Exception Handling, [online]. Available at :< http://msdn.microsoft.com/en-us/library/4t3saedz.aspx>. [Accessed 15 April 2011]Nirosh, 2011, • Introduction to Object-Oriented Programming Concepts and More, [Online](Updated 25 January 2011) Available at < http://www.codeproject.com/KB/architecture/OOP_Concepts_and_manymore.aspx#Abstract > [Accessed 23rd March 2011].Pitts, R.I., 2000. • Introduction to Polymorphism in C++ [online]. Available at :< http://www.cs.bu.edu/teaching/cpp/polymorphism/intro/>. [Accessed on 18 April 2011]Tenoul.com. • C++ Object Oriented: Readme First [online]. Available at :< http://www.tenouk.com/cplusplustutorial.html>. [Accessed on 18 April 2011]Umbarger, D., 2008. • An Introduction to Polymorphism in Java, [online]. Available at:< http://apcentral.collegeboard.com/apc/public/repository/Intro_to_Polymorphismin_Umbargar.pdf>.[Accessed 12 April 2011]

Page 149: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

139

Williams, A., 2001. • Introduction to C++ Templates [online]. Available at :< http://www.justsoftwaresolutions.co.uk/articles/intrototemplates.pdf>. [Accessed 15 April 2011]Wu Thomas, 2009. • An Into To Oop with Java, 4E. Tata McGraw-Hill.

Recommended ReadingBalagurusamy, E., 2006. • Object Oriented Programming with C++. 3rd ed., Tata McGraw Hill Publishing Company Limited.Barnes, D.J. & Kolling, M., 2008. • Objects First With Java: A Practical Introduction Using BlueJ. 4th ed., Prentice HallBronson, G. J., 2005. Object• -Oriented Program Development Using Java: A Class-Centered Approach. 2nd ed., Course TechnologyCay S. Horstmann, Gary Cornell, 2001. • Core Java 2: Fundamentals. Prentice Hall PTR.David Barnes, David J. Barnes, 2000. • Object-oriented programming with Java: an introduction. Prentice Hall.Farrell. J.,2008. • Object Oriented Programming using C++, 4th ed., Course Technology, USA; Cengage Learning. P.794.Horstmann, C.S. & Cornell, G., 2007. • Core Java(TM), Volume I—Fundamentals. 8th ed., Prentice Hall.Hubbard, J., 2000. • Schaum’s Outline of Programming with C++. 2nd ed., McGraw-HillHunt, J., 2002. • Java and Object Orientation. 2nd ed., SpringerIbsen, C. & Anstey, J., 2011. Camel in Action. 1• st ed., Manning Publications.Josuttis, N.M., 2002. Object-Oriented Programming in C++. 1• st ed., WileyJulie Anderson, Hervé Franceschi, 2008. • Java 6 illuminated: an active learning approach. Jones & Bartlett Learning.Kak, A., 2003. • Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java. 1st ed.,Wiley-IEEE PressKoffman, 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.p.1040.Loudon, K., 2003. • C++ Pocket Reference. 1st ed., O’Reilly Media.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 MediaShaw, P., 2010. • Java inheritance FAQ (Code Style FAQ ebook series). 1st ed.,One Percent Better.Sierra, K., 2005. • Head First Java. 2nd ed., O’Reilly MediaStelting, S., 2004. • Robust Java: Exception Handling, Testing, and Debugging. Prentice HallStroustrup, B., 2000. • The C++ Programming Language: Special Edition. 3rd ed., Addison-Wesley ProfessionalStroustrup. B., 2002. • A Tour of C++ [Online](Updated 18January 2002]Available at < http://www.informit.com/articles/article.aspx?p=25003&seqNum=3 >. [Accessed 21 March 2011].Waldo, J., 2010. • Java: The Good Parts. 1st ed., O’Reilly Media.

Page 150: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

140

Self Assessment Answers

Chapter Ic1. a2. a3. b4. d5. a6. c7. a8. c9. d10.

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

Chapter IIIa1. d2. c3. b4. a5. b6. b7. c8. b9. d10.

Chapter IVa1. b2. d3. c4. c5. d6. b7. a8. a9. c10.

Page 151: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

141

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

Chapter VIa1. c2. a3. b4. c5. a6. a7. b8. d9. c10.

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

Chapter VIIId1. a2. b3. c4. a5. c6. b7. a8. b9. b10.

Page 152: Object Oriented Programming - Jaipur National Universityjnujprdistance.com/assets/lms/LMS JNU/B.Sc.(IT)/Sem...Object Oriented Programming 2 1.1 Introduction to OOP Object Oriented

Object Oriented Programming

142

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