Вы находитесь на странице: 1из 238

oppubb.

book Page 1 Tuesday, March 16, 2004 12:23 PM

2EMHFWRULHQWHG
Issue 2b, March 2004

&2%2/
REMHFWRULHQWHG
SURJUDPPLQJZLWKFRERO

oppubb.book Page 2 Tuesday, March 16, 2004 12:23 PM

Copyright 2004 Micro Focus International Limited.


All rights reserved.
Micro Focus International Limited has made every effort to ensure that this book is
correct and accurate, but reserves the right to make changes without notice at its sole
discretion at any time. The software described in this document is supplied under a
license and may be used or copied only in accordance with the terms of such license,
and in particular any warranty of fitness of Micro Focus software products for any
particular purpose is expressly excluded and in no event will Micro Focus be liable for
any consequential loss.
Animator, COBOL Workbench, EnterpriseLink, Mainframe Express,
Micro Focus, Net Express, REQL and Revolve are registered trademarks, and
AAI, Analyzer, Application to Application Interface, AddPack, AppTrack,
AssetMiner, CCI, DataConnect, Dialog System, EuroSmart, FixPack,
LEVEL II COBOL, License Management Facility, License Server,
Mainframe Access, Mainframe Manager, Micro Focus COBOL, Object COBOL,
OpenESQL, Personal COBOL, Professional COBOL, Server Express,
SmartFind, SmartFind Plus, SmartFix, SourceConnect, Toolbox, WebSync,
and Xilerator are trademarks of Micro Focus International Limited. All other
trademarks are the property of their respective owners.
No part of this publication, with the exception of the software product user
documentation contained on a CD-ROM, may be copied, photocopied, reproduced,
transmitted, transcribed, or reduced to any electronic medium or machine-readable
form without prior written consent of Micro Focus International Limited.
Licensees may duplicate the software product user documentation contained on a CDROM, but only to the extent necessary to support the users authorized access to the
software under the license agreement. Any reproduction of the documentation,
regardless of whether the documentation is reproduced in whole or in part, must be
accompanied by this copyright statement in its entirety, without modification.
U.S. GOVERNMENT RESTRICTED RIGHTS. It is acknowledged that the Software and the
Documentation were developed at private expense, that no part is in the public
domain, and that the Software and Documentation are Commercial Computer
Software provided with RESTRICTED RIGHTS under Federal Acquisition Regulations
and agency supplements to them. Use, duplication or disclosure by the U.S.
Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of The
Rights in Technical Data and Computer Software clause at DFAR 252.227-7013 et. seq.
or subparagraphs (c)(1) and (2) of the Commercial Computer Software Restricted
Rights at FAR 52.227-19, as applicable. Contractor is Micro Focus, 9420 Key West
Avenue, Rockville, Maryland 20850. Rights are reserved under copyright laws of the
United States with respect to unpublished portions of the Software.

20040316122346

oppubb.book Page 3 Tuesday, March 16, 2004 12:23 PM

Table of Contents
About this Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

11

Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Command Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Side Headings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

11
12
13

Part 1: Overview
1

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Object-oriented COBOL syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

17

Developing OO Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

18

What to Read Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19

Object-oriented Analysis and Design . . . . . . . . . . . . . . . . . . . . . . . .

19

OO Programming Concepts . . . . . . . . . . . . . . . . . . . 21
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

21

Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

22

Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23

Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

24

Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

25

Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

25

Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

26

Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

27

Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29

Object-oriented Programming with COBOL

oppubb.book Page 4 Tuesday, March 16, 2004 12:23 PM

Part 2: Object-oriented COBOL Programming


3

Using Objects in Programs . . . . . . . . . . . . . . . . . . . . 33


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Declaring Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Using Object References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Declaring Object References . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Manipulating Object References . . . . . . . . . . . . . . . . . . . . . . . . .
Object Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

35
35
36
37

Sending Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using the INVOKE Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Inline Method Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Invocation Using Object Properties . . . . . . . . . . . . . . . . . . . . . . .

38
39
39
40

Conformance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Creating a New Instance Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Destroying Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Object Destruction Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Finalized Object References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Class Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Method Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Data Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Files in OO Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Programming Factory Object Behavior . . . . . . . . . . . . . . . . . . . . . . .
Factory Object Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Class Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Factory Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

56
56
57
57

Programming Instance Object Behavior . . . . . . . . . . . . . . . . . . . . . .


Instance Data. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Instance Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Instance Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

58
58
59
60

Object-oriented Programming with COBOL

oppubb.book Page 5 Tuesday, March 16, 2004 12:23 PM

Parameterized Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

60

Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

65

Method Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

65

Predefined Object Reference Names . . . . . . . . . . . . . . . . . . . . . . . .

67

Instance Creation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

69

Get and Set Property Methods . . . . . . . . . . . . . . .


PROPERTY Clause in a Data Item Definition .
PROPERTY Clause in a Method Definition . . .
Coding the Object Property Syntax . . . . . . . .

71
72
72
73

......
......
......
......

........
........
........
........

Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

75

Interface Source Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

75

Interface Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

77

Parameterized Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

78

Compiling and Debugging OO COBOL Applications 81


Compiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Compiler Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Directly Inherited Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

81
81
83

Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Preventing Reallocation of Object Handles . . . . . . . . . . . . . . . .
Finding Memory Leaks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Object Data Guard Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

84
84
85
86

Message Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

87

Troubleshooting Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Memory Exceptions and Protection Violations on Method
Invocations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Symbol Redefined . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Program Not Found . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

89
89
90
90

Object-oriented Programming with COBOL

oppubb.book Page 6 Tuesday, March 16, 2004 12:23 PM

Part 3: Tutorials
8

Objects and Messages Tutorial . . . . . . . . . . . . . . . . . 95


The Stopwatch Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Sending Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100

Simple Class Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . 101


Structure of a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Identifying a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Identifying Classes Used by a Program . . . . . . . . . . . . . . . . . . . .
The Factory Object Source Element . . . . . . . . . . . . . . . . . . . . . . .
Factory Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
The Instance Object Source Element . . . . . . . . . . . . . . . . . . . . . .
Instance Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

101
102
102
103
103
104
105

Animating the Stopwatch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106


Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

10 More Complex Class Tutorial . . . . . . . . . . . . . . . . . . 111


The Personnel Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Exploring the Personnel Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Animating the Personnel Application . . . . . . . . . . . . . . . . . . . . . . . . 114
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

11 Interfaces and Parameterized Class Tutorial . . . . . . 119


The PClass Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Exploring the Pclass Classes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Animating the Pclass Application. . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

Object-oriented Programming with COBOL

oppubb.book Page 7 Tuesday, March 16, 2004 12:23 PM

Part 4: Micro Focus OO COBOL Alternatives and


Extensions
12 Micro Focus OO COBOL Alternative Syntax . . . . . . 127
Summary of Syntax Alternatives . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Shared Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Working-Storage Section in a Method . . . . . . . . . . . . . . . . . . . . . . . 129
Working Storage and Object Storage . . . . . . . . . . . . . . . . . . . . . . . . 129
Data Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Direct Data Inheritance in Source Code . . . . . . . . . . . . . . . . . . . 130
Direct Data Inheritance at Run Time . . . . . . . . . . . . . . . . . . . . . 132
Extending a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

13 Requirements-based Vocabulary . . . . . . . . . . . . . . . 137


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Defining a Vocabulary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
External Class Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Method Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
User-defined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

138
138
139
141

Using Vocabulary-defined Verbs and Functions . . . . . . . . . . . . . . . . 141

Part 5: Micro Focus Class Libraries


14 Introduction to the Class Libraries . . . . . . . . . . . . . . 145
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Public and Private Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Class Library Method Parameter Types . . . . . . . . . . . . . . . . . . . . . . . 147
Class Library Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Frameworks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Animating the Class Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

Object-oriented Programming with COBOL

oppubb.book Page 8 Tuesday, March 16, 2004 12:23 PM

15 Collection Frameworks . . . . . . . . . . . . . . . . . . . . . . . 151


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Different Categories of Collection . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Working with CharacterArray Objects. . . . . . . . . . . . . . . . . . . . .
Creating a CharacterArray Object . . . . . . . . . . . . . . . . . . . . . . . .
Querying a CharacterArray Object. . . . . . . . . . . . . . . . . . . . . . . .

152
153
154
156
156
157

Comparison Between Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158


Equality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Relative Value of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Hashing Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Display Mechanisms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Using the display Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Display on a Listbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Collection Sort Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Iterator Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

16 Intrinsic Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Using Intrinsic Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Cloning an Intrinsic Data Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Sending a Message to an Intrinsic Data Type . . . . . . . . . . . . . . . 167
Writing New Intrinsic Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Code for an Intrinsic Class Object. . . . . . . . . . . . . . . . . . . . . . . . . 168
Code for an Intrinsic Instance Object. . . . . . . . . . . . . . . . . . . . . . 169

17 Callback Frameworks . . . . . . . . . . . . . . . . . . . . . . . . 173


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Using Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Creating a Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Invoking a Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

Object-oriented Programming with COBOL

oppubb.book Page 9 Tuesday, March 16, 2004 12:23 PM

18 Exception Handling Frameworks . . . . . . . . . . . . . . . 177


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Creating an Error Message File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Registering an Exception Message File . . . . . . . . . . . . . . . . . . . . . . . 179
Raising an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
Providing Your Own Exception Handlers . . . . . . . . . . . . .
Writing Exception Handler Methods . . . . . . . . . . . . .
Registering an Object with the Exception Handler . .
Canceling an Exception Registration . . . . . . . . . . . . .

.......
.......
.......
.......

.
.
.
.

182
183
185
185

Replacing the System Exception Method . . . . . . . . . . . . . . . . . . . . . 185

19 Component Frameworks. . . . . . . . . . . . . . . . . . . . . . 187


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Defining Output Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
Defining Input Sockets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Connecting Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Sending Signals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

Part 6: Micro Focus OO COBOL Tutorials


20 Inheritance Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . 197
The Account Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Simple Account Transactions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202

21 Collections, Intrinsics and Dictionaries Tutorial. . . . 203


Collections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Using Intrinsics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Iterator Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213

Object-oriented Programming with COBOL

oppubb.book Page 10 Tuesday, March 16, 2004 12:23 PM

10

22 Exception Handling Tutorial . . . . . . . . . . . . . . . . . . . 215


Raising an Exception . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Registering an Exception Handler . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Writing an Exception Handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222

23 Requirements-based Vocabulary Tutorial . . . . . . . . 223


Introducing the Vocabulary Example . . . . . . . . . . . . . . . . . . . . . . . . . 223
Using Requirements-based Vocabulary . . . . . . . . . . . . . . . . . . . . . . . 225
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

Part 7: Appendices
A Descriptions of OO Run-time Switches . . . . . . . . . . 229
List of Switches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

Object-oriented Programming with COBOL

oppubb.book Page 11 Tuesday, March 16, 2004 12:23 PM

11

About this Book


This book explains how to do object-oriented programming in COBOL,
using ISO 2002 COBOL, Micro Focus OO extensions or a mixture of
both. It includes explanations of concepts, programming tutorials,
programming documentation and information about the Micro Focus
class libraries.

Audience
You should be familiar with the COBOL language and with your
operating system. You should read the Getting Started book and be
familiar with the COBOL development cycle described in your
documentation.

Notation
The notation used in the books is as follows:

Enter refers to the carriage-return or Enter key. Where commands


to be typed are shown, the Enter key is not shown. It is treated as
implicit that the Enter key must be pressed at the end of the line.

Hexadecimal numbers are enclosed in quotation marks and


preceded by a lower-case "x" or "h"; for example, x"9D", h"03FF".
The "x" is used when the hexadecimal number represents a
character string; the "h" when it represents a numerical value.

With COMP-X and COMP-5, PIC X is used rather than PIC 99. Unlike
PIC 99, PIC X shows the length of the data item directly and so
demonstrates more clearly the use of COMP-X, which is to define a
binary item of the specified number of bytes.

Object-oriented Programming with COBOL

oppubb.book Page 12 Tuesday, March 16, 2004 12:23 PM

12

About this Book

Command Lines
The notation used to describe the format of command lines is as
follows:

Words printed in italics are generic terms representing names to be


devised by you.

Words printed in nonitalic characters are the actual words you must
enter.

Windows:

On Windows you can type them in upper, lower, or mixed case


except where otherwise stated.

UNIX:

On UNIX you must type them in upper or lower case as shown.

Square brackets [ ] mean the material inside them is optional.

Braces { } mean you must choose from the options inside them. If
there is only one option in the braces, they mean repetition.

An ellipsis (...) following { } or [ ] means you can repeat the material


inside them. The number of repetitions allowed is unlimited unless
otherwise stated. Square brackets [ ] with an ellipsis mean you can
omit the material altogether.

If a command line does not fit across the page, it is continued on the
next line; the continuation line is indented.

Server Express:

On UNIX, all command line formats and examples are for the
standard UNIX shell, the Bourne shell. If you are using another shell,
see your UNIX documentation for the appropriate formats.

Server Express:

Where examples showing environment variables do not specifically


show them being exported to the shell, it is treated as implicit that
they are exported.

Server Express:

Some keystrokes using function keys or the Alt or Ctrl keys are not
available on all UNIX platforms. The Users Guide contains a UNIX
Key Usage Chart, listing how the keystrokes shown in the books
map onto actual keystrokes.

Object-oriented Programming with COBOL

oppubb.book Page 13 Tuesday, March 16, 2004 12:23 PM

Notation

Side Headings
In a generic book or chapter, text that does not apply to all supported
environments and COBOL systems is marked by a side heading in the
left margin. A side heading applies to the paragraph it is next to, unless
it is next to the first paragraph in a section, in which case it applies to
that whole section.
The following examples of side headings show what they mean:
Server Express:
Net Express:

This text applies to Server Express on UNIX.


This text applies to Net Express on Windows.

Object-oriented Programming with COBOL

13

oppubb.book Page 14 Tuesday, March 16, 2004 12:23 PM

14

About this Book

Object-oriented Programming with COBOL

oppubb.book Page 15 Tuesday, March 16, 2004 12:23 PM

15

Part 1: Overview
This part contains the following chapters:

Chapter 1, Introduction

Chapter 2, OO Programming Concepts

Object-oriented Programming with COBOL

oppubb.book Page 16 Tuesday, March 16, 2004 12:23 PM

16

Part 1: Overview

Object-oriented Programming with COBOL

oppubb.book Page 17 Tuesday, March 16, 2004 12:23 PM

17

1 Introduction
This chapter introduces the facilities for object-oriented programming
provided in your COBOL system, and explains how to use this book to
begin OO programming with COBOL.

Object-oriented COBOL syntax


Your COBOL system enables you to do object-oriented (OO)
programming in COBOL, while still retaining all the syntax and features
previously available. Your COBOL system supports:

Syntax that conforms to the ISO 2002 COBOL standard

Micro Focus alternatives and extensions to the ISO 2002 COBOL


standard

You can choose to just use ISO 2002 syntax, or you can use ISO 2002
and Micro Focus syntax, mixing them in the same program. However,
we recommend that you use the ISO 2002 syntax if you want your
programs to be portable to platforms that do not support Micro Focus
COBOL.
The chapters in Parts 1, 2 and 3 of this book use the ISO 2002 syntax
and related terminology. Micro Focus alternatives and extensions are
generally mentioned when a new piece of syntax is introduced.
The chapters in Parts 4, 5 and 6 of this book use the Micro Focus syntax
and related terminology. The main differences between ISO 2002 and
Micro Focus OO COBOL are listed in the chapter Micro Focus OO COBOL
Alternative Syntax, in Part 4.

Object-oriented Programming with COBOL

oppubb.book Page 18 Tuesday, March 16, 2004 12:23 PM

18

Chapter 1 Introduction

Developing OO Programs
Development starts with the analysis of the problem and the design of a
program or programs that solve the problem. Object-oriented design
involves identifying the objects that you want to work with and what
they need to do. Object-oriented analysis and design lie outide the
scope of this book; for a reading list, see the section Object-Oriented
Analysis and Design.
When you reach the design phase, you can make use of the Micro Focus
class libraries, as long as you do not want to port your programs to
platforms that do not support Micro Focus COBOL. A class library is a
collection of ready-made objects that you can use in your programs. (For
definitions of the terms class and object see the chapter OO
Programming Concepts.) More information on the Micro Focus class
libraries is available in the chapter Introduction to the Class Libraries.
ISO 2002 COBOL also provides a class library. However, it includes far
fewer classes than the Micro Focus class libraries.
When you start coding your program you will be on familiar territory,
using your usual development environment tools such as the Editor and
Animator.
Net Express:

Net Express provides features that help you specifically with OO


development:

Wizards that you can use to create new programs

The ability to search for OO programming constructs in the Browse


tool (click Search > Browse).

An OO COBOL tool bar that helps you to develop and maintain OO


COBOL code quickly and easily

If you use both Net Express and Server Express, you can develop and
debug your application on Net Express, and transfer the code to a
Server Express platform for production. OO COBOL code is portable
between Net Express and Server Express, except for code developed for:

GUI programming

COM components

Object-oriented Programming with COBOL

oppubb.book Page 19 Tuesday, March 16, 2004 12:23 PM

What to Read Next

What to Read Next


We advise you to start by reading the chapter OO Programming
Concepts which provides an introduction to object-oriented
programming concepts and terminology.
When you are ready to find out more about coding in object-oriented
COBOL, move onto Parts 2 and Part 3. Part 2 contains more detailed
information about object-oriented programming, specifically in COBOL,
while Part 3 contains some tutorials. If you want to go straight to the
tutorials, we recommend that you try only the tutorials described in the
chapters Objects and Messages Tutorial and Simple Class Tutorial,
before returning to Part 2, starting with the chapter Using Objects in
Programs. All the chapters in Parts 2 and 3 use the ISO 2002 OO COBOL
syntax and terminology.
The chapters in Parts 4, 5 and 6 all relate to features and facilities of
Micro Focus COBOL and use the Micro Focus OO COBOL syntax and
terminology. Part 4 describes Micro Focus syntax that provides
alternatives and extensions to the ISO 2002 syntax. Part 5 is devoted to
the Micro Focus class libraries; start with the chapter Introduction to the
Class Libraries. Part 6 contains tutorials that use Micro Focus alternatives
and extensions to the ISO 2002 syntax.

Object-oriented Analysis and Design


The documentation supplied with your COBOL system will help you to
start programming in OO COBOL. However, if you are new to OO,
learning about the principles of Object-Oriented Design and Analysis
(OOD and OOA) will enable you to make the best use of this new
technology.
The reading list below suggests some books dealing with objectoriented methodologies and technologies.
Booch, Grady. Object-Oriented Design. Benjamin/Cummings, 1994.
ISBN: 0-8053-0091-0.
Jacobson , Ivor. Object-Oriented Software Engineering.
Addison-Wesley, 1992. ISBN: 0-201-54435-0.

Object-oriented Programming with COBOL

19

oppubb.book Page 20 Tuesday, March 16, 2004 12:23 PM

20

Chapter 1 Introduction

Rumbaugh. James. Object-Oriented Modeling and Design.


Prentice Hall, 1991. ISBN: 0-13-629841-9.
Shlaer, Sally and Mellor, Steve. Object-Oriented Systems Analysis:
Modeling the World in Data. Prentice Hall, 1988. ISBN: 0-13-629023-1
and Object Lifecycles: Modeling the World in States. Prentice Hall, 1992.
ISBN: 0-13-629940-7
Taylor, David. Object Oriented Information Systems: Planning and
Implementation. John Wiley, ISBN: 0-471-54364-0.
Wirfs-Brock, Rebecca. Designing Object-oriented Software .
Prentice Hall, 1990. ISBN: 0-13-629825-7.
There are also several training organizations that run languageindependent courses on OOD and OOA.

Object-oriented Programming with COBOL

oppubb.book Page 21 Tuesday, March 16, 2004 12:23 PM

21

2 OO Programming Concepts
This chapter describes the key concepts supported by an objectoriented programming language, and how they are implemented by
Micro Focus COBOL. Micro Focus COBOL supports the ISO 2002
standard for Object-Oriented COBOL (OO COBOL) and supplies some
additional OO facilities.

Overview
OO COBOL provides the following elements, which are typical of any
OO programming language:

Objects

Classes

Methods

Interfaces

Messages

These together provide the three characteristics that define an OO


language:

Encapsulation

Inheritance

Polymorphism

The following sections describe these elements and characteristics in


turn, and how they are implemented in OO COBOL.

Object-oriented Programming with COBOL

oppubb.book Page 22 Tuesday, March 16, 2004 12:23 PM

22

Chapter 2 OO Programming Concepts

Objects
An object is a combination of data and the procedures to operate on
that data. The data is known as the objects attributes, and the
procedures are known as its methods. Every object in an object-oriented
application has a unique object identifier, allocated to it at creation and
fixed for its lifetime.
Objects hold data, but they do not replace files and databases. The data
in an object exists only during the lifetime of the object. Objects are
created and destroyed by object-oriented applications.
Many of the objects in an OO application represent objects in the real
world. For example, a banking system would include objects to
represent customers, accounts and ledgers. The attributes of an account
would include the balance, and its methods would include Debit, Credit,
GetBalance. Figure 2-1 shows two ways of representing such an object.
Figure 2-1. An Object

The user of an object can only find out about or change its attributes by
making requests to the object. These requests are known as messages,
and each message invokes a method supported by the object. The
object interface is a description of all the messages to which the object
responds. For example, to find out the balance of an account, you
would send an account object the message GetBalance.
The actual representation of the data is known only to the object. As
long as the object interface remains the same, a programmer can

Object-oriented Programming with COBOL

oppubb.book Page 23 Tuesday, March 16, 2004 12:23 PM

Classes

change the internals of how the object represents and operates on


data, without affecting the rest of the system.

Classes
A class is a definition of an object; it embodies all the information you
need to create and manipulate objects of a particular type. An account
class defines account objects and a ledger class defines ledger objects.
An account object is said to be an instance of the account class, or an
instance object, or simply an instance.
A class is a programming language construct, while an object is an
entity that exists in memory at run time.
A class not only defines an instance object; it also defines a factory
object. The factory object defines the classs own data and behavior.
The class does not have the same behavior as the instances it creates. A
class is like a printers plate, printing identical forms. A plate enables
you to print a form, but is not a form itself.
The main function of the factory object is to create new instance
objects, but it can also contain data and methods that are shared by all
instance objects. For example, the factory object of an account class
could include a data item for keeping a count of the number of account
objects created.
In OO COBOL, a class is a COBOL source element, which consists of a set
of nested source elements, including source elements for the factory
object and the instance object. The factory source element contains all
the attributes and methods specific to the factory object. The object
source element contains the attributes and methods specific to all
instance objects. Figure 2-2 shows a class and instances being created
from it.

Object-oriented Programming with COBOL

23

oppubb.book Page 24 Tuesday, March 16, 2004 12:23 PM

24

Chapter 2 OO Programming Concepts

Figure 2-2. A Class and Instances Created From It

Note: Micro Focus COBOL provides alternative terminology and


features:

The equivalent of a factory object is the class object.

The top-level source element for the class can contain data that is
common to all instance objects and the class object

Methods
Methods are the pieces of code that implement the behavior of an
object. In OO COBOL, each method is a separate source element nested
within the factory or object source element. An object method can
access its own data, the instance data and the factory data declared in

Object-oriented Programming with COBOL

oppubb.book Page 25 Tuesday, March 16, 2004 12:23 PM

Interfaces

the factory object source element. A factory method can access its own
data and the factory data.
Methods can be incomplete; these are known as method prototypes. A
method prototype does not contain any code, just a heading and an
end-marker. A method prototype is always fully implemented
elsewhere in the application; for an explanation of the benefits of using
method prototypes see the section Interfaces.

Interfaces
Interfaces are collections of method prototypes. The set of method
prototypes defines a common behavior that a variety of objects might
share. For example, you might have an interface Rentable, that defines
methods appropriate for objects that people can rent, such as cars and
video tapes. The Car class is a subclass of the Vehicle class, while the
VideoTape class is a subclass of the VideoRecording class, but both Car
and VideoTape implement the Rentable interface. The interface
methods might include pickUp and dropOff. These are defined as
prototypes in the interface. Each class that implements the interface
must provide full method definitions for the method prototypes in the
interface.
Interfaces give you additional flexibility in designing your OO
applications; they are one of the elements in an OO language that
provide polymorphism (see the section Polymorphism).

Messages
A message is the way you request an object to perform a service. A
message always consists of the following:

Object reference

Method selector

Object-oriented Programming with COBOL

25

oppubb.book Page 26 Tuesday, March 16, 2004 12:23 PM

26

Chapter 2 OO Programming Concepts

Messages may also optionally contain input and output parameters.


Where there is an output parameter, the sender will be expecting a
reply to its message.
The object reference enables the run-time system to find the object for
which the message is intended. The target of a message is known as the
receiver. The COBOL run-time system uses dynamic binding to
determine the receiver of a message. This means that the receiver of a
message is determined at run time rather than at compile time.
The method selector is the text of the message; it tells the receiver
which method it should invoke. OO COBOL uses the INVOKE verb to
send messages. Figure 2-3 shows the components of a message both
diagramatically and in OO COBOL syntax.
Figure 2-3. A Message

Encapsulation
Encapsulation in OO langauges is the inclusion within an object of
everything it needs to function: its data and the implementation of its
methods. Other objects can use it as long as they adhere to the objects
interface; they do not need to know anything about the way the object
holds and manipulates its data. Encapsulation helps to preserve the
integrity of data.

Object-oriented Programming with COBOL

oppubb.book Page 27 Tuesday, March 16, 2004 12:23 PM

Inheritance

Inheritance
Inheritance enables OO languages to mirror the real world more closely
by establishing hierarchies of classes. Most objects in the real world
belong to specific categories; for example, cars and motor bikes are
vehicles, managers and workers are employees. Using inheritance in OO
applications reduces coding effort, because you only need to include
methods in a subclass if the required behavior is different from that
provided in the superclass. When you create a method in a subclass of
the same name as a method in the class it inherits from, the method in
the subclass overrides the method in the class; the method in the
subclass is known as a reimplementation of the method in the class.
For example, our banking application might handle the following types
of account: checking accounts, credit card accounts and savings
accounts. There are some features that all these accounts have in
common; a balance attribute, methods credit, debit and getBalance. But
there are also differences; a savings account pays interest, while a
checking account may allow overdrafts.
An Account class implements all the methods and attributes common to
all its subclasses. The subclasses implement the attributes and methods
which they uniquely require.
A deposit account implements its own version of Debit that does not
allow overdrafts. Figure 2-4 shows a possible inheritance hierarchy for
bank accounts.
Figure 2-4. Bank Account Inheritance

Object-oriented Programming with COBOL

27

oppubb.book Page 28 Tuesday, March 16, 2004 12:23 PM

28

Chapter 2 OO Programming Concepts

Inheritance makes subsequent updates easier, because you can add new
subclasses as required. For example, the bank might introduce two new
types of savings account: an instant access account, and a high interest
account where you have to give notice of a withdrawal. These could be
subclassed from the Savings Account class, with additions to provide the
new behavior required. Because they still respond to the message
interface used by all account objects, the changes do not ripple through
the rest of the system.
Micro Focus COBOL comes with a number of class libraries. All the
classes in the Base Class Library are ultimately descended from class
Base. Base provides methods which are required by all classes, which
include methods for creating and destroying objects. The classes you
write are also likely to be subclasses of Base. You can create your own
root class and subclass from that, but you may need to duplicate some
of the services provided by Base.
In OO COBOL, a factory of a subclass has access to all the factory
methods of its superclasses. An instance of a subclass has access to all
the object methods of its superclasses.
OO COBOL provides multiple inheritance; this means that in addition to
a subclass inheriting all the methods of the classes above it in the
hierarchy, it can also inherit directly from more than one class. This is
illustrated in Figure 2-5.
Figure 2-5. Multiple Inheritance

Object-oriented Programming with COBOL

oppubb.book Page 29 Tuesday, March 16, 2004 12:23 PM

Polymorphism

Many OO languages, including OO COBOL, also provide interface


inheritance. This enables you to build up hierarchies of interfaces.
Interface inheritance, like class inheritance, helps to reduce coding
effort.

Polymorphism
Polymorphism is an important part of any object-oriented programming
language. Polymorphism means that the same message sent to different
objects can invoke different methods.
Polymorphism is provided by two mechanisms in OO COBOL:

Inheritance
Where a number of subclasses inherit from a class, the methods in
the class can be method prototypes, that is methods that dont
contain any code. Complete methods of the same name appear in
each subclass, and these can be different.

Interfaces
Interfaces are collections of methods applicable to a variety of
objects. Again, the methods in the interface are prototypes. If a
class implements an interface, it must provide complete methods of
the same name, and these methods can differ between classes that
implement the same interface.

For example, consider a graphics drawing system that has objects


representing squares and objects representing circles. Circle objects and
square objects both have the method draw, either because both are
descended from a class that has the method draw, or because both
implement an interface Drawable that has the method draw. The code
for drawing squares and circles are different, but the display controller
can send the message draw to any graphical object, without caring
what type it is. The receiver of the message will execute its own draw
method, producing the correct result (see Figure 2-6).

Object-oriented Programming with COBOL

29

oppubb.book Page 30 Tuesday, March 16, 2004 12:23 PM

30

Chapter 2 OO Programming Concepts

Figure 2-6. Polymorphism

Object-oriented Programming with COBOL

oppubb.book Page 31 Tuesday, March 16, 2004 12:23 PM

31

Part 2: Object-oriented
COBOL Programming
This part contains the following chapters:

Chapter 3, Using Objects in Programs

Chapter 4, Classes

Chapter 5, Methods

Chapter 6, Interfaces

Chapter 7, Compiling and Debugging OO COBOL


Applications

Object-oriented Programming with COBOL

oppubb.book Page 32 Tuesday, March 16, 2004 12:23 PM

32

Part 2: Object-oriented COBOL Programming

Object-oriented Programming with COBOL

oppubb.book Page 33 Tuesday, March 16, 2004 12:23 PM

33

3 Using Objects in Programs


This chapter describes how you can use objects in programs. It uses
examples of code to illustrate points. For full syntax definitions, see
your Language Reference.

Overview
Objects can be used by an application which is not itself objectoriented. The same rules apply whether the program you write is an
OO COBOL class, or a procedural COBOL program in which you want to
use COBOL objects.
Programs that use objects all have certain features in common:

They have a Repository paragraph.


This lists all the classes and interfaces the program is going to use. If
the program itself is an OO COBOL class, the Repository paragraph
also lists its superclass.
Micro Focus COBOL provides alternative syntax; see the section
Summary of Syntax Alternatives in the chapter Micro Focus OO
COBOL Alternative Syntax.

They declare one or more data items of type OBJECT REFERENCE.


An object reference data item holds an object handle, that is, a
pointer to the location of the object in memory.. The run-time
system assigns a unique object handle to every single object active
in your application. An object handle enables you to send messages
to the object.

They send messages.


When you send a message to an object, you invoke a method inside
the object. Some methods receive or return parameters; when you
invoke the method you include the parameters as part of the
message.
Object-oriented Programming with COBOL

oppubb.book Page 34 Tuesday, March 16, 2004 12:23 PM

34

Chapter 3 Using Objects in Programs

Generally, a program that uses objects sends a message to one or more


factory objects to create the instance objects it requires. For each
instance object created, you must declare an object reference to hold
the object handle, although you may overwrite the object handle in an
object reference with a new one if you have finished with it. When a
program has finished with an object, it should destroy it.

Declaring Classes
If you want to use an object in a program, you must declare the objects
class in the programs Repository paragraph. This prompts the Compiler
to obtain information about the class from the external repository,
which is an area where information about classes and interfaces is held.
The availability of the external repository enables conformance
checking to take place (see the section Conformance). Information
about classes is added to the external repository when a class is
compiled.
The CLASS clause also:

Creates a data item for each class named. At run time, this data item
holds an object handle to the factory object.

Enables the run-time system to find and load the file with the class
executable code.
A class is guaranteed to be loaded before the factory object receives
its first message. Usually this occurs when you send the first message
to the factory object, but before the factory object receives it.

When you declare a class, it effectively makes the classs factory object
available. The class names in the Repository paragraph are
automatically declared as object reference data items. This enables you
to send messages to the factory object.
The code below shows class registration for classes CharacterArray and
Employee:
repository.
class CharacterArray as "chararry"
class Employee

Object-oriented Programming with COBOL

oppubb.book Page 35 Tuesday, March 16, 2004 12:23 PM

Using Object References

If you code the AS clause, the Compiler uses the value of the literal as
the external name of the class program; otherwise it uses the class name
changed to upper case. If you are writing a class, you do not have to
include a CLASS clause for the class you are writing; if you do include
one, the Compiler ignores it and uses the class name or literal in the
Class-ID paragraph in the Identification Division.
Micro Focus COBOL provides alternative syntax; see the section
Summary of Syntax Alternatives in the chapter Micro Focus OO COBOL
Alternative Syntax.

Using Object References


An object reference can hold a handle to a factory or instance object.
Depending on the syntax you use, object references are untyped or
typed. An untyped object reference data item can hold an object
reference for any factory or instance object. Untyped object references
are also known as universal object references. A typed object reference
can only hold an object reference of the type specified by the syntax.
It is good programming practice to use typed object references rather
than untyped; this is because they allow the Compiler to perform its
conformance checking, which tends to lessen the number of run-time
errors that occur. For more information on conformance checking see
the section Conformance.

Declaring Object References


You need to declare data items of type OBJECT REFERENCE to hold
handles to any objects you will be using.
For example:
01
01
01
01

anObject
usage object reference.
secdObject usage object reference factory of BankAccount.
thirdObject usage object reference active-class.
fourthObject usage object reference Rentable.

The first line defines an untyped or universal object reference.

Object-oriented Programming with COBOL

35

oppubb.book Page 36 Tuesday, March 16, 2004 12:23 PM

36

Chapter 3 Using Objects in Programs

The second, third and fourth lines define typed object references:

The secondObject data item can hold a handle only to the factory
object of the class BankAccount or a subclass of that class.

The thirdObject data item can hold a handle only to an object of the
active class, that is, the class in which this data description appears
(either in the factory source element or the object source element),
or any subclass of that class. Object references of type active-class
cannot appear in procedural COBOL programs.

The fourthObject data item can hold a handle only to an object that
implements the Rentable interface. Interfaces are collections of
method prototypes that define behavior; for more information
about interfaces and how objects implement them see the chapter
Interfaces.

You do not need to declare object references for the factory objects of
the classes you are going to use in your program. These are declared
automatically when you list your classes in the Repository paragraph.

Manipulating Object References


The only direct operations you can use on object references are:

Send a message to the object represented by the handle in the


object reference. For example:
invoke anObject "message"

Copy an object reference to another. For example:


set anObject1 to anObject2

Test whether two object references refer to the same object. For
example:
if anObject1 = anObject2 ...

Micro Focus
Extension

Test whether an object reference refers to an object of a particular


class. For example:
if anObject1 instance of ClassA ...

Object-oriented Programming with COBOL

oppubb.book Page 37 Tuesday, March 16, 2004 12:23 PM

Using Object References

No other operations are valid, because the object reference contains


only a handle to an object. To change or interrogate an objects internal
state, you have to send messages to it.
If you clear all references to a particular object, you will be unable to
send that object any more messages. In particular, you will not be able
to destroy that object and deallocate its storage (see the section
Destroying Objects ).
You can pass object references as parameters when you send a message
or make a COBOL CALL, in effect enabling you to pass objects between
different parts of an application.

Object Views
You can copy object references from one data item to another using the
SET statement, but only if the receiving object reference is to a subclass
of the class of the sending object reference. For example, if classes
circle, triangle and rectangle all inherit from class shape, the following
code is valid:
01 obj1 usage object
01 obj2 usage object
01 obj3 usage object
01 obj4 usage object
...
set obj1 to obj2
set obj1 to obj3
set obj1 to obj4

reference
reference
reference
reference

class
class
class
class

shape.
circle.
triangle.
rectangle.

This syntax enables polymorphism; in this example you use it in order to


execute the right methods for the particular shape you are processing,
for example the method for calculating its area.
However, the following code is not valid:
set obj2 to obj1

This is because obj1 might not be pointing to a circle object. However,


you might know that there are certain points in your program where
obj1 does point to a circle object. Object views enable you to exploit this
knowledge. In this example, you would recode your SET statement as
follows:
set obj2 to obj1 as circle

Object-oriented Programming with COBOL

37

oppubb.book Page 38 Tuesday, March 16, 2004 12:23 PM

38

Chapter 3 Using Objects in Programs

This statement will be accepted at compile time. The presence of the


object view "as circle" signals to the run-time system that it must check
that obj1 is actually pointing to an object of class circle, before
executing the statement. If the check fails, you get a run-time error.
The object view syntax also provides:

A FACTORY clause, which asks the run-time system to check that the
object reference is pointing to the factory object of the class.

An ONLY phrase, which asks the run-time system to check that the
object reference is pointing to an object of that class only and not
any subclass.

An option to specify an interface name as an alternative to a class


name. If you specify an interface name, the run-time system checks
that the object reference is pointing to an object that implements
that interface

A UNIVERSAL clause, which causes the object reference to be


treated as universal.

Sending Messages
You send a message to an object to make it execute a method. The
method to be executed is named in the message.
If an object does not understand a message, it is passed up the method
inheritance chain until it is recognized and executed (see the section
Method Inheritance in the chapter Classes for more information).
There are three ways of sending a message:

The INVOKE statement

In-line method invocation

Object properties

Object-oriented Programming with COBOL

oppubb.book Page 39 Tuesday, March 16, 2004 12:23 PM

Sending Messages

Using the INVOKE Statement


You can send a message by using the INVOKE statement. For example:
invoke myClass "new" returning myObject

This sends message "new" to myClass; in this example myClass is an


object reference referring to the class declared in the example in the
previous section. The target of an INVOKE statement is always an object
reference. USING and RETURNING parameters are optional, and follow
the same rules as a COBOL CALL statement.
You do not have to use a literal for the message name. You can also put
a message name into a PIC x(n) data item. For example:
move "new " to aMessage
...
invoke myClass aMessage returning myObject

However, there is a disadvantage to using a data item: the object


reference that precedes the message name data item, myClass in this
example, must be a universal object reference, and hence the Compiler
cannot do its usual conformance checking. For more information on
conformance checking see the section Conformance.
The data item used to store the message must be large enough to allow
at least one space at the end of the message name. The run-time system
needs the space to be able to find the end of the message name.
The results are unpredictable if you send a message and use the same
variable for sending a parameter and returning a result. For example,
do not code:
invoke myObject "add" using aValue returning aValue

Inline Method Invocation


You can invoke a method inline, as long as it has a returning parameter,
by coding the object reference followed by the method and separated
by two colons in place of an operand in a statement, for example:
move anAccount::"getBalance" to current-balance

Object-oriented Programming with COBOL

39

oppubb.book Page 40 Tuesday, March 16, 2004 12:23 PM

40

Chapter 3 Using Objects in Programs

This is equivalent to the following INVOKE statement:


invoke anAccount "getBalance" returning current-balance

Invocation Using Object Properties


You can invoke get property and set property methods using object
properties. Get and set property methods are methods that are either
generated automatically by the Compiler in response to object property
syntax in data definitions, or coded by you using special syntax in the
Method-ID paragraph. To invoke a get or set property method, you use
a statement such as:
move balance of anAccount to current-balance

This statement invokes the get property method balance of the account
object referred to by the object reference anAccount.
For more details see the section Get and Set Property Methods in the
chapter Methods.

Conformance
Conformance is a quality that applies to interfaces. The term interface is
used in two ways in OO COBOL:

Every object, whether factory or instance, is said to have an


interface consisting of the data and methods that have been
defined for the object in its class source element.

An interface can also be a collection of method prototypes,


specifying some behavior.

Part of an objects interface (in the first sense) can be a set of methods
that it provides because it implements an interface (in the second
sense). Interfaces in the second sense are explained in more detail in the
chapter Interfaces.
It is essential in OO programming that, when your program is executed,
each object conforms to the interface that you defined for it. To help to

Object-oriented Programming with COBOL

oppubb.book Page 41 Tuesday, March 16, 2004 12:23 PM

Conformance

ensure this, the Compiler provides conformance checking. In other


words, as far as possible it ensures that your objects will conform at runtime to the interfaces you have described for them. If any conformance
checks fail, the Compiler displays error messages. The more rigorously
you use the OO COBOL syntax, the more thoroughly your program will
be conformance checked.
Conformance checking relies on the existence of an external repository
file, containing details of all the interfaces. The use of this file is
controlled by the REPOSITORY Compiler directive, as follows:

To request that your program is conformance checked, compile it


with the setting REPOSITORY (CHECKING ON)

To make sure information about the object interfaces in your


program is added to the external repository, so that other programs
can be conformance checked against it, compile with the setting
REPOSITORY (UPDATE ON).

If you want both checking and update, compile with the setting
REPOSITORY (UPDATE ON CHECKING ON).

Here are some examples of the kinds of checks included:

You invoke a method of an object of class A using a typed object


reference. The Compiler checks that the method exists in the class
and that all the using and returning parameters in the INVOKE
statement match the parameters defined for the method in the
class.

You define class B as inheriting from class A. Class As factory object


has two methods, and so does class Bs. The Compiler checks that
the methods in class Bs factory object have the same names and
same using and receiving data definitions as the methods in class A.
(The methods in class B override the methods in class A.)

You define classes B and C as inheriting from class A, and you set a
typed object reference for class B to a typed object reference for
class A; the Compiler rejects this, because at compile time the typed
object reference to class A might actually point to an object of class
C. (You can get round this restriction by using an object view, which
delays the checking until run time. For more information see the
section Object Views.)

The Compiler uses the information in the external repository to perform


conformance checking.

Object-oriented Programming with COBOL

41

oppubb.book Page 42 Tuesday, March 16, 2004 12:23 PM

42

Chapter 3 Using Objects in Programs

Creating a New Instance Object


When you create a new object, the run-time system allocates an object
handle, and storage for the variables declared in the instance objects
Working-Storage Section. You can create as many instances of any
particular class of object as system resources allow; each has identical
behavior, but its own unique data. Classes either provide their own
methods for creating new object instances, or inherit them from a
superclass.
The method "new" is implemented in the class Base (part of the
supplied Base Class Library) to create an instance of a single object. To
create an instance object, send the message to a class and provide a
variable to receive the object reference.
For example:
working-storage section.
01 anAccount
object reference of BankAccount.
...
procedure division.
...
invoke BankAccount "new" returning anAccount

In this example, BankAccount returns a handle to a new instance of


itself in object reference anAccount. Some class library classes
implement a version of "new" which expects one or more parameters
for initialization. Some classes, for example Window, implement a
"new" method which sends the newly created object the "initialize"
message. Consult your Class Library Reference to check the interface to
the "new" method for the class you want to use. Object creation
methods are always factory methods.
Not all types of objects are created with the "new" message; for
example the collection objects in the Micro Focus Base Class Library are
created by "ofReferences" and "ofValues" methods. For more
information about collections see the chapter Collection Frameworks.

Object-oriented Programming with COBOL

oppubb.book Page 43 Tuesday, March 16, 2004 12:23 PM

Destroying Objects

Destroying Objects
Some OO programming languages perform garbage collection at run
time, that is, they automatically destroy objects that are no longer in
use. OO COBOL does not provide garbage collection. Once you create
an object, it remains in existence until destroyed explicitly, even if the
data item which holds its object handle is destroyed or goes out of
scope.
There are two ways an object can be destroyed:

The application that created it can destroy it when it has finished


with it

The run-time system always destroys any objects still in existence


when the run unit terminates

It is good programming practice to destroy unwanted objects in your


applications, rather than leaving it to the run-time system. You should
not destroy an object if it is still in use. However, if you have passed an
object to another part of your application, you may not know whether
the object is still in use or not. You should establish rules to govern
whether or not an object passed to another object can be destroyed.
An object which is no longer in use by an application, but which has not
been destroyed, is said to constitute a memory leak. The class Behavior,
part of the Micro Focus Base Class Library, has a method that helps with
finding memory leaks; for more information see the section Finding
Memory Leaks in the chapter Compiling and Debugging OO COBOL
Applications.

Object Destruction Methods


To destroy an object, send it the "finalize" message. For example:
invoke anObject "finalize" returning anObject

The "finalize" method is implemented in the Base class (part of the


supplied Micro Focus Base Class Library) and inherited by all classes.
Some class library objects contain references to other objects (for
example, collection objects). When you send the "finalize" method to

Object-oriented Programming with COBOL

43

oppubb.book Page 44 Tuesday, March 16, 2004 12:23 PM

44

Chapter 3 Using Objects in Programs

the containing object, the objects it refers to do not get destroyed. If


the only references you had to these objects were the ones held in the
containing object, you can now no longer reach or destroy those
objects.
Class library container objects, such as the collection objects, respond to
the "deepFinalize" message. This destroys all the objects within the
container as well as the container itself. You may want to consider
implementing "deepFinalize" in any objects of your own which contain
other objects, or reimplementing "finalize" to destroy contained
objects.
Which method is appropriate depends on the nature of the containing
object. If the containing object is the sole owner of the objects, it should
implement its own version of "finalize". If the containing object is
storing objects as an access mechanism for other clients, it should only
destroy them if it receives a "deepFinalize".

Finalized Object References


Once you have destroyed an object, you must avoid sending messages
to any reference that still points to that object. For example, do not
code:
set objectA to objectB
invoke objectB "finalize" returning objectB

The object handle held in objectA now points to a non-existent object.


Sending a message to an object handle after the object to which it
refers has been finalized gives unpredictable results:

If the object handle has not been reused by the run-time system, it
halts the application with a run-time error.

If the object handle has been reused by the run-time system, your
message is sent to the wrong object. If the object understands the
message, there will be no error informing you that something has
gone wrong.

There is an OO COBOL run-time switch to prevent reuse of finalized


object references - this ensures that you will always get a run-time error
when you attempt to send a message to a finalized object (see the

Object-oriented Programming with COBOL

oppubb.book Page 45 Tuesday, March 16, 2004 12:23 PM

Destroying Objects

section Preventing Reallocation of Object Handles in the chapter


Compiling and Debugging OO COBOL Applications).
If you create a copy of an object and keep the handle to the copy, you
can destroy the original object without affecting the copy.
All objects in the supplied class libraries create copies of any objects you
pass in as parameters and of any objects returned as parameters, with
the exception of elements stored in collections.

Object-oriented Programming with COBOL

45

oppubb.book Page 46 Tuesday, March 16, 2004 12:23 PM

46

Chapter 3 Using Objects in Programs

Object-oriented Programming with COBOL

oppubb.book Page 47 Tuesday, March 16, 2004 12:23 PM

47

4 Classes
This chapter explains the rules for writing classes, with short examples
of code. For full syntax definitions, see your Language Reference.

Overview
You need to write OO COBOL classes to create objects other than the
ones in the class libraries supplied by Micro Focus. When you write a
class, you need to understand three distinct entities:

The class
The source code defining the class.

The factory object


The class at run time.

Instance objects
Created by the factory object at run time.

A class embodies all the behavior for its factory object and its instance
objects. It defines the factory and instance data, and factory and
instance methods. A class also inherits the data and methods of its
superclass.
Methods are discussed both in this chapter, and in the chapter
Methods.
Net Express:

Net Express provides wizards that help you to create classes, methods
and data quickly. For more information see the Help topics To create a
class, To add a method to a class and To add a data item to a class.

Object-oriented Programming with COBOL

oppubb.book Page 48 Tuesday, March 16, 2004 12:23 PM

48

Chapter 4 Classes

Class Structure
Each class describes the behavior of two different objects:

The factory object

The instances of the class

There is never more than one occurrence of each type of factory object
in an application, whereas there can be many occurrences of its
instances. The main function of any factory object is to create instances,
although in some cases a factory object has other behavior as well.
Micro Focus
Alternative

In Micro Focus OO COBOL the class object is equivalent to the factory


object.
A class is structured as a set of nested source elements (see Figure 4-1).
Figure 4-1. Class Structure

The code block below shows the outline of an example class. An ellipsis
(...) shows where code has been omitted, and indentation indicates the
levels of nesting.

Object-oriented Programming with COBOL

oppubb.book Page 49 Tuesday, March 16, 2004 12:23 PM

Class Structure

class-id. Example inherits


from Base.
environment division.

*> Class identification.


*>
*>
*>
*>
*>
*>
*>

Environment division
header is optional.
All sections legal in
MF or ANSI 85 COBOL
Environment Division
are valid, though not
shown here.

*>
*>
*>
*>
*>
*>
*>
*>
*>
*>
*>

Repository paragraph
names the classes this
class refers to.
Information for the
Example class is stored in
the external repository
under the name "exmp".
Information for the
Base class is stored in
the external repository
under the name "base"

...
configuration section.
repository.

class Example as "exmp"

class Base as "base"

class CharacterArray
.

*> Period terminates paragraph.

...
factory.

*> Defines the start of the


*> factory object.

environment division.
data division.
working-storage section.

*> Defines factory object data

...
...
method-id. "new".

*> Start factory method "new".

...
end method "new".
end-factory.

*> End factory method "new".


*> End of the factory object

Object-oriented Programming with COBOL

49

oppubb.book Page 50 Tuesday, March 16, 2004 12:23 PM

50

Chapter 4 Classes

object.

working-storage section.

*>
*>
*>
*>
*>

Start of the code


defining behavior
of instances
of the class.
Defines instance data.

...
method-id. "sayHello".*> Start of instance
*> method "sayHello"
...
end method "sayHello".*> End of instance method.
end object.
*> End of code for
*> instances.
end class Example.

To see a class outline example that uses the Micro Focus COBOL
alternative syntax, see the section Summary of Syntax Alternatives in
the chapter Micro Focus OO COBOL Alternative Syntax.

Inheritance
Most OO COBOL classes inherit from a superclass. In the Micro Focus
class libraries the only exception to this is the Base class, which is at the
root of the inheritance tree for all other classes in the class libraries.
When you write your own COBOL classes you will nearly always write
them as a subclass either of Base or of another class.
In addition to a subclass inheriting all the methods of the classes above
it in the hierarchy, it can also inherit directly from more than one class;
this is known as multiple inheritance.
If you do decide to write a class which is not a subclass either of Base or
of one of its subclasses, you will not inherit the functions provided by
Base. You will have to implement your own method for destroying
unwanted instances, to replace the "finalize" method in the Base class.
You dont need to implement your own "new " method for creating
new instances, because this method is part of the Behavior class, and is
always available. Behavior is provided in the Base Class Library, and can

Object-oriented Programming with COBOL

oppubb.book Page 51 Tuesday, March 16, 2004 12:23 PM

Inheritance

be thought of as a metaclass (that is, a class that describes the


underlying behavior of all objects).
There are two things a class can inherit from its superclass or
superclasses:

Methods

Data

These are dealt with separately in the next two sections.

Method Inheritance
A factory object inherits all the factory methods of its superclass, and an
instance inherits all the instance methods of its superclass. Since the
superclass in turn inherits all the factory and instance methods of its
superclass, it follows that an object inherits all the methods
implemented by superclasses all the way up to the root class (usually
Base). When a method is implemented in more than one class in an
heirarchy, then when an object of a class that inherits the method is
executed, it is the method that is lower down in the hierarchy that is
executed.
If a class inherits from a class that also inherits from a class, and if a
method of the same name exists in both superclasses, then when that
method is invoked, the method in the superclass immediately above the
subclass is called.
If a class inherits directly from more than one class (multiple
inheritance), and if a method of the same name exists in more than one
of those superclasses, then when that method is invoked, the method in
the superclass declared first in the Class-ID paragraph of the subclass is
called.
Figure 4-2 shows an object C1 receiving the "setValue" message. Object
C1 is an instance of class C. The superclass of class C is class B, and the
superclass of class B is class A. Classes B and C do not implement instance
method "setValue", so the message gets passed all the way up to class A
where the code for "setValue" exists.
Instance method "getValue" is implemented in both class B and class A.
If object C1 was sent the "getValue" message, it would use the
implementation in class B, as this would be found first. You can always
Object-oriented Programming with COBOL

51

oppubb.book Page 52 Tuesday, March 16, 2004 12:23 PM

52

Chapter 4 Classes

reimplement a method that is already in a superclass when you want to


change its behavior for subclasses.
Figure 4-2. Method Inheritance

Figure 4-3 shows a case where an instance object gets sent a message
not implemented in any of its superclasses. The message gets passed up
the inheritance chain until it gets to Base. If Base does not understand
the message either, it sends the message "doesNotUnderstand" back to
the instance which originally received the message.

Object-oriented Programming with COBOL

oppubb.book Page 53 Tuesday, March 16, 2004 12:23 PM

Inheritance

Figure 4-3. Trapping Messages That are Not Understood

The "doesNotUnderstand" message then gets passed up the chain until


it reaches Base, where the "doesNotUnderstand" method raises an
exception which stops the application. If you want to create objects
which can handle messages they dont understand, you can
reimplement the "doesNotUnderstand" message to trap the error
before it gets back up to the Base class.
Figure 4-4 shows what happens when you send a message to a factory
object that does not understand it. The message is passed to the factory
methods for all the superclasses in the chain. When it reaches Base,
something slightly different happens.

Object-oriented Programming with COBOL

53

oppubb.book Page 54 Tuesday, March 16, 2004 12:23 PM

54

Chapter 4 Classes

Figure 4-4. Trapping a Message Not Understood by a Factory Object

All factory objects are instances of Behavior. Behavior is part of the Base
Class Library, and can be thought of as a metaclass, or class that
describes behavior common to all classes of object. If the message is an
instance method of Behavior, it is executed. Otherwise, Behavior sends
it to the instance methods of Base. It does this because Behavior is a
subclass of Base.
If no method is found, then Base sends the "doesNotUnderstand"
message back to the object which originally received the message.

Data Inheritance
A factory object inherits all the factory data of its superclass, and an
instance object inherits all the instance data of its superclass. The

Object-oriented Programming with COBOL

oppubb.book Page 55 Tuesday, March 16, 2004 12:23 PM

Files in OO Programs

inherited data of a subclass includes any data that the superclass itself
inherited from a class higher up the hierarchy. The inherited object data
is initialized when an object is created. The inherited factory data is
allocated independently from the factory data of the inherited class or
classes when the factory of the subclass is created. A subclass can only
access inherited data through the methods it inherited from the same
class. For example, if the class Manager inherits from the class
Employee, and Employee defines the data item:
employeeNumber

PIC 999

The Manager class cannot store a value in its inherited


employeeNumber data item by using a statement such as:
move 100 to employeeNumber

Instead it must use a method declared in the Employee class, for


example:
invoke self "setEmployeeNumber" using 100

The object reference SELF is a reserved name which always refers to the
object in which it occurs (see the section Predefined Object Reference
Names in the chapter Methods).
Micro Focus COBOL provides alternative syntax and behavior; see the
section Data Inheritance in the chapter Micro Focus OO COBOL
Alternative Syntax.

Files in OO Programs
OO COBOL supports full COBOL file handling syntax, and you can use
this in your classes to read and write to COBOL file types. To do file
handling, you need to include the File Section and a File-Control
paragraph for each file in your factory code or instance code. One or
more of your factory methods or instance methods will contain file
processing verbs such as OPEN, CLOSE, READ.
When the factory or instance source elements of a class contains a file
specification, any subclasses below it in the class hierarchy inherit the
file specification. Each factory or instance object of each of these
subclasses has its own file connector unless the EXTERNAL clause is

Object-oriented Programming with COBOL

55

oppubb.book Page 56 Tuesday, March 16, 2004 12:23 PM

56

Chapter 4 Classes

specified for the file in the original class. You can use dynamic filename
assignment or file sharing to resolve conflicts in accessing the physical
files associated with these file connectors. For more infomation about
file connectors, dynamic filename assignment and file sharing see your
Language Reference.

Programming Factory Object Behavior


The part of the class that defines factory object behavior is the factory.
The factory source element is nested inside a COBOL class source
element, bracketed by the FACTORY and END-FACTORY headers. The
factory source element embodies the behavior of the factory object,
which exists only at run time when the class is loaded.
Not all classes contain a factory source element; the main function of a
factory object at run time is to create new instances. This function is
often inherited from the superclass. The main reasons for writing your
own factory object are:

To provide instance creation methods that include initialization


code.

To store data global to all instances of the class (instances will only
be able to access this data by sending messages to the class).

To see where the factory source element fits within the class source
element, review the code for an example class in the section Class
Structure.

Factory Object Data


You declare factory object data in the Working-Storage Section of the
factory source element. Factory object data can be accessed only from
factory methods and can optionally be inherited by a subclass.
When a class is loaded by an application, the run-time system allocates
an area of memory for the data declared in the Working-Storage
Section of the factory source element, and for data declared in any
superclasses it inherits from.

Object-oriented Programming with COBOL

oppubb.book Page 57 Tuesday, March 16, 2004 12:23 PM

Programming Factory Object Behavior

A factory object can only access data directly that it has declared itself.
A factory object can only access data it has inherited by sending
messages to its superclass.
For further information about data inheritance using ISO 2002 OO
COBOL see the section Data Inheritance. For further information about
data inheritance using Micro Focus alternative syntax see the section
Data Inheritance in the chapter Micro Focus OO COBOL Alternative
Syntax.

Class Initialization
Class initialization code is executed when the class is loaded by the runtime system; it is only ever executed once during an application run.
Class initialization code is optional, and for most classes is not required.
You use it for initializing factory object data. For example, you might
want to make certain objects available to your factory object at startup.
You couldnt specify these in value clauses in your factory WorkingStorage Section because value clauses can only specify static data,
whereas object handles are allocated dynamically at run time.
To write class initialization code, write a factory method called
"initializeClass", and put all the initialization code in that method. The
method will be automatically called by the run-time system when it
loads the class.
Your COBOL system uses demand loading to reduce application startup
times. This means you cant predict exactly when any particular class will
be loaded. A class is guaranteed to be loaded and initialized by the time
it receives its first message. Because you do not know exactly when a
class is loaded, you should not rely on class initialization code to set
values in external variables used elsewhere in the application.

Factory Methods
Factory methods are source elements nested inside the factory object
source element. There is only ever one occurrence of any particular type
of factory object when you run an application, so factory methods are
generally concerned with the creation and management of instance
objects.

Object-oriented Programming with COBOL

57

oppubb.book Page 58 Tuesday, March 16, 2004 12:23 PM

58

Chapter 4 Classes

Factory methods have access to factory object data.


You code factory and instance methods in the same way; the only
difference between them is their position in the class source element
and the scope of data to which they have access. Coding methods is
explained in more detail in the chapter Methods.

Programming Instance Object Behavior


The part of the class that defines instance object behavior is the object.
The object source element is nested inside a COBOL class source
element, bracketed by the OBJECT and END-OBJECT headers. It follows
the factory source element. The object source element embodies the
behavior of the instance objects, which exist only at run time.
To see where the object source element fits within the class source
element, review the code for an example class in the section Class
Structure.

Instance Data
You declare instance data in the Working-Storage Section of the
instance object source element. Instance data can only be accessed from
instance methods, and each instance can only see its own instance data.
An instance object inherits all the instance data of its superclass and any
classes higher up the hierarchy.
When an instance is created by an application, the run-time system
allocates an area of memory for the data declared in the WorkingStorage Section, and for instance data declared in any superclasses it
inherits from. For more information about creating instances see the
section Instance Creation Methods in the chapter Methods.
An instance object can only access data directly that it has declared
itself. The only way an instance object can access data it has inherited
from a superclass, is to send a message to the superclass. For further
information about data inheritance using ISO 2002 OO COBOL see the
section Data Inheritance. For further information about data

Object-oriented Programming with COBOL

oppubb.book Page 59 Tuesday, March 16, 2004 12:23 PM

Programming Instance Object Behavior

inheritance using Micro Focus alternative syntax see the section Data
Inheritance in the chapter Micro Focus OO COBOL Alternative Syntax.
You should only declare as instance data the data which is actually part
of an objects attributes. You should declare data items which you need
for temporary working and calculations elsewhere. The safest place to
declare temporary data is in the Local-Storage Section of any methods
which require it.
For example, the only instance data declared for the Account objects
used by the tutorials in this book is the customer name, account number
and balance. If there is a piece of data which is the same for all instances
(for example, the interest rate), it is declared as factory object data. All
temporary data is declared in method Local-Storage Sections as
required.
Every byte of storage you declare as instance data is allocated every
time your application creates a new instance object. Only declaring as
instance data the data which is strictly part of the objects attributes
keeps memory overhead to a minimum.

Instance Initialization
How you code the initialization for an object is largely up to you. There
is no explicit mechanism for instance initialization in the way there is for
class initialization. The easiest and most readable way is to code an
"initialize" method, and to write an instance creation method (which is
always a factory method) which invokes the "initialize" method after it
has created an instance. You can also initialize data in the WorkingStorage Section using VALUE clauses.
Some objects might be initialized from data supplied with the message
that creates them. The instance creation method would have to pass
these parameters to the "initialize" method. Other types of object are
always initialized to the same state at creation. Windows and dialog
boxes usually fall into this category; the initialization code usually
consists of painting them with the same set of gadgets and labels every
time.

Object-oriented Programming with COBOL

59

oppubb.book Page 60 Tuesday, March 16, 2004 12:23 PM

60

Chapter 4 Classes

Instance Methods
Instance methods are source elements nested inside the instance object
source element. Instance methods are the way in which an application
can alter the state of an object or query its attributes.
Instance methods have access to instance data.
You code factory and instance methods in the same way; the only
difference between them is their position in the class source element
and the scope of data to which they have access. How to code methods
is explained in more detail in the chapter Methods.

Parameterized Classes
A parameterized class is a skeleton class that has one or more formal
parameters. When you provide specific class names or interface names
as actual parameters, the Compiler expands the parameterized class
into a new non-parameterized class.
The purpose of parameterized classes is to make it easier for you to
create many similar classes. For example, if you need four linked list
classes to enable you to store four different types of object, you can
write one parameterized class, then use the expansion feature to create
the four linked list classes at compile time. This is less work than writing
four complete linked list classes.
(In a linked list each item has a link to the next item. Linked lists provide
an easy way of storing and retrieving objects.)
An additional advantage of parameterized classes is that they enable
conformance checking at compile time. If you have a general linked list
that can store any type of object, an object of a different class to the
class your application expects could be added to the table; this could
result in unexpected run-time results. With an expanded parameterized
class, any INVOKE statement trying to add an object of the wrong class
will be caught at compile time by the Compiler.
A parameterized class always has a USING phrase that lists the formal
parameters in its Class-ID paragraph.

Object-oriented Programming with COBOL

oppubb.book Page 61 Tuesday, March 16, 2004 12:23 PM

Parameterized Classes

You need to specify the EXPANDS phrase in the entry for the class in the
Repository paragraph of any program that uses a class created from a
parameterized class.
For example, suppose that you wanted to create a linked list for
employees who report to a particular manager. The parameterized class
could look like this:
$set repository(update on checking on)
class-id. PLinkList as "PLinkList" inherits Base
using fparam1.
repository.
class fparam1
class Base as "base"
.
factory.
* new: creates new linked list, initialise
* head and tail pointers
method-id. "new".
linkage section.
01 newObject usage object reference PLinkList.
procedure division returning newObject.
invoke super "new" returning newObject
invoke newObject "initlinkedlist"
exit method
end method "new".
end factory.
object.
working-storage section.
* data items to hold head of linked list and position
* during iteration
method-id. "initLinkedList".
local-storage section.
01 tmp-element usage object reference fparam1.
procedure division.
* code to initialize linked list
exit method
end method "initLinkedList".
method-id. "add".
01 newEntry usage object reference LinkEntry.

Object-oriented Programming with COBOL

61

oppubb.book Page 62 Tuesday, March 16, 2004 12:23 PM

62

Chapter 4 Classes

linkage section.
01 lk-element usage object reference fparam1.
procedure division using by value lk-element.
* code to add the element to the linked list
exit method.
end method "add".
method-id. "getFirst".
local-storage section.
01 tmp-element usage object reference.
linkage section.
01 lk-element usage object reference fparam1.
procedure division returning lk-element.
* code to get the first element from a linked list
exit method.
end method "getFirst".
method-id. "getNext".
local-storage section.
01 tmp-element usage object reference.
linkage section.
01 lk-element usage object reference fparam1.
procedure division returning lk-element.
* code to get the next element from a linked list
exit method.
end method "getNext".
end object.
end class PLinkList.

At compile time all occurrences of fparam1 are replaced by the the


name of an actual class or interface. To make this happen you need to
specify the ACTUAL-PARAMS Compiler directive. In this example the
directive is:
ACTUAL-PARAMS(ELinklist Employee)
Elinklist is the new class to create from the parameterized class.
Employee is the class name that replaces fparam1.
You can now use the ELinklist class in a program, for example:
$set repository(update on checking on)
class-id. Manager as "Manager" inherits Employee.

Object-oriented Programming with COBOL

oppubb.book Page 63 Tuesday, March 16, 2004 12:23 PM

Parameterized Classes

repository.
class Employee as "Employee"
class Manager as "Manager"
class PLinkList as "PLinkList"
class ELinkList as "ELinkList"
expands PLinkList using Employee.
factory.
...
end factory.
object.
working-storage section.
01 ListEmployees usage object reference ELinkList
value null.
* initManager: initalize linked list
method-id. "initManager".
procedure division.
set ListEmployees to ELinkList::"new"
exit method
end method "initManager".
* AddEmployee: add employee to linked list
method-id. "addEmployee".
linkage section.
01 lk-employee usage object reference Employee.
procedure division using by value lk-employee.
invoke ListEmployees "add"
using by value lk-employee
exit method
end method "addEmployee".
* display : display managers details and all reporting
* employees from linked list
method-id. "display" override.
local-storage section.
01 employee usage object reference Employee.
procedure division.
...
invoke ListEmployees "getfirst" returning employee
perform until exit
if employee not = null
invoke employee "display"
else
exit perform
end-if

Object-oriented Programming with COBOL

63

oppubb.book Page 64 Tuesday, March 16, 2004 12:23 PM

64

Chapter 4 Classes

invoke ListEmployees "getnext"


returning employee
end-perform
...
exit method.
end method "display".

Object-oriented Programming with COBOL

oppubb.book Page 65 Tuesday, March 16, 2004 12:23 PM

65

5 Methods
This chapter explains how to write methods, with short examples of
code. For full syntax definitions, see your Language Reference.

Overview
You write methods inside class source elements, which are described in
the chapter Classes. Each method is a nested source element bracketed
by METHOD-ID and END METHOD headers. You may optionally
precede the first METHOD-ID header by an IDENTIFICATION DIVISION
header. Factory methods appear inside the factory object source
element. Instance methods appear inside the instance object source
element, following the Working-Storage Section.
If the object that you are coding implements an interface, you must
write methods for every method prototype in the interface. For further
information about interfaces and method prototypes, see the chapter
Interfaces.
Net Express:

Net Express provides wizards that help you to create classes, methods
and data quickly. For more information see the Help topics To create a
class, To add a method to a class and To add a data item to a class.

Method Data
Factory methods can access factory Working-Storage data and instance
methods can access instance Working-Storage data. In all other
respects factory and instance methods look and work identically.

Object-oriented Programming with COBOL

oppubb.book Page 66 Tuesday, March 16, 2004 12:23 PM

66

Chapter 5 Methods

A method can also have data of its own; you can declare the following
types of storage section in a method:

Local storage
Data items that are local to the current invocation of a method.

Linkage
Data items for passing parameters to and from a method.

The following piece of code shows an example method, "setInItemA"


which stores a single character and converts it to upper case. The
method returns 1 if the character was already in upper case and zero
otherwise. It refers to a data item, clItemA, which you can assume is
declared in the Working-Storage Section of the instance object.
method-id. setInItemA.
local-storage section.
01

aTempItem

pic x(4) comp-5.

linkage section.
01
01

lnkValue
aResult

pic x.
pic x comp-5.

procedure division using lnkValue


returning aResult.
move lnkValue to inItemA
move 1 to aTempItem
call "CBL_TOUPPER" using inItemA
by value aTempItem
if lnkValue = clItemA
move 1 to aResult
else
move 0 to aResult
exit method.
end method setInItemA.

The method uses local storage for all its temporary working data. The
run-time system allocates memory for local storage each time the
method is invoked, and deallocates it after executing the EXIT METHOD
statement. This has the advantage of supporting recursion. A method
may be recursive even if it doesnt invoke itself directly; it may invoke a
method in a different object which invokes the original method a
second time.

Object-oriented Programming with COBOL

oppubb.book Page 67 Tuesday, March 16, 2004 12:23 PM

Predefined Object Reference Names

The Linkage Section is used to declare all parameters passed to or from


the method. Usually parameters are passed by reference, which means
that no actual memory is allocated for Linkage Section items.

Predefined Object Reference Names


Quite often a factory or instance object may need to send a message to
itself. The three most common reasons are listed below:

You can put a piece of code used by several different methods into
a method on its own. You can use this method like a subroutine.

You may need to get or change the value of a data item declared in
a superclass. This is possible only if the superclass provides a method
to do this, since methods are always inherited by subclasses. Your
object sends a message to itself to invoke the inherited method and
apply it to its own data.

You may need to access factory data from an instance method

Three predefined object reference names, which are initialized by the


run-time system when an object is created, are available to class source
elements to enable them to send messages to themselves. They are:

SELF
SELF enables an object to send a message to itself. The method
invoked is a method in the same class. If you send a message to SELF
from object A, object A is the receiver of the message; if you send a
message to SELF from object C, object C is the receiver of the
message.
SELF always refers to the object currently executing, even if the
method is one which is being inherited. For example, imagine two
objects, A and B, instances of classes A and B where B inherits from
A. A implements instance method, "calculateValue". B implements
instance method, "getObjectConstant". The "calculateValue"
method sends the message "getObjectConstant" to SELF. If B gets
sent the "calculateValue" message, the method invoked is the one
inherited from class A. When "calculateValue" sends a message
"getObjectConstant", the message actually gets sent to the object
B.

Object-oriented Programming with COBOL

67

oppubb.book Page 68 Tuesday, March 16, 2004 12:23 PM

68

Chapter 5 Methods

If A were to be sent the "calculateValue" message, then the send to


SELF would send the message to A, which would not recognise the
method "getObjectConstant.

SUPER
SUPER enables an object to send a message to itself. The method
invoked is a method in one of the superclasses of the class. If SUPER
is used from an instance, the run-time system searches for a method
beginning with the instance code of the superclass immediately
above the class, and works its way up through the instance methods
of all the superclasses until it finds a method matching the message.
If SUPER is used from a factory method, the run-time system
searches for a factory method beginning with the factory object
code of the superclass immediately above the class and works its
way up through the factory methods of all the superclasses until it
finds a method matching the message.

Micro Focus
extension

SELFCLASS
SELFCLASS enables an instance object to send a message to the
factory object which created it. The method invoked is a method in
the factory object. If you use SELFCLASS from a factory method, it
points to the metaclass for this class, which is an instance of
Behavior.
ISO 2002 OO COBOL provides an alternative to SELFCLASS; this is the
"FactoryObject" method of the ISO 2002 Base class. If you invoke
the "FactoryObject" method on any object that inherits from Base,
it returns the same object reference as SELFCLASS, that is an object
reference pointing to the factory object.

Note: You can also use SELF and SELFCLASS as object reference data
items that you can pass as parameters to other methods.

One further predefined object reference name is available; this is NULL.


NULL contains the null object refernce value, that is, a value that is
guaranteed not to point to an object.
Micro Focus
extension

The predefined object reference NIL is also available. NIL and NULL have
the same meaning.
The OO COBOL system also uses one external variable, OO-DESKTOP.
This is used with the GUI classes in the supplied class library.

Object-oriented Programming with COBOL

oppubb.book Page 69 Tuesday, March 16, 2004 12:23 PM

Instance Creation Methods

You must not change the contents of any of the predefined object
references or of OO-desktop.
SELF, SUPER, SELFCLASS, NULL and NIL are all reserved words.

Instance Creation Methods


You need to be able to create instance objects from your classes. At its
simplest, creating a new object instance means getting a memory
allocation for its data and an object handle by which you can refer to it.
This basic task is handled by an instance method in the metaclass
Behavior, called "new". All factory objects are instances of the
metaclass, and so inherit this method
If you do not want to carry out any initialization for an instance, you do
not need to code anything in the class for its creation; you can simply
inherit the "new" method from the metaclass. The example class below
works like this:
class-id. simple inherits from base.
* No factory methods for simple
...
object.
working-storage section.
01
simpleInstanceData
pic x(80).
* Instance methods for simple are not shown here.
...
end object.
end class simple.

When your application wanted a new instance of Simple, you would


code:
invoke simple "new" returning anObject

where anObject is a data item of type object reference. The "new"


method allocates the 80 bytes required for an instance of simple and
puts an object handle into anObject.
In many cases you will want to carry out some instance initialization on
objects created, in which case you have to code your own factory
method for creating instances. However, your own instance creation

Object-oriented Programming with COBOL

69

oppubb.book Page 70 Tuesday, March 16, 2004 12:23 PM

70

Chapter 5 Methods

methods will always use Behavior method "new" as the basic


mechanism for creating an object and allocating memory. For example:
class-id. A inherits from Base.
...
factory.
...
method-id. newWithData.
linkage section.
01 lnkObject
object reference A.
01 lnkName
pic x(80).
procedure division using lnkName
returning lnkObject.
*----Create a new instance of A using the "new" method
*----from Base
invoke super "new" returning lnkObject
*----Send it an initialize message.
invoke lnkObject "initialize" using lnkName
exit method.
end method newWithData.
end factory.
object.
working-storage section.
01 theName
pic x(80).
...
method-id. initialize.
linkage section.
01 lnkName

pic x(80).

procedure division using lnkName.


*----Store the initialization parameter in the objects
*
instance data
move lnkName to theName
exit method.
end method initialize.
...
end object.
end class A.

Object-oriented Programming with COBOL

oppubb.book Page 71 Tuesday, March 16, 2004 12:23 PM

Get and Set Property Methods

The "newWithData" method in class A sends the "new" message to


SUPER, introduced in the section Predefined Object Reference Names.
Sending a message to SUPER is very similar to sending it to SELF; the
only difference is that the run-time system starts looking for a matching
method in the code of your superclass rather than in the code of this
class.
There is no rule that says that you have to name an instance creation
method "new", although it is used by convention as it makes it obvious
what the method does.

Get and Set Property Methods


A frequent coding requirement is the setting of a number of data fields
to particular values; for example, a program reads in details of a new
customer, and needs to create a new record in a file or a new row in a
database table containing the information about the customer. To meet
this requirement in an OO application, you need a method for each
field that sets the required value. Methods that set values are known as
set methods.
Another frequent coding requirement is the retrieval of information
from a number of data fields; for example, a program that displays
information about existing customers needs to obtain the information
from records in a file or rows in a database table containing the
information about the customers. To meet this requirement in an OO
application, you need a method for each field, that gets the required
value. Methods that get values are known as get methods.
Coding get and set methods for a number of data fields can be quite
tedious, so OO COBOL provides two mechanisms that reduce the
amount of programmer effort:

The PROPERTY clause in a data item definition

The PROPERTY clause in a method definition

Both of these mechanisms work with object properties. Object


properties provide syntax to get information out of and pass
information back into objects.

Object-oriented Programming with COBOL

71

oppubb.book Page 72 Tuesday, March 16, 2004 12:23 PM

72

Chapter 5 Methods

PROPERTY Clause in a Data Item


Definition
If you code the PROPERTY clause in a data item definition, the Compiler
automatically generates simple get property and set property methods
for you. These methods differ slightly depending on the data
description. For details of the methods generated see your Language
Reference.
For example, in your class program you might code:
class-id. A inherits from Base.
...
factory.
...
end factory.
object.
working-storage section.
01 custNo pic 9(10) comp property.
...
end-object.
end class A.

The Compiler generates get property and set property methods for custno, with internal method names. You do not need to know what these
method names are, because you do not call them directly. To find out
how to use the methods, see the section Coding the Object Property
Syntax.

PROPERTY Clause in a Method


Definition
With this mechanism, you write get and set methods, but use the
PROPERTY clause in the Method-ID paragraph of each method, so that
the Compiler can generate internal method names which will work with
the object property syntax. Use this mechanism if you need methods
that do more than the simple methods generated when you specify the
PROPERTY clause in a data definition.

Object-oriented Programming with COBOL

oppubb.book Page 73 Tuesday, March 16, 2004 12:23 PM

Get and Set Property Methods

For example, your class source element might include the following
code:
class-id A inherits from Base.
...
object.
working-storage section.
01 custNo pic 9(10).
method-id. get property custNo.
linkage section.
01 lkCustNo pic 9(10).
procedure division returning lkCustNo.
*> My other code here
move custNo to lkCustNo
*> My other code here
exit method.
end method.
method-id. set property custNo.
linkage section.
1 lkCustNo pic 9(10).
procedure division using lkCustNo.
*> My other code here
move lkCust-no to custNo
*> My other code here
exit method.
end method.

The Compiler generates internal method names for the get and set
methods for the custNo data item.

Coding the Object Property Syntax


You use the get and set property methods by coding the object
property syntax in your Procedure Division. In the following example a
procedural program sets the custNo object property:
program-id. PROG1.
repository.
class A.
property custNo.
working-storage section.
01 cust-no-in PIC 9(10) comp.
01 obj-ref usage object reference class A.
procedure division.
...

Object-oriented Programming with COBOL

73

oppubb.book Page 74 Tuesday, March 16, 2004 12:23 PM

74

Chapter 5 Methods

* invoke SET PROPERTY method


move cust-no-in to custNo of obj-ref

In the following example a procedural program gets the custNo object


property:
program-id. PROG1.
repository.
class A.
property cust-no.
working-storage section.
01 cust-no-out PIC 9(10) comp.
01 obj-ref usage object reference class A.
procedure division.
...
* invoke GET PROPERTY method
move custNo of obj-ref to cust-no-out

Object-oriented Programming with COBOL

oppubb.book Page 75 Tuesday, March 16, 2004 12:23 PM

75

6 Interfaces
This chapter explains the rules for writing interfaces, with short
examples of code. For full syntax definitions, see your Language
Reference.

Overview
An interface is a set of method prototypes; that is, skeleton methods
with no code. Classes can implement interfaces; a class that implements
an interface must provide full method definitions for the method
prototypes in the interface.
You can develop a hierarchy of inheriting interfaces, similar to a
hierarchy of classes. An interface can inherit from more than one
interface; this is known as multiple inheritance. An inheriting interface
has all the method specifications defined for the inherited interface
definition or definitions, including any method specifications that the
inherited definition or definitions inherited. The inheriting interface
can define new methods augmenting the set of inherited method
specifications. The inheriting interface must always conform to each of
the inherited interfaces.
Net Express:

Net Express provides wizards that help you to create interfaces and
methods quickly. For more information see the Help topics To create a
class and To add a method to a class.

Interface Source Elements


You write your interface definitions in interface source elements. An
interface source element can contain one or more interface definitions.

Object-oriented Programming with COBOL

oppubb.book Page 76 Tuesday, March 16, 2004 12:23 PM

76

Chapter 6 Interfaces

The code block below shows the outline of an example interface source
element. An ellipsis (...) shows where code has been omitted, and
indentation indicates the levels of nesting. In this example the interface
Drivable, containing a method prototype for calculating mileage,
inherits from the interface Rentable, which can be assumed to contain
methods applicable to all objects that can be rented.
interface-id. Drivable
inherits from Rentable. *> Interface identification.
environment division.

*> Environment division


*> header is optional.

...
configuration section.
repository.

interface Drivable

interface Rentable as "rble"

*>
*>
*>
*>
*>

Repository paragraph
names the interfaces this
interface refers to.
Information for the
Drivable interface stored

*>
*>
*>
*>
*>
*>

in the external repository


under the name "DRIVABLE"
Information for the
Rentable interface stored
in the external repository
under the name "rble".

.
*> Period ends paragraph.
procedure division.
method-id. "calcMileage". *> Start of method
*> prototype "calcMileage".
*> Method contains data
*> but no code.
data division.
linkage section.
01 endMileage pic 9(6).
01 beginMileage pic 9(6).
01 mileage pic 9(6).
procedure division using endMileage, beginMileage
returning mileage.
end method "calcMileage". *> End of method prototype.
method-id. "logDamage".
*> Start of method
*> prototype "logDamage".
end method "logDamage".
*> End of method prototype.

end interface Drivable.

Object-oriented Programming with COBOL

oppubb.book Page 77 Tuesday, March 16, 2004 12:23 PM

Interface Implementation

Interface Implementation
Factory objects and instance objects within classes can implement
interfaces. The implementing object implements all the method
prototypes defined for the implemented interface definition or
definitions, including any method prototypes that the implemented
definition or definitions inherited.
Here is an example of an instance object that implements the Drivable
interface:
class-id. Car inherits from Vehicle.
configuration section.
repository.
class Car
class Vehicle
interface Drivable
.
factory.
* The code for the factory object starts here
...
* The code for the factory object ends here.
end factory.
*-----The instance object code starts here.
object. implements Drivable.
working-storage section. *> Instance data goes here.
...
procedure division.
interface-methods.
*> Start of implementation
*> of interface methods.
method-id. "calcMileage".
data division.
linkage section.
01 endMileage pic 9(6).
01 beginMileage pic 9(6).
01 mileage pic 9(6).
procedure division using endMileage, beginMileage
returning mileage.
subtract endMileage from beginMileage giving mileage.
end method "calcMileage".
method-id. "logDamage".
...
end method "logDamage".

Object-oriented Programming with COBOL

77

oppubb.book Page 78 Tuesday, March 16, 2004 12:23 PM

78

Chapter 6 Interfaces

method-id. "pickUp"
...
end method "pickUp"
instance methods.

*> Implementation of method


*> inherited by Drivable from
*> Rentable

*> start of instance methods


*> for an object of this class

...
end object.
*-----the instance object code ends here.
end class Car.

The Compiler provides conformance checking for interface


implementation. It checks that the interface of the factory object of the
implementing class conforms to the interfaces to be implemented by
the factory object, and that the interfaces of the instance objects of the
implementing class conform to the interfaces to be implemented by the
instance object. The Compiler also checks that you have implemented
all the methods listed in the interface definition. For more information
about conformance see the section Conformance in the chapter Using
Objects in Programs.

Parameterized Interfaces
A parameterized interface is a skeleton interface that has one or more
formal parameters. When you provide specific class names or interface
names as actual parameters, the Compiler expands the parameterized
interface into a new non-parameterized interface. The purpose of
parameterized interfaces is to make it easier for you to create many
similar interfaces.
A parameterized interface always has a USING phrase that lists the
formal parameters in its Interface-ID paragraph.
You need to specify the EXPANDS phrase in the entry for the interface
in the Repository paragraph in any program that uses a interface
created from a parameterized interface.
Here is an outline of the code for a parameterized interface:
interface-id. pinterface using fparam1 fparam2.
repository.
class fparam1

Object-oriented Programming with COBOL

oppubb.book Page 79 Tuesday, March 16, 2004 12:23 PM

Parameterized Interfaces

class fparam2.
method-id meth1.
procedure division using by reference fparam1.
end method meth1.
method-id meth2.
procedure division using by reference fparam2.
end method meth1.
end interface pinterface.

At compile time all occurrences of fparam1 and fparam2 are replaced by


the names of actual classes or interfaces. To make this happen you need
to specify the ACTUAL-PARAMS Compiler directive. In this example the
directive might be:
ACTUAL-PARAMS(MyInterface ClassA ClassB)
MyInterface is the new interface to create from the parameterized
interface. ClassA and ClassB are the class names that replace fparam1
and fparam2.
You can now use the MyInterface interface in a class, for example:
class-id. ClassC.
configuration section.
repository.
interface MyInterface expands pinterface using ClassA ClassB
...
factory. implements MyInterface.
...
stop run

You can use the MyInterface interface in a procedural program too, but
only indirectly. You need to create a class that implements the interface,
then include entries for both the interface and the class in the
programs Repository paragraph. In the program you can use typed
object references of the MyInterface interface, and use the myInterface
interface in object views, for example:
program-id. prog.
repository.
class A.
class B.
class ClassC implements MyInterface.
*> this class implements MyInterface
interface MyInterface expands pinterface
using ClassA ClassB.

Object-oriented Programming with COBOL

79

oppubb.book Page 80 Tuesday, March 16, 2004 12:23 PM

80

Chapter 6 Interfaces

...
working-storage section.
1 obj-ref1 usage object reference MyInterface.
1 obj-ref2 usage object reference factory class3.
procedure division.
set obj-ref1 to obj-ref2
invoke obj-ref1 "someMethodInTheInterface" using ...

Object-oriented Programming with COBOL

oppubb.book Page 81 Tuesday, March 16, 2004 12:23 PM

81

7 Compiling and Debugging OO


COBOL Applications
This chapter provides some information to help you compile and debug
OO COBOL applications.

Compiling
The processes for compiling an OO application are very similar to those
described for all COBOL applications elsewhere in your documentation
set.
Use the standard Micro Focus Compiler to compile your OO COBOL
programs.

Compiler Directives
Use the OOCTRL Compiler directive to control behavior that is specific
to OO COBOL programs. This provides a number of options, which you
set on or off by use of the + and - signs respectively, preceding the
option character. The options are:
F

Specifies whether or not to fold method names invoked by the


program being compiled to lower case. Use -F if your program
calls Java methods, since Java method names are case-sensitive.
See your Distributed Computing book for information on using
Java and COBOL together.

Specifies whether to make class data global for instances. The


use of this option is not recommended. It is provided for
compatibility with earlier releases.

Object-oriented Programming with COBOL

oppubb.book Page 82 Tuesday, March 16, 2004 12:23 PM

82

Chapter 7 Compiling and Debugging OO COBOL Applications

Specifies whether to make parameter type information available


to the run-time system. This is needed for messages sent to COM.
The number of parameters in any method called or declared is
limited to 31, plus an optional return value.

Specifies whether to disable the use of:

IN and OF any place that could possibly follow a data name


in the verb signature of a method interface definition

Any verb in the verb signature of a method interface


definition.

Specifies whether to use Working-Storage Section to mean


Object-Storage Section in instances and factory objects (class
objects).

The default is OOCTRL(+F-G-P+Q+W)


If you want to use conformance checking, you must set the REPOSITORY
directive. This controls whether or not information about the interfaces
you create are stored in the external repository file, and whether new
classes are checked for conformance. You might also need to set the
RDFPATH directve, which specifies where the external repository is
stored.
If you use parameterized classes or parameterized interfaces, you need
to set the ACTUAL-PARAMS directive.
Do not set the ALIGN directive when compiling classes. This can cause
unpredictable errors at run-time. All classes in the supplied class libraries
are compiled with the default value of ALIGN(8).
When you compile OO programs to native code (for linking to .exe or
.dll files), set the following compiler directives to optimize the result for
fast execution:
CASE FASTCALL FASTLINK NOFIXOPT NOPARAMCOUNTCHECK
NOREENTRANT NOSERIAL
There are two exceptions to this advice:

You must set the REENTRANT compiler directive on any COBOL class
that can be invoked from more than one thread. This directive
ensures that the class initialization process is handled correctly
when the class is started from more than one thread. Classes
compiled without this directive can fail in unpredictable and

Object-oriented Programming with COBOL

oppubb.book Page 83 Tuesday, March 16, 2004 12:23 PM

Compiling

inconsistent ways when invoked from more than one thread at a


time.

Do not set NOPARAMCOUNTCHECK on any class which has methods


that check the number of parameters passed to them. Leave the
PARAMCOUNTCHECK directive set (default) for any classes which
use code like this to test how many parameters were passed:
procedure division using p1 p2 ... returning p5
if address of p1 <> null
...
end-if
if address of p2 <> null
...
end-if

For more details of these directives see your Compiler Directives


documentation.

Directly Inherited Data


If you use the Micro Focus syntax for inheriting data directly from a
superclass (WITH DATA clause in Class-ID paragraph), you must compile
the superclass first. Data is inherited directly through .cls and .ins files
generated by the Compiler from the Object-Storage Sections in a class.
These files must be available before you compile any subclass that
inherits the data. See the section Data Inheritance in the chapter Micro
Focus OO COBOL Alternative Syntax for more information.
Note: If you change the Object-Storage definitions in a class, you must
recompile any of its subclasses that inherit its data. Otherwise, run-time
behavior is unpredictable.

Net Express:

If you rebuild the whole project, Net Express automatically compiles


classes in the right order.

Object-oriented Programming with COBOL

83

oppubb.book Page 84 Tuesday, March 16, 2004 12:23 PM

84

Chapter 7 Compiling and Debugging OO COBOL Applications

Debugging
Many of the same tools and techniques used for debugging COBOL
applications are applicable to OO COBOL applications. You can animate
the classes in an application in the same way that you can animate any
COBOL program.
When you query an object reference, the Animator displays the object
handle contained in the object reference. This enables you to see
whether object references are pointing to the same or different objects.
An object handle with value x"0000" always refers to the NilObject. An
object handle with the value of x"20202020" is reserved by the run-time
system. Sending messages to it gives the error message "Invalid object
reference".
There are some extra facilities to help you with some debugging
problems that are unique to OO programs:

A run-time system switch to prevent reallocation of object handles

An object counter that can help you to find memory leaks

Object storage guard pages

These facilities are explained in the following sections.

Preventing Reallocation of Object


Handles
The run-time system has a debugging option to prevent reallocation of
object handles. The default behavior of the run-time system is to reuse
the object handle for any object which has been finalized.
An application which sends messages to object handles after the object
referenced has been finalized can cause unpredictable behavior. The
message may be sent to a new object which has been allocated the old
handle.
If the message sent is one the new object does not understand, then the
"doesNotUnderstand" exception is raised, alerting you to the fact that
something has gone wrong. If the new object does understand the

Object-oriented Programming with COBOL

oppubb.book Page 85 Tuesday, March 16, 2004 12:23 PM

Debugging

message, then it will execute a method, and your application may fail at
some later point, or give unexpected results.
To prevent reallocation of object handles, set environment variable
OOSW to+d:
Net Express:

set oosw=+d

Server Express:

OOSW=+d
export OOSW

Now when a message is sent to an object handle for an object which no


longer exists, the run-time system displays the following error message:
RTS 240 Object reference not valid

Note: The +d setting for OOSW is intended for development work only.
Do not set +d in a production environment, as the run-time system
could eventually run out of object handles to allocate. The number of
object handles the run-time system can allocate before this happens
depends on the amount of memory available.

Finding Memory Leaks


A memory leak is memory allocated to an object which is no longer in
use by your application, but which has not been finalized. One way to
track down memory leaks is to watch the number of objects in your
application. For example, if adding a record created an extra 24 objects,
but deleting it only removed 20, a memory leak is a possibility.
You can find out the number of objects in existence at any time by
sending the message "getNumberOfObjects" to the Behavior class. For
example:
invoke Behavior "getNumberOfObjects" returning totalNumber

where totalNumber is declared as a pic x(4) comp-5.

Object-oriented Programming with COBOL

85

oppubb.book Page 86 Tuesday, March 16, 2004 12:23 PM

86

Chapter 7 Compiling and Debugging OO COBOL Applications

Object Data Guard Pages


A guard page is a page of memory that has special permissions set on it
so that it cannot be read or written to. By placing guard pages before or
after pages assigned to object data storage, the run-time system can
catch attempts to read or write beyond the ends of object data.
On some systems guard pages can help you track down some types of
memory corruption problem. Check your product release notes to see
whether they are supported on your system. They can help you find
errors on two types of memory:

Memory used to store object data. This is data defined in the


Working-Storage Sections of factory and instance object programs,
if you are using ISO 2002 standard syntax, or the Object-Storage
Sections of class and instance object programs, if you are using the
alternative Micro Focus syntax

Memory allocated through method "malloc" of the Base class.

You can use guard pages to trap either:

Attempts to read or write before the start of memory

Attempts to read or write after the start of memory

These sorts of problems can occur when you are using reference
modification to access data, or when you pass object data as a
parameter to a method that tries to access it using Linkage Section data
items declared as the wrong size. If you are using the Base class methods
"malloc" and "dealloc" to allocate and free memory, the following
types of error are also trapped:

Net Express:

Attempting to use memory you have freed

Attempting to free memory twice

If any of these types of errors occur when you are running with guard
pages active, you will get run-time error 114; if you are animating the
program execution stops with the statement that caused the problem
highlighted.
You can set the guard pages before or after object data and memory
allocations.

Object-oriented Programming with COBOL

oppubb.book Page 87 Tuesday, March 16, 2004 12:23 PM

Message Tracing

To set the guard page before object data and memory allocations:
Net Express:
Server Express:

set oosw=+g1
OOSW=+g1
export OOSW

To set the guard page after object data and memory allocations:
Net Express:
Server Express:

set oosw=+g2
OOSW=+g2
export OOSW

Switches +g1 and +g2 are mutually exclusive - you cannot set them both
at the same time.
Note: Running with guard pages on increases the amount of memory
used by your application. Only use it for debugging.

Message Tracing
If you are having problems with finding the point at which an
application fails or raises an exception, you can switch on a message
trace. This can be particularly useful if the error occurs while execution
is in one of the class libraries.
Server Express:

To turn on message tracing, set the OOSW environment variable before


you run your application:
OOSW=+t
export OOSW

The output is an ASCII file, trace.log, which you can look at with any
ASCII editor.
Net Express:

To turn on message tracing, either:

Click View > Trace Log. The trace information appears in a pane at
the bottom of the Net Express IDE. You can change how many
messages are stored by clicking Options > Trace Log and entering a
new value in Store Messages
Object-oriented Programming with COBOL

87

oppubb.book Page 88 Tuesday, March 16, 2004 12:23 PM

88

Chapter 7 Compiling and Debugging OO COBOL Applications

Set the OOSW environment variable before you run your


application:
set oosw=+t

The output is an ASCII file, trace.log, which you can look at with any
ASCII editor.
Every message sent by the application is logged in file trace.log.
Note: Running with trace on slows down application execution as every
message sent is written and flushed to the file.

The table below describes the trace information.

Trace Information Format


Type of Resolve

The target of an INVOKE is categorized by one of


the three values below:
resolve

The INVOKE is from one object to


another.

resolveself

An object invoked itself (INVOKE


SELF...)

resolvetosuper

An object invoked its superclass


(INVOKE SUPER...)

Object reference

The object handle of the receiver of the message.

Message

The message sent by the INVOKE.

Object type

Shows one of the following codes:


I

Instance object.

Factory object.

Metaclass object.

Class of object
invoked

The classname of the type of object invoked.

Class of
implementor

Class name of the implementor of the method.

Stack level

Shows the depth of the message stack. The stack


level becomes one greater each time a method
sends a message, and one lower each time a
method exits.

Object-oriented Programming with COBOL

oppubb.book Page 89 Tuesday, March 16, 2004 12:23 PM

Troubleshooting Tips

Troubleshooting Tips
This section deals with the following common problems:

Server Express:

Memory exceptions and protection violations that happen when


methods are invoked

Symbol redefined

Program not found

Memory Exceptions and Protection


Violations on Method Invocations
When passing parameters to and from methods, you need to ensure
that the data items used in the INVOKE statement match those
expected by the method. In particular, if a method attempts to move
data into a RETURNING parameter, and an INVOKE statement calling a
method does not supply a RETURNING parameter, the application may
cause a protection violation or memory exception.
For example, the "currentTime" method below returns the time in a 6byte group item:
method-id. "currentTime".
linkage section.
01 lnkTime.
03 lnkHours
pic xx.
03 lnkMins
pic xx.
03 lnkSecs
pic xx.
procedure division returning lnkTime.
move timeNow to lnkTime
exit method.
end method "currentTime".

The method invocation below has no RETURNING parameter, and


would probably cause a protection violation or other memory exception
error at run-time:
invoke mainClock "currentTime"

Object-oriented Programming with COBOL

89

oppubb.book Page 90 Tuesday, March 16, 2004 12:23 PM

90

Chapter 7 Compiling and Debugging OO COBOL Applications

Symbol Redefined
OO programs can cause RTS error 119 (Symbol redefined) for either of
the following reasons:

You have defined the same method-name twice in a single object

You have defined a class name with more than one filename

The first of these happens when within a single class you have named
two factory methods the same or two instance methods the same. You
are allowed to use the same names for a factory and an instance
method; you might for example have a class program which defined an
"initialize" method for both the factory and the instance object.
The second usually happens when you have a particular class defined in
the Repository paragraph of different programs, against different
filenames. Filenames are case-sensitive, so you can get this error even if
the names only differ in case.
For example, the Repository paragraph in program A might look like
this:
repository.
class DateClass as "Date"
...

and the Repository paragraph in the DateClass class might look like this:
repository.
class DateClass as "date"
...

At run time, when program A tries to invoke DateClass the run-time


system raises error 119. The convention used throughout the Class
Library and the examples in this book is to enter all filenames as lower
case.
Server Express:

Program Not Found


If your application tries to use a class which is not available, the runtime system gives you error message 173 (Called program not found). To
be available, there must be an executable file for the class either on the

Object-oriented Programming with COBOL

oppubb.book Page 91 Tuesday, March 16, 2004 12:23 PM

Troubleshooting Tips

current directory or in any of the directories pointed to by one of the


following environment variables:

COBDIR (for .int and .gnt format)

COBPATH (for .gnt format)

Object-oriented Programming with COBOL

91

oppubb.book Page 92 Tuesday, March 16, 2004 12:23 PM

92

Chapter 7 Compiling and Debugging OO COBOL Applications

Object-oriented Programming with COBOL

oppubb.book Page 93 Tuesday, March 16, 2004 12:23 PM

93

Part 3: Tutorials
This part contains the following chapters:

Chapter 8, Objects and Messages Tutorial

Chapter 9, Simple Class Tutorial

Chapter 10, More Complex Class Tutorial

Chapter 11, Interfaces and Parameterized Class Tutorial

Object-oriented Programming with COBOL

oppubb.book Page 94 Tuesday, March 16, 2004 12:23 PM

94

Part 3: Tutorials

Object-oriented Programming with COBOL

oppubb.book Page 95 Tuesday, March 16, 2004 12:23 PM

95

8 Objects and Messages Tutorial


This tutorial is a gentle introduction to OO COBOL programming, using
a class with some simple behavior, called the Stopwatch class. In this
tutorial you will create instances of the Stopwatch class. An instance of
the Stopwatch class is a stopwatch object, and having created
stopwatches, you can send messages to them.
This tutorial consists of the following sessions:
1

The Stopwatch class

Sending messages

The Stopwatch Class


This section introduces you to the Stopwatch class, describing its
behavior.
The Stopwatch class has two parts:

The Stopwatch factory source element, containing factory methods

The Stopwatch instance source element, containing instance


methods

A class is an object in its own right; it can have behavior and data of its
own, which is different to the behavior and data of instances of the
class. The main function of most classes is to implement the behavior
needed to create and initialize new instances.
You can use stopwatches to time things. Each stopwatch has methods
to start, stop and reset timing, and to get the current elapsed time.

Object-oriented Programming with COBOL

oppubb.book Page 96 Tuesday, March 16, 2004 12:23 PM

96

Chapter 8 Objects and Messages Tutorial

The Stopwatch class factory and instance methods are listed below.
Factory methods

Description

"new" returning anObject

Returns an instance of the


Stopwatch class, with the handle
in anObject

"howMany" returning aNumber

Returns the number of


Stopwatch instances created so
far.

Instance methods

Description

"start"

Starts a stopwatch running.

"stop"

Stops a stopwatch running.

"reset"

Resets the elapsed time on the stopwatch


to zero. You can only reset a stopwatch
that isnt running.

"getTimeFormatted"

Returns the time since the stopwatch


started in hh:mm:ss:ss format
(hours:minutes:seconds:hundredths of
seconds).

In addition to these methods, the Stopwatch class inherits all those


implemented by its superclass (Base). The superclass is the parent from
which this class inherits its basic behavior.
The Stopwatch class inherits all the factory methods of Base, and its
instances inherit all the instance methods of Base. This means that
Stopwatch responds to all the messages that Base responds to as well as
its own. Inheritance is explained in more detail in the section the section
Inheritance in the chapter Classes.
The Base class is part of the class library supplied with your COBOL
system. If you want to look at the methods of Base see your Class
Library Reference.
You can now move on to the next session, which uses Animator to show
you message sending.

Object-oriented Programming with COBOL

oppubb.book Page 97 Tuesday, March 16, 2004 12:23 PM

Sending Messages

Sending Messages
In this section you will create instances of the Stopwatch class, and send
messages to the instances, using the supplied program, timer.cbl.
Program timer.cbl is not an OO COBOL class; it is a piece of procedural
code which uses OO COBOL objects. To communicate with the objects
timer.cbl uses the following OO COBOL syntax:

The Repository paragraph


Declares the classes used by the programs, and links them to their
filenames.

The OBJECT REFERENCE data type


Declares a variable to hold object handles.

The INVOKE verb


Sends a message to an object.

You will now animate timer to see some simple object behavior. The
code demonstrates the following points:

Factory objects and the instance objects they create respond to


different messages.

Each instance created has its own unique instance data.

The factory object has factory data, which is unique to itself, and
not directly available to any of its instances.

The way you can access an objects data is through its methods (by
sending it messages). You cannot read or modify data to which the
object does not explicitly give you access through a method.

To animate timer:
1

Use Infomgr to locate the required demonstration programs and


transfer them to a working directory.

Run the supplied shell script timrscrp.


This compiles timer.cbl and stopwtch.cbl.

Object-oriented Programming with COBOL

97

oppubb.book Page 98 Tuesday, March 16, 2004 12:23 PM

98

Chapter 8 Objects and Messages Tutorial

Start animating timer. Enter the following command line:


anim timer
Animator starts with the statement below tag T010 highlighted
ready for execution.

Step the statement (invoke StopWatch "new" ...).


This sends the "new" message to the Stopwatch class, which creates
an instance of itself, returning an object handle to it in
wsStopWatch1.

Look at the contents of data item wsStopwatch1 with the


Animator Query function.
This data item is declared with usage object reference, which is
a COBOL data type introduced for OO COBOL programming..The
class name Stopwatch indicates that this data item can be used only
to hold an object reference to a Stopwatch object. It now holds a
handle (a four-byte reference) to the object you have created.
When you write in OO COBOL, you use the object handle as an
address to send messages to the object. You can pass object handles
between different programs or objects as parameters, in effect
enabling you to pass an object between different parts of an
application.

Close the Animator monitor.

Step the statement below tag T020 (invoke wsStopWatch1


"start").
The stopwatch starts timing.
The shell script you just ran did not compile Stopwatch for
animation, so you wont see the Stopwatch code executing. In this
tutorial we are concentrating on how to use objects, rather than on
how to construct them.

Step the line below tag T030 (invoke Stopwatch "new"...).


This creates a new instance of the Stopwatch class, and puts the
object handle into wsStopwatch2. Each of the two stopwatches
you created has the same behavior, but contains different data.

Object-oriented Programming with COBOL

oppubb.book Page 99 Tuesday, March 16, 2004 12:23 PM

Sending Messages

Step the statement below tag T040 (invoke Stopwatch


"howMany").
"howMany" is a factory method which enables you to query the
factory data of Stopwatch. Double-click wsCount to view the value
of wsCount. It contains 2, the number of instances created so far.

10 Step the statement below tag T050 (invoke wsStopwatch2


"start").
The second stopwatch starts running.
11 Step the statements below tag T060 (invoke wsStopwatch1
"getTimeFormatted"...).
You are now querying the time the first stopwatch has been
running, and it returns the time which has elapsed since you started
it. The other statements display the value on the console. Press
F2=view to see the console, press any key to return to the Animator
view.
12 Step the statements below tag T070 (invoke wsStopwatch1
"stop").
The stopwatches stop running.
13 Step the statements below tag T080.
This code fetches the elapsed time between the "start" and "stop"
messages for each stopwatch.
14 Step the statements below tag T090 (invoke wsStopwatch1
"finalize"...).
The "finalize" method destroys an object, deallocating the memory
it uses. The "finalize" method always returns a null object handle,
which you can use (as it has been here) to set the object reference
which held the handle to null.
You must always "finalize" objects when you have finished with
them, to avoid wasting system resources.
15 Press Escape to stop the Animator.

Object-oriented Programming with COBOL

99

oppubb.book Page 100 Tuesday, March 16, 2004 12:23 PM

100

Chapter 8 Objects and Messages Tutorial

Summary
This completes the tutorial on creating objects and sending messages.
You have seen:

How to create objects.

How to send messages.

How to finalize objects.

At this point you might be thinking that there is nothing special about
objects, and you could have done exactly the same thing using a few
subroutines. This is true, but think about what this would involve.
First you need to define a data structure for recording the start, stop
and elapsed time for a stopwatch. Then timer1.cbl needs to declare this
structure for each stopwatch it is going to use. When you want to start
timing, you call the start subroutine, passing it one of these structures
as a parameter. Similarly when you want to stop, or get the elapsed
time.
Should you decide to alter the implementation of the stopwatch
subroutines, you probably also need to change every place where you
have declared stopwatch data.
Compare this with the situation using objects. You declare an object
reference for each stopwatch, and having declared it, you simply send it
messages to start, stop or give the elapsed time. You can alter the
implementation as much as you want, providing you keep the interface
for the messages the same.
All the implementation details are hidden from you, and each
stopwatch you declare encapsulates its data and implementation into a
single entity. The code for any client of a stopwatch is kept very simple,
enabling you to concentrate on what you want to do with it, rather
than on how to use it.

Object-oriented Programming with COBOL

oppubb.book Page 101 Tuesday, March 16, 2004 12:23 PM

101

9 Simple Class Tutorial


In the Objects and Messages Tutorial you learned how to create
instances of a class and send messages. In this chapter you will learn
how to write classes for objects of your own, using the example
Stopwatch class introduced in the Objects and Messages Tutorial.
The first part of the discussion looks at the way a class is built up. It is
followed by sections in which you animate through the Stopwatch
code.
This tutorial consists of the following sessions:
1

Structure of a class

Animating the stopwatch

Structure of a Class
This tutorial starts with a look at the overall structure of a class source
element, using the Editor to examine the structure of Stopwatch.
The class source element consists of a set of nested source elements.
The sections below examine the following elements of the class source
element:

Identifying a class

Identifying classes used by a program

The factory object source element

Factory methods

The instance object source element

Instance methods

Object-oriented Programming with COBOL

oppubb.book Page 102 Tuesday, March 16, 2004 12:23 PM

102

Chapter 9 Simple Class Tutorial

To load Stopwatch into the Editor:


1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory.

Change to the working directory. Enter the following command:


editor stopwtch.cbl
As you read the explanations in the following sections, use the
Editor to locate and examine the code in stopwtch.cbl.

Identifying a Class
Each class source element starts with a class-id identifier and finishes
with an end class clause. These bracket the outermost level of the
nesting. The Stopwatch class looks like this:
class-id. Stopwatch as "stopwtch"
inherits from Base.
...
end class Stopwatch.

The inherits from phrase identifies Stopwatchs superclass, Base.


To see this code:

Move the cursor to the top of the file to see the Class-ID paragraph.

Move the cursor to the end of the file to see the End Class header.

Identifying Classes Used by a Program


The Repository paragraph identifies the executable code files which
implement classes used by the program. The superclass and every class
which will be invoked from the class must be identified in the
Repository paragraph.
To see the Repository paragraph for Stopwatch, scroll down the text
edit pane until you get to the Repository paragraph, located below tag
S005.

Object-oriented Programming with COBOL

oppubb.book Page 103 Tuesday, March 16, 2004 12:23 PM

Structure of a Class

The Repository paragraph looks like this:


repository.
class Base as "base".

The CLASS clause serves two purposes:

It creates a data item for each class named. At run time, this data
item holds an object handle to the factory object.

It enables the run-time system to find and load the file with the
class executable code.
A class is guaranteed to be loaded before the factory object receives
its first message. Usually this occurs when you send the first message
to the factory object, but before the factory object receives it.

The Factory Object Source Element


The factory object source element defines the data and methods for the
factory object. It is nested within the class source element, immediately
following the class source elements Data Division (if there is one). It
looks like this:
factory.
working-storage section.
* factory data .
...
* factory methods
end factory.

The factory object data is defined in the Working-Storage Section. The


factory object data can only be accessed from the factory methods

Factory Methods
Each factory method is a nested source element. The code below shows
an outline for a "new" method for Stopwatch.
method-id. "new".
...
linkage section.
01 lnkWatch

object reference.

Object-oriented Programming with COBOL

103

oppubb.book Page 104 Tuesday, March 16, 2004 12:23 PM

104

Chapter 9 Simple Class Tutorial

procedure division returning lnkWatch.


* code to create and initialize a Stopwatch object.
exit method.
end method "new".

As with the class source element itself, you can declare different types
of data in the Data Division of the method. The DATA DIVISION header
itself is optional. Data declared here is only accessible to the code in this
method. The Data Division can contain any of the following sections:

Local-Storage Section
Data items that are local to the current invocation of a method. The
method uses local storage for all its temporary working data. This
has the advantage of supporting recursion.

Linkage Section
Variables passed as parameters to and from the method.

The Procedure Division contains the code for the method. You
terminate processing of the method with an EXIT METHOD statement.
This returns processing to the program which invoked the method.
To see the "new" method, use the Editor to locate the "new" method,
below tag S015. This method uses a Linkage Section to return data from
the method.

The Instance Object Source Element


The instance object source element defines the data and methods for
instances of the class. It is nested within the class source element. It
looks like this:
object.
working-storage section.
* instance data for the object.
...
* Instance methods
end object.

The only Data Division section that has any meaning in an object source
element is the Working-Storage Section. You can create other data
sections, but the run-time behavior if you try to access the data in these
sections is undefined.

Object-oriented Programming with COBOL

oppubb.book Page 105 Tuesday, March 16, 2004 12:23 PM

Structure of a Class

Any data you declare in the Working-Storage Section is accessible to all


the instance methods, and may be inherited by instances of subclasses
of the class.
There is no Procedure Division in an object source element, only
methods. To write an initialization method for instances, write a
method called "initialize", and then invoke it from the "new" method
for the class after you have created an instance.
To see the object source element and data declarations paragraph for
Stopwatch, use the Editor to locate the OBJECT header. The OBJECT
header and Working-Storage Sections are located below tags S030 and
S035.

Instance Methods
Instance methods are nested inside the object source element. Writing
an instance method is exactly like writing a factory method, with the
only difference being the scope of data which the instance method can
access.
The instance method can access data:

Declared in the Data Division of the instance method source


element

Declared in the Working-Storage Section of the object source


element

To see the "start" method for Stopwatch, use the Editor to locate the
"start" method, just below tag S040. This method does not declare any
data of its own, but makes changes to the objects state by altering data
declared in the Working-Storage Section.
The code below summarizes the structure of a COBOL class, and recaps
the material covered so far in this tutorial.
class-id. Stopwatch as "stopwtch"
inherits from Base.
*> Identification
*> and inheritance
repository.

*> Repository paragraph names


*> the files containing the

Object-oriented Programming with COBOL

105

oppubb.book Page 106 Tuesday, March 16, 2004 12:23 PM

106

Chapter 9 Simple Class Tutorial

class Base as "base"


.
...

*> executables for each


*> class.
*> Period terminates paragraph.

factory.
working-storage section.
...
method-id. "new".
...
end method "new".
end factory.

*> Defines the start of the


*> Defines factory object data

object.

*>
*>
*>
*>

working-storage section.
...
method-id. "start".
...
end method "stop".
end object.

*> Start factory method "new".


*> End factory method "new".
*> End factory object
Start the code defining
behavior of instances
of the class.
Defines instance data.

*> Start instance


*> method "sayHello"
*> End instance method.
*> End code for
*> instances.

end class Stopwatch.

This completes the summary of class structure. In the next section you
will animate some of the Stopwatch code.

Animating the Stopwatch


In this session, you will animate some of the code in the Stopwatch class,
to see how classes and objects work. You are going to use the same
programs as in the Objects and Messages Tutorial, but this time
Stopwatch is compiled for animation so that you can see the code
execute.
To animate the Stopwatch class:
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory.

Object-oriented Programming with COBOL

oppubb.book Page 107 Tuesday, March 16, 2004 12:23 PM

Animating the Stopwatch

Run the supplied shell script wtchscrp.


This compiles timer.cbl and stopwtch.cbl for animation.

Start animating timer. Enter the following command line:


anim timer
Animator starts with the statement below tag T001 highlighted
ready for execution.

Step the first statement (invoke StopWatch "new" ...).


This sends the "new" message to the Stopwatch class, and execution
switches to the "new" method of the Stopwatch class.

Step the statement below tag S015 (invoke super "new"...).


The mechanism for actually creating a new object (allocating the
memory and returning an object handle) is inherited from the
supplied class library, and this statement executes the inherited
method. Some classes do not implement the "new" method at all,
but rely on the inherited method. Those that re-implement it
usually do so to send an initialization message to the new object. In
this case we have overridden it to keep track of the number of
instances created.

Step the statement below tag S020 (add 1 to osCount).


Data item osCount is part of the factory data, which is declared in
the factory Working-Storage Section.

Step the exit method statement to return from the method back
to timer.cbl.

Step the statement below tag T020. (invoke wsStopWatch1


"start").
Control switches to the "start" method of Stopwatch. Scroll up
through the code to the OBJECT header (between tags S030 and
S035). Methods which appear after the OBJECT header are instance
methods, and can access data declared in the Working-Storage
Section below the OBJECT header. They cannot access data declared
in the factory object (between the FACTORY header and END
FACTORY marker).
The "start" method tests to see whether the stopwatch is currently
running, and if it isnt, stores the current time in working storage, in
the startTime variable.
Object-oriented Programming with COBOL

107

oppubb.book Page 108 Tuesday, March 16, 2004 12:23 PM

108

Chapter 9 Simple Class Tutorial

Step through the code below tag S045 (if watchStopped), up to


and including the exit method statement.
Control returns to timer.cbl.

10 Perform step the statement below tag T030 (invoke StopWatch


"new" ...): press P thenS.
This creates a second stopwatch without you having to stepm
having to step through all the "new" code a second time.
11 Step the statement below tag T040 (invoke Stopwatch
"howMany").
Execution switches to the "howMany" method of Stopwatch. This is
a factory method (between the FACTORY header and ENDFACTORY marker), and returns the value in factory data variable
osCount.
12 Step the statements below S025 (move osCount to lnkCount) up
to and including exit method.
13 Step the statement below tag T050 (invoke wsStopwatch2
"start").
Execution switches to the "start" method of Stopwatch.
14 Query the value of watchRunning.
When you executed this method previously, on step 8, you set
watchRunning to true, but now it reads false. The reason is that
each different instance of Stopwatch has its own unique data. The
last time you executed this method, you sent the "start" message to
the instance of Stopwatch represented by the handle in
wsStopwatch1; this time you have sent it to a different instance,
which has its own data.
15 Step through the code up to and including the exit
methodstatement.
Control returns to timer.cbl. At this point you have seen factory
object and instance object code executing, and how different
instances have different data.
You can animate the rest of the code if you are interested to see
how the Stopwatch works.
16 Press Escape to quit Animator when you have finished.

Object-oriented Programming with COBOL

oppubb.book Page 109 Tuesday, March 16, 2004 12:23 PM

Summary

Summary
This concludes this tutorial on writing a class program. In this tutorial
you learned:

How to write a class.

The difference between factory and instance data.

How different instances of the same class contain different data.

The next tutorial demonstrates some more features of OO COBOL.

Object-oriented Programming with COBOL

109

oppubb.book Page 110 Tuesday, March 16, 2004 12:23 PM

110

Chapter 9 Simple Class Tutorial

Object-oriented Programming with COBOL

oppubb.book Page 111 Tuesday, March 16, 2004 12:23 PM

111

10 More Complex Class Tutorial


In this chapter you will learn how to write more complex classes that
use the following OO features in the ISO 2002 standard:

Inline method invocation

Object properties

Object views

Multiple inheritance

The Personnel Application


This section introduces the classes used in this tutorial. We will use the
Net Express development environment to explore the code in these
classes, before animating it in the second part of this tutorial.
The Personnel application uses the following classes:

Person

Employee

Student

IndPlacement

CharString

Object-oriented Programming with COBOL

oppubb.book Page 112 Tuesday, March 16, 2004 12:23 PM

112

Chapter 10 More Complex Class Tutorial

CharString is a utility class that creates and manipulates strings. The


other four classes form a hierarchy, as shown in Figure 10-1:
Figure 10-1. Classes in Personnel Application

CharString and Person both inherit from Base.


Note: Every class in the Personnel application has a "finalize" method,
but for the sake of simplicity these methods are not invoked. You
should always write "finalize" methods for your classes and make sure
you invoke them. Finalize methods destroy objects and release the
resources they were using. For more information on finalizing see the
section Destroying Objects in the chapter Using Objects in Programs.

Object-oriented Programming with COBOL

oppubb.book Page 113 Tuesday, March 16, 2004 12:23 PM

Exploring the Personnel Classes

Exploring the Personnel Classes


Before we animate the personnel application, its worth exploring the
code to view the syntax for multiple inheritance and object properties.
To do this, follow these steps:
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory. For information about using Infomgr,
see the chapter Infomgr in your Utilities Guide

Open the file IndPlacement.cbl in the Editor.

Find the CLASS-ID header at the beginning of the source code.


The IndPlacement source code starts with the CLASS-ID header. This
reads:
class-id. IndPlacement as "IndPlacement"
inherits Student Employee.

In other words, IndPlacement inherits from two classes.


4

Now scroll down to find the methods in IndPlacment.cbl.


IndPlacement has one factory method, "newIndPlacement", and
instance methods to display and finalize an IndPlacement object.
However, because it inherits from Student and Employee, it also
inherits all the methods in those classes.
Where a class provides a method of the same name as one or more
classes that it inherits from, as is the case here with "display" and
"finalize", you have to code the OVERRIDE clause in the Method-ID
paragraph to indicate that the method in the subclass overrides the
method in the superclass.
If a subclass inherits from two classes that contain methods of the
same name, and it does not itself contain a method of that name,
then the subclass inherits the method of the class that is named first
in the Class-ID paragraph.

Close IndPlacement.cbl and open the file Employee.cbl

Scroll to the end of the code.The last two methods in the Employee
class are GETJOBTITLE and SETJOBTITLE. These are methods that

Object-oriented Programming with COBOL

113

oppubb.book Page 114 Tuesday, March 16, 2004 12:23 PM

114

Chapter 10 More Complex Class Tutorial

have been generated automatically through the use of the object


property syntax.
To see the syntax, scroll up through the code until you come to the
data definition for jobTitle. This reads:
01

jobTitle usage object reference CharString property.

The property keyword indicates that you want the Compiler to


generate simple get and set methods The get method returns the
contents of the jobTitle data item, and the set method sets the
contents of the jobTitle data item to a certain value.
Well see how these methods are called when we animate the
application.
7

Close Employee.cbl

Animating the Personnel Application


The main program of the personnel application, personnel.cbl, is not an
object-oriented program. It is a procedural program that uses classes.
To animate the personnel application:
1

Run the supplied shell script persscrp. This compiles all the source
code files for animation.

Start animating the personnel application. Enter the following


command line:
anim personnel

Set a breakpoint on the line after P005:


set jobtitle of emp1

to make it easy to return here from deep in the class hierarchy.


4

Step the first statement, which creates a new employee, with data
items name and date of birth. You are now at the first statement of
the method "newEmployee" in employee.cbl. Note that this
statement uses the predefined object reference SUPER to indicate
that the method to be invoked is in the superclass, Person.

Object-oriented Programming with COBOL

oppubb.book Page 115 Tuesday, March 16, 2004 12:23 PM

Animating the Personnel Application

Step this statement. You now move up the inheritance chain again,
to Person; you are at the first statement of the method
"newPerson" in person.cbl. Again, this method invocation uses the
predefined object reference SUPER to indicate that the method to
be invoked is in the superclass. The method is the "new" method of
Base, the class from which most classes ultimately inherit.

Step this statement. The "new" method of Base is executed but you
do not go into the source code for Base since it is part of a class
library.

Step the next statement; this invokes the "initPerson" method in


the Person class, which initalizes the new object with values for the
data items lk-personName and lk-dob.

The next statement, the first in the "initPerson" method, uses inline
method invocation to call the newString method of the utility class
CharString, which allocates memory for and creates strings of any
length. The statement:
move CharString::"newstring"(lk-personName) to personName

is equivalent to:
01 tempObject usage object reference CharString
.
.
.
invoke CharString "newstring" using lk-personName
returning tempObject
setpersonName to tempObject

Unless you want to explore the behavior of the CharString class,


press Z to complete the creation of strings holding the name and
date of birth of the first employee.
9

You should now be at the breakpoint that you set in the main
program, personnel.cbl. Step the next statement, which invokes
CharString to create a string for the job title of the employee.

10 Perform Step the next three statements: press P then S three times.
You are now in the set property method for the data item jobTitle.
This is a method that was automatically generated when you
compiled employee.cbl, because jobTitle was defined with the
object property syntax.
11 Step through this method until you return to personnel.cbl.

Object-oriented Programming with COBOL

115

oppubb.book Page 116 Tuesday, March 16, 2004 12:23 PM

116

Chapter 10 More Complex Class Tutorial

12 Scroll down until you find the line below the tag P010:
invoke IndPlacement "newindplacement" using "John White"
"23/07/81"

With the cursor on this line press B then Z to zoom to the cursor
position. A second employee is created, with name, date of birth
and job title.
13 The statement that you have halted on creates an object of class
IndPlacement (industrial placement). This is the class that inherits
from both Employee and Student. Step this statement. You move to
the first statement of the newIndPlacement method of the
IndPlacement class.
14 Step this statement. You might expect this to invoke the
newEmployee method of the Employee class, or the newStudent
method of the Student class. But since both of these call the
newPerson method of the Person class, it makes more sense to call
the newPerson method directly.
15 Press P then S four times. . This creates the new person with name
and date of birth.
16 You should now be back in the main program, personnel.cbl. Press
P, then S. ; this calls CharString to create a string for the job title of
the industrial placement.
17 Step the next statement, which calls CharString to create a string for
the course title of the industrial placement.
18 Press P then S three times.. You are now in another automatically
generated set method, but this time it is a method of the Student
class. It sets the course title of the student - in this case, our
industrial placement.
19 Step through this method until you return to personnel.cbl.
20 The next part of this tutorial illustrates object views. Before we
continue, find the data definition for personTable: position the
cursor on personTable(3) in the next statement and press L then C.
The data definition is:
01 personTable occurs 3 times usage object reference
Person.

personTable is a typed object reference: it can hold only object


references of the Person class.

Object-oriented Programming with COBOL

oppubb.book Page 117 Tuesday, March 16, 2004 12:23 PM

Animating the Personnel Application

21 Press P then S. This creates a new Person, person1.


22 Step the next statement. This sets the third object reference in
personTable to person1, the person we just created.
23 Step the next statement. This sets the first object reference in
personTable to emp1, the first employee we created. This is fine,
because we can always set an object reference of a particular class
to an object reference of a subclass.
24 Step the next statement. This sets the second object reference in
personTable to indPlace1, the industrial placement we created. This
is also fine, since IndPlacement is also a subclass of Person.
25 Step the next statement. This sets the object reference emp3 to the
first object reference in personTable. If the statement was simply:
set emp3 to personTable(1)

we would get a syntax error, because this is not allowed. It is not


allowed because personTable(1) might not be pointing to an
employee object. However, since we know that at this point in the
program it does point to an employee object, we can write:
set emp3 to personTable(1) as employee

A check is made at run time that the object reference is of the


correct type, and an error is reported if the check fails.
26 The next few lines of code (between tags P015 and P020) provide a
way of avoiding the run-time error by using an IF statement that
uses a Micro Focus OO COBOL extension, the "INSTANCE OF" syntax.
Step through this code. You see OK appear in the Application
Output window, confirming that personTable(1) was pointing to an
employee object.
27 The next few lines of code (under tag P020) illustrate polymorphism.
The class Person implements the interface Displayable so all its
subclasses also implement it. However, all the subclasses provide
their own "display" method, overriding the one in Person. The OO
run-time system know what class each object reference in
personTable is and invokes the appropriate "display" method for
each object. Well take a look at the display method of employee.
Step the next four statements. You are now in employee.cbl, at the
first line of its "display" method.

Object-oriented Programming with COBOL

117

oppubb.book Page 118 Tuesday, March 16, 2004 12:23 PM

118

Chapter 10 More Complex Class Tutorial

28 Press P then S to execute the next statement in one go. This invokes
the "display" method of the class Person, which displays just the
items that are common to all persons: name and and date of birth.
You can step through the "display" method of Person if you want
to take a closer look at the code).
29 Step through the next two statements, which display "Job title: " in
the Application Output window.
30 Press P then S. This invokes the "displayNl" method of the utility
class CharString, which displays the job title without advancing.
31 Step the next statement. You return to the end of the perform loop
in personnel.cbl.
32 Step the next two statements, then press P then S. This invokes the
"display" method of IndPlacement, because the next object in
personTable is an indPlacement object. You can see the course title
being displayed as well as the name and date of birth.
33 Step the next two statements, then press P then S. This invokes the
"display" method of Person, because the final object in personTable
is a Person object. Only the name and date of birth are displayed.
34 Step to the end of the program.
35 Press B then C to clear the breakpoint you set in step 2.
36 Press Escape to stop the Animator.

Summary
In this tutorial you have learned:

How to use inline method invocation

How to use object properties to generate get and set methods

How to use object views to set object references going up the class
hierarchy

How multiple inheritance works

Object-oriented Programming with COBOL

oppubb.book Page 119 Tuesday, March 16, 2004 12:23 PM

119

11 Interfaces and Parameterized


Class Tutorial
In this tutorial you learn how to write and use interfaces and
parameterized classes.

The PClass Application


This section introduces the classes used in this tutorial. We will use the
Net Express development environment to explore the code in these
classes, before animating it in the second part of this tutorial.
The Pclass application uses the following classes:

Person

Employee

Student

IndPlacement

CharString

Motor

Vehicle

Car

PLinkList

LEntry

The first five of these classes were used in the chapter More Complex
Class Tutorial; they have the same functions in this tutorial. To remind
yourself of the relationships between the first four classes see the

Object-oriented Programming with COBOL

oppubb.book Page 120 Tuesday, March 16, 2004 12:23 PM

120

Chapter 11 Interfaces and Parameterized Class Tutorial

figure Classes in Personnel Application in the section The Personnel


Application in that chapter.
The next three classes in the list form a hierarchy, as shown in
Figure 11-1:
Figure 11-1. Classes in Pclass Application

Person and Car both implement the interface Displayable: this means
that they must both contain a display method to replace the display
method prototype in the Displayable interface.
PLinkList is a parameterized class, that is, a class that has one or more
formal parameters, which are replaced at run time by real parameters.
Parameterized classes allow you to re-use the same code to create many
similar classes. The classes that are created from PLinkList create and
maintain a linked list of objects. LEntry is a class that is used in
conjunction with PLinkList.
CharString, Person, Vehicle and PLinkList all inherit from Base.
Note: Some of the classes in the Pclass application have "finalize"
methods, but for the sake of simplicity these methods are not invoked.
You should always write "finalize" methods for your classes and make
sure you invoke them. Finalize methods destroy objects and release the
Object-oriented Programming with COBOL

oppubb.book Page 121 Tuesday, March 16, 2004 12:23 PM

Exploring the Pclass Classes

resources they were using. For more information on finalizing see the
section Destroying Objects in the chapter Using Objects in Programs.

Exploring the Pclass Classes


Before we animate the application, its worth exploring the code to
view the syntax for interfaces and parameterized classes. To do this,
follow these steps:
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory. For information about using Infomgr,
see the chapter Infomgr in your Utilities Guide

Open the file Displayable.cbl, the source file for the Displayable
interface, in the Editor. You can see that the interface consists of
just one method, "display", and that this contains no code that does
anything, just headers and an end marker. A method like this is
called a method prototype. An object that implements the
Displayable interface must supply a real "display" method to
replace the prototype. If the method protototype specifies
parameters, the implementing objects must supply methods with
matching parameters.

Close Displayable.cbl and open the file Car.cbl.

Scroll down until you come to the line that defines the car object:
object. implements Displayable.

This states that objects of the Car class must be displayable, that is
there must be a method in the Object part of the class that specifies
how Car objects are to be displayed. You can see by scrolling down
that the Car class does indeed include a display method.
Well see how these methods are called when we animate the
application.
5

Close Car.cbl and open the file PLinkList.cbl. The source code begins
with the CLASS-ID header:
class-id. PLinkList as "PLinkList" inherits Base
using fparam1.

Object-oriented Programming with COBOL

121

oppubb.book Page 122 Tuesday, March 16, 2004 12:23 PM

122

Chapter 11 Interfaces and Parameterized Class Tutorial

The syntax "using fparam1" indicates that this is a parameterized


class that takes one formal parameter. The conditional compilation
code at the beginning of the Repository paragraph:
$if formalParam = "interface"
interface fparam1
$else
class fparam1

allows this parameterized class to take either a class or an interface


as a formal parameter.
The Compiler directive in the supplied shell script pclascrp:
actual-params(DLinkList Displayable)

provides the actual parameters. The first entry inside the braces is
the name of the normal class that is generated at compile time,
DLinkList in this case. The second parameter is the name of the class
or interface that the normal class references. In this case we are
using the parameterized class PLinkList to create a normal class
DLinkList that manipulates objects that implement the Displayable
interface.
By specifying a class as the actual parameter, you could use the same
parameterized class to create a normal class that manipulates
objects that are all of the same class.
The next Compiler directive:
constant formalParam "interface"

informs the parameterized class that on this occasion it is being


used to create a class that takes an interface as a parameter, rather
than a class.
We will see how other classes refer to the class created from
PLinkList when we animate the application.
6

Close PLinkList.cbl

Object-oriented Programming with COBOL

oppubb.book Page 123 Tuesday, March 16, 2004 12:23 PM

Animating the Pclass Application

Animating the Pclass Application


The main program of the personnel application, pclass.cbl, is not an
object-oriented program. It is a procedural program that uses classes.
To animate the pclass application:
1

Run the supplied shell script pclascrp. This compiles all the source
code files for animation.

Start animating the pclass. Enter the following command line:


anim pclass

Scroll down until you find the statement after tag P005:
set car1 to Car::"newcar"("Mini", 4, 6)

Position the cursor on this statement and press B then Z to zoom to


the cursor position.
This creates two objects, an employee and an industrial
emplacement, using the same code as in the personnel application
described in the chapter More Complex Class Tutorial.
4

The next two statements create two new car objects. Step through
the code for the first object, car1, if you want to see the details of
the object creation process. Otherwise press P then S twice.

Step the next four lines, which illustrate the ability to set object
references to an object that implements an interface. The object
displayItem, defined in pclass.cbl as:
01 displayItem usage object reference Displayable.

can only be used to refer to objects that implement the Displayable


interface. If you attempt to set it to an object that does not
implement this interface, the Compiler will detect and report the
error as part of its conformance checking.
6

The code between tags P015 and P020 show that object views and
the Micro Focus OO COBOL extension, the "INSTANCE OF" syntax,
work with interfaces as well as with classes. Step through this code
if you want to investigate the details. Otherwise scroll down to the
first line of code after tag P020, position the cursor on that line and
press B then Z.

Object-oriented Programming with COBOL

123

oppubb.book Page 124 Tuesday, March 16, 2004 12:23 PM

124

Chapter 11 Interfaces and Parameterized Class Tutorial

The next few lines show how the class DLinkList, created from the
parameterized class PLinkList, is used. Press P then S to execute the
statement:
set displayList to DLinkList::"new"

This creates a new DLinkList object using inline method invocation,


and sets the object reference displayList to point to this object. A
DlinkList object is a linked list that can hold objects that implement
the Displayable interface.
8

The next four lines add four objects to the linked list by invoking
the "add" method of the DLink List class. These are of disparate
classes, but because they all implement Displayable, they can all be
added to the list. If you attempt to add an object that does not
implement this interface, the Compiler will detect and report the
error as part of its conformance checking.
If you are interested in seeing how the code to add an object to the
linked list works, step the next statement, and all the statements
executed as a result of the method invocation in it.

Position your cursor on the statement after tag P025, and to add
objects to the list.

10 The code between tag P025 and the end of the program displays
each item in the list in turn, calling each objects specific "display"
method. If you are interested in seeing how the code to display an
object in the linked list works, step though the first iteration.
11 Press Z to complete the program. You will see the information
being displayed in the Application Output Window.
12 Press Escape to stop the Animator.

Summary
In this tutorial you have learned:

How to use interfaces.

How to use parameterized classes.

Object-oriented Programming with COBOL

oppubb.book Page 125 Tuesday, March 16, 2004 12:23 PM

125

Part 4: Micro Focus OO COBOL


Alternatives and Extensions
This part contains the following chapters:

Chapter 12, Micro Focus OO COBOL Alternative Syntax

Chapter 13, Requirements-based Vocabulary

Object-oriented Programming with COBOL

oppubb.book Page 126 Tuesday, March 16, 2004 12:23 PM

126 Part 4: Micro Focus OO COBOL Alternatives and Extensions

Object-oriented Programming with COBOL

oppubb.book Page 127 Tuesday, March 16, 2004 12:23 PM

127

12 Micro Focus OO COBOL


Alternative Syntax
This chapter describes the Micro Focus syntax and mechanisms that
provide alternatives and extensions to the ISO 2000 syntax

Summary of Syntax Alternatives


The following table shows an outline of a class coded using the ISO
2002 OO COBOL syntax in the left-hand column and the same class
coded using the Micro Focus alternative syntax in the right-hand
column. Your COBOL system supports all the syntax in both columns.

Object-oriented Programming with COBOL

oppubb.book Page 128 Tuesday, March 16, 2004 12:23 PM

128

Chapter 12 Micro Focus OO COBOL Alternative Syntax

Not all the syntax available is shown; for full details of all the OO
COBOL syntax see your Language Reference.
ISO 2002 OO COBOL Syntax

Micro Focus OO COBOL Syntax

class-id. Example inherits


from Base.
environment division.
...
configuration section.
repository.
class Example as "exmp"
class Base as "base"
class CharacterArray.

class-id. Example inherits


from Base.
environment division.
...
object section.
class-control.
Example is class "exmp"
Base is class "base"
CharacterArray
is class "chararry".
data division.
...
class-object
data division.
object-storage section.
...
method-id.
"newWithData".
...
end method
"newWithData".
end class-object.

...
factory.
data division.
working-storage section.
...
method-id.
"newWithData".
...
end method
"newWithData".
end-factory.
object.
working-storage section.
...
method-id.
"sayHello".
...
end method
"sayHello".
end object.
end class Example.

object.
object-storage section.
...
method-id. "sayHello".
...
end method "sayHello".
end object.
end class Example.

Shared Data
In Micro Focus OO COBOL you can code a Data Division in the class
source element. This Data Division can contain a Working-Storage
Section only. Data defined in this Working-Storage Section is known as

Object-oriented Programming with COBOL

oppubb.book Page 129 Tuesday, March 16, 2004 12:23 PM

Working-Storage Section in a Method

shared data, because it is accessible from class methods (factory


methods) and instance methods.

Working-Storage Section in a Method


In Micro Focus COBOL you can use working storage for temporary
variables inside a method, but this remains permanently allocated, and
is shared by all invocations of the method, in all objects of the same
class. This means that it is not suitable for any method that could be
invoked recursively or in a multi-threaded environment. For example,
method "setData" in object A1 (an instance of class A) invokes method
"getDetails" in object B1. The method in object B1 does a "setData" in
object A2 (also an instance of class A). Any data in working storage from
the original invocation of "setData" (which has not yet finished
execution) is overwritten by the second invocation. Local storage data
for the two invocations of "setData" would be kept completely
separate.

Working Storage and Object Storage


In Micro Focus OO COBOL you store class object data in the ObjectStorage Section of the class object source element, and instance object
data in the Object-Storage Section of the object source element. In ISO
2002 OO COBOL, you store this data in the Working-Storage Sections of
the factory and object source elements. A setting of the OOCTRL
Compiler directive controls how the Compiler treats Working-Storage
Sections.

If you set OOCTRL(+W), the Compiler interprets the Working


Storage Section in a factory (class object) or instance object source
element as an Object-Storage Section. You should not code an
Object-Storage Section too. This is the default.

If you set OOCTRL(-W), the Compiler interprets the Working Storage


Section in a factory (class object) or instance object source element
as a Working-Storage Section. You can code an Object-Storage
Section too. The scope of the Working-Storage Section is restricted

Object-oriented Programming with COBOL

129

oppubb.book Page 130 Tuesday, March 16, 2004 12:23 PM

130

Chapter 12 Micro Focus OO COBOL Alternative Syntax

to the factory (class object) or instance object in which the section


appears.

Data Inheritance
Data inheritance in Micro Focus OO COBOL has a richer meaning than
the same term in ISO 2002 OO COBOL. In ISO 2002 OO COBOL, data
inheritance is the ability of a factory object to access data declared in
the factory object of an inherited class through the factory methods of
that class, and also the ability of an instance object to access data
declared in the instance object of an inherited class through the
instance methods of that class. Micro Focus OO COBOL supplies this
same ability. In addition, in Micro Focus OO COBOL you can use syntax
that enables your subclasses to access data declared in inherited classes
directly. This is called direct data inheritance.
A class can optionally directly inherit the data declared in the ObjectStorage Sections of its superclass. The next two sections explain:

How to control direct data inheritance in your source code

How direct data inheritance works at run time

Direct Data Inheritance in Source Code


Inheritance of data is controlled by two optional clauses in the CLASS-ID
header at the beginning of the class.
The first of these, DATA IS PROTECTED, enables subclasses to access the
classs own data directly. (There is a synonym for this phrase, DATA IS
RESTRICTED). The second of these, WITH DATA, enables a class to access
its superclasss data directly. For example:
class-id. B data is protected
inherits from A
with data.

This says that B inherits all the data in A, and that any subclass of B can
also inherit Bs data (which would include As data).

Object-oriented Programming with COBOL

oppubb.book Page 131 Tuesday, March 16, 2004 12:23 PM

Data Inheritance

When you compile class B, the WITH DATA clause causes the Checker to
look for two files: a.cls and a.ins.
You cannot use multiple inheritance (allowed in ISO 2002 syntax) and
the Micro Focus WITH DATA clause in the same Class-ID paragraph. For
example, the following code is illegal:
class-id. C inherits from A, B
with data.

The .cls file is a COBOL copyfile containing the data definitions for the
class object data and the .ins file is a copyfile containing the data
definitions for the instance data. The Checker inserts these
automatically at the start of the Object-Storage Sections for class and
instance data when it compiles the source code for class B.
The DATA IS PROTECTED clause causes the COBOL Checker to generate
two files: b.cls and b.ins. These copyfiles start with all the definitions for
inherited data, which is followed by the definitions for any class or
instance data declared in class B.
The use of copyfiles to implement data inheritance has the following
implications:

Where you have classes inheriting data, they must be compiled from
the top down, starting with the superclass, so that the .ins and .cls
files are available when you compile the subclasses.

The .cls and .ins files for superclasses must either be in the same
directory as classes which inherit their data, or in a directory on your
COBCPY environment variable.

You might want to prevent subclasses from inheriting data, in which


case you can either omit the DATA IS PROTECTED clause or replace it by
DATA IS PRIVATE. This stops the Checker from creating the .cls and .ins
copyfiles. The following Class-ID header would mean that B still
inherited As data, but that subclasses of B would not be able to inherit
Bs data:
class-id. B data is private
inherits from A
with data.

You might code another class that starts like this:


class-id. C data is protected
inherits from B
with data.

Object-oriented Programming with COBOL

131

oppubb.book Page 132 Tuesday, March 16, 2004 12:23 PM

132

Chapter 12 Micro Focus OO COBOL Alternative Syntax

When you try to compile the class for C, the Compiler will stop with the
following message:
FILE below not found - Stop/Retry/Continue/Alter-path:
B.CLS

Unless you can give the Compiler a path where it can find a copy of
b.cls, you will have to stop the compilation, and alter the source code
for C so that it no longer tries to inherit data from B.
Note: If you change a class from having protected data to private data,
the Compiler does not delete its .cls and .ins files if they already exist.

Direct Data Inheritance at Run Time


When you inherit data from a superclass, the Compiler puts a copy of all
the class object data definitions from the superclass in your class ObjectStorage Section, and a copy of all the instance object data definitions in
your instance Object-Storage Section.
The diagram in Figure 12-1 shows three classes, A, B and C. C inherits
from B without data, and B inherits from A with data. Class A
implements instance method "setInDataA" which sets a value into data
item instanceItemA. On the right-hand side of the dotted line are three
instance objects, A1, B1 and C1, created at run time by class objects A, B
and C.
If object B1 gets the message "setInDataA", the message gets executed
by the instance method implemented in A (because B does not
implement this method). However, the data item that gets updated is
instanceItemA held in instance object B1s storage.
Because class B inherits from A with data, the source code in class B can
also manipulate instanceItemA directly. For example, the programmer
for class B could code an instance method containing the statement:
move "!" to instanceItemA

Object C1 also has memory allocated for instanceItemA and


instanceItemB in its Object-Storage Section at run time. However,
because it does not inherit with data, the Checker does not know the
definitions of these items when Class C is compiled. The value for

Object-oriented Programming with COBOL

oppubb.book Page 133 Tuesday, March 16, 2004 12:23 PM

Data Inheritance

instanceItemA can only be set by sending class object C the


"setInDataA" message.
Coding:
move "!" to instanceItemA

in an instance method of C would be rejected by the Checker at


compile-time. The programmer of Class C can set instanceItemA by
coding inside an instance method:
invoke self "setInDataA" using "!"

This sends the "setInData" message to instance object C1 at run time,


and it gets passed up the inheritance chain until it reaches class A. The
object reference SELF is a reserved name which always refers to the
object in which it occurs (see the section Predefined Object Reference
Names in the chapter Methods).
Figure 12-1. Data Inheritance

Object-oriented Programming with COBOL

133

oppubb.book Page 134 Tuesday, March 16, 2004 12:23 PM

134

Chapter 12 Micro Focus OO COBOL Alternative Syntax

Extending a Class
Extending a class enables you to add new methods to an OO COBOL
class without changing the original source code. Class extension is a
Micro Focus OO COBOL extension.
The difference between extending a class and subclassing it is that the
extensions are inherited by all existing subclasses.
For example, if class A has a subclass, class B, you can add functionality
to class A by subclassing it to create subclass C. However, class B will not
inherit the functionality of class C, because it is a subclass of A. If you
extend class A with a class extension, X, the effect at run time is the
same as if you had changed and recompiled class A. Class B inherits all
the extra functionality in class X.
To extend a class, write a class program where the class header looks
like this:
class-id. ExtensionName extend OriginalClass [with data].

The Class-Control paragraph must contain references to the extension


class and the class which it extends. Use the WITH DATA clause to
enable the extension class to reference class and instance data of the
original class directly. The extension class cannot declare new class or
instance data of its own, although it can declare its own working
storage.
To use the class extension, you must insert a COBOL CALL to it at any
point in application execution before the class extensions are used, to
register the new methods with the run-time system.
The three short classes below show how class extension works. Class A is
a subclass of Base and class B is a subclass of A. Neither of these classes
have any methods. Class Axtnd is a class extension for A.
Class A:
class-id. a inherits from base.
class-control.
a is class "a"
base is class "base"
.

Object-oriented Programming with COBOL

oppubb.book Page 135 Tuesday, March 16, 2004 12:23 PM

Extending a Class

class-object.
end class-object.
object.
end object.
end class a.

Class B:
class-id. b inherits from a.
class-control.
b is class "b"
a is class "a"
.
class-object.
end class-object.
object.
end object.
end class b.

Class Axtnd (the extension of class A) implements a single instance


method:
class-id. axtnd extend a.
class-control.
axtnd is class "axtnd"
a is class "a"
.
object.
method-id. "extendMethod".
procedure division.
display "Im an extension"
exit method.
end method "extendMethod".
end object.
end class axtnd.

Object-oriented Programming with COBOL

135

oppubb.book Page 136 Tuesday, March 16, 2004 12:23 PM

136

Chapter 12 Micro Focus OO COBOL Alternative Syntax

The next piece of code is a short test which shows how the extension
works:
program-id. ExtensionTest.
class-control.
a is class "a"
b is class "b"
.
working-storage section.
01 thisB
object reference.
procedure division.
call "axtnd"
*> Load class extension
invoke b "new"
returning thisB *> Create instance of B
invoke thisB "extendmethod" *> Send a message
stop run.

When you run the ExtensionTest program, it loads class Axtnd. All
methods implemented in this class are now accessible as though they
were methods of class A. When the test program sends the
"extendMethod" message to an instance of class B, the extension
method is executed, as though it were implemented in class A and
inherited by class B.

Object-oriented Programming with COBOL

oppubb.book Page 137 Tuesday, March 16, 2004 12:23 PM

137

13 Requirements-based
Vocabulary
Requirements-based vocabulary enables you to define new COBOL
verbs and functions for use with the objects you have created. This
chapter explains the syntax for defining these new verbs and functions.
Requirements-based vocabulary is a Micro Focus extension. All the code
shown in this chapter uses the Micro Focus alternatives to the ISO 2002
syntax.

Overview
As an alternative message-sending mechanism to the INVOKE verb, you
can create your own new COBOL verbs and functions. For example, you
could create a new verb, CREDIT, enabling you to write:
credit aBankAccount with amount

To use this syntax in a program, you have to include a class interface


definition at the start of your program or class. Interface definitions
are declared through external classes. An external class has the
structure of a class, and defines all of the class and instance methods of
the class, but does not contain any of the code for the methods.
By convention, each external class is held in a .if file, and programs
using vocabularies use COPY statements to include the class definition.
The COPY statements must appear before the Class-ID header.
There are three steps to using requirements-based vocabularies:
1

Define a vocabulary for an object (or for a set of objects). The


vocabulary for each object is defined in an external class.

Include the external classes at the start of each program (or class)
which invokes objects through a vocabulary.

Object-oriented Programming with COBOL

oppubb.book Page 138 Tuesday, March 16, 2004 12:23 PM

138

Chapter 13 Requirements-based Vocabulary

Use the verbs and functions defined by the vocabulary to send


messages to objects.

In many cases, step 1 will be the responsibility of different programmers


to steps 2 and 3. One group of programmers is given the task of
designing objects for an organizations own class library, while other
groups use the objects from the class library as the building blocks to
create business applications.
The class library designers would take charge of defining the vocabulary
(step 1 above) for objects in the class library, ensuring that it was
consistent and readable. The application builders would use the
vocabularies (steps 2 and 3) to simplify their own development work,
and to enhance the readability of their applications.

Defining a Vocabulary
You define vocabularies on a class basis. Each vocabulary is defined by
an external class. An external class is a program that defines a set of
method interfaces, but does not include any code.

External Class Structure


External classes have the same basic structure as any OO COBOL class.
The outline structure for the BankAccount external class is shown
below:
class-id. BankAccount is external
inherits from Base
object section.
class-control.
BankAccount is class "account"
Base is class "Base"
.
* Class methods.
class-id. "new"
* Method interface definition.
end program "new".
...

Object-oriented Programming with COBOL

oppubb.book Page 139 Tuesday, March 16, 2004 12:23 PM

Defining a Vocabulary

* Object program.
object.
* Instance methods
end object.
end class BankAccount.

The only differences between the external class definition for


BankAccount, and the BankAccount class itself, are:

The Class-ID paragraph defines the class as EXTERNAL

There is no Object-Storage Section in the class or object program

There is no class Procedure Division

Each method program contains only an interface definition

Method Interface
A method program interface definition has the following elements:

Method-ID paragraph

Linkage Section

PROCEDURE DIVISION header

verb or function signature

END METHOD header

No storage is declared, and there is no code in the Procedure Division.


The method interface for the credit method looks like this:
method-id. credit is method.
linkage section.
01 lnkAmount
pic 9(10)v99.
procedure division using lnkAmount
INVOKED AS ==Credit <self> [with] <lnkAmount> ==
OR AS ==deposit <lnkAmount> [in] <self> ==
.
end method credit.

Object-oriented Programming with COBOL

139

oppubb.book Page 140 Tuesday, March 16, 2004 12:23 PM

140

Chapter 13 Requirements-based Vocabulary

The elements of the new syntax definition are:


Delimiters

The INVOKED AS phrase indicates the start of


the verb or function signature syntax. Each
signature is bracketed by double equals "==".
You can specify multiple definitions for a
method by using the OR AS phrase.

Parameters

Appear inside angle brackets "<>". All


parameters must be passed by reference in the
PROCEDURE DIVISION USING statement.
<SELF> is a special parameter which marks the
point where the sender puts the object
reference for the method. <SELF> must always
appear once (and only once) in the interface
definition. You can also use <THIS> and
<OBJECT> as synonyms for <SELF>.

Compulsory words

Appear exactly as they are to be used.

Noise words

Appear inside square brackets "[ ]". Noise words


enable you to make your new verbs and
functions more readable. In the example above,
you can use both these ways to invoke the credit
method:
credit anAccount with aSumOfMoney
credit anaccount aSumOfMoney

By default, the following are disallowed in the verb signatures of


method interface definitions:

The use of IN or OF in any place that could possibly follow a data


name.

The use of any COBOL verb.

You can enable the use of both these in verb signatures by setting
compiler directive OOCTRL(-Q). Setting this directive disables the use of
qualification in a verb signature which invokes a method. The default
setting is OOCTRL(+Q).

Object-oriented Programming with COBOL

oppubb.book Page 141 Tuesday, March 16, 2004 12:23 PM

Using Vocabulary-defined Verbs and Functions

User-defined Functions
You can also create new functions with user vocabularies. The new
functions look like COBOL intrinsic functions when used in a program.
For example, you could code:
compute interest = .06 * function balance (thisBankAccount)

You can omit the keyword function, so you could also write:
compute interest = .06 * balance (thisBankAccount)

The definition of function balance looks like this:


method-id. "getBalance".
linkage section.
01 lsAmount pic S9(10)v99.
procedure division returning lsAmount
INVOKED AS FUNCTION == Balance ( <self> ) ==.
end method "getbalance".

Using Vocabulary-defined Verbs and


Functions
To use vocabulary defined verbs or functions:
1

Include the external class defining the new syntax in your program
as a copyfile, using a COPY statement. By convention these are
stored in .if files.
If you are using several objects with their own vocabulary
definitions, you must include the external class for each one. Put
external classes at the top of the source code, before the
Identification Division.

Use the vocabulary defined for the object in place of an INVOKE


verb and method name when you want to send the object a
message.

Object-oriented Programming with COBOL

141

oppubb.book Page 142 Tuesday, March 16, 2004 12:23 PM

142

Chapter 13 Requirements-based Vocabulary

The Micro Focus class libraries supplied with your COBOL system include
external classes with vocabularies for the following types of
manipulation:.
chararray.if

String manipulation verbs

symbtab.if

SymbolTable manipulation verbs

Net Express:

guibase.if

Event mapping verbs

Net Express:

sdiframe.if

GUI application framework verbs

One advantage that vocabularies give you is that data values are cast
into the format expected by the target method. For example, you can
code:
credit anAccount with 5

The interface definition at the start of the program enables the


Compiler to convert the number 5 into the numeric format expected by
the method. The equivalent using standard OO COBOL requires two
statements:
move 5 to anAmount
invoke anAccount "credit" using anAmount

For an example that uses requirements-based vocabulary, see the


chapter Requirements-based Vocabulary Tutorial.

Object-oriented Programming with COBOL

oppubb.book Page 143 Tuesday, March 16, 2004 12:23 PM

143

Part 5: Micro Focus Class


Libraries
This part contains the following chapters:

Chapter 14, Introduction to the Class Libraries

Chapter 15, Collection Frameworks

Chapter 16, Intrinsic Data

Chapter 17, Callback Frameworks

Chapter 18, Exception Handling Frameworks

Chapter 19, Component Frameworks

Object-oriented Programming with COBOL

oppubb.book Page 144 Tuesday, March 16, 2004 12:23 PM

144 Part 5: Micro Focus Class Libraries

Object-oriented Programming with COBOL

oppubb.book Page 145 Tuesday, March 16, 2004 12:23 PM

145

14 Introduction to the Class


Libraries
This chapter introduces you to the Micro Focus class libraries supplied
with your COBOL system, and tells you how you can find out more
about them.

Overview
The following class libraries are supplied:

Base
The Base Class Library provides COBOL classes for basic system
support. It also provides classes for

Handling exceptions raised by objects

Treating COBOL intrinsic data types as objects

Managing collections of objects. These are very useful in OO


programming.

Java domain
Classes for Java/COBOL interworking.

Java classes for COBOL support


Java classes that enable you to send messages to COBOL data items.

Net Express:

GUI classes
Classes for creating and managing graphical applications that
exploit the Windows native interface. These include classes for
most of the common controls, including dialog boxes, entry fields,
pushbuttons, list boxes, and tree views.

Object-oriented Programming with COBOL

oppubb.book Page 146 Tuesday, March 16, 2004 12:23 PM

146

Chapter 14 Introduction to the Class Libraries

Object-orientation is a very natural way to write graphical


interfaces, with the objects that the end-user of an application sees
mapping onto the objects that the programmer writes. To partner
the GUI Class Library, Net Express includes a GUI Application
Template. This provides a starter set of classes for writing a GUI
application, which you can modify and extend. For further
information look up "GUI Application Template" in the Help Index.
Net Express:

COM
Classes that represent COM documents, servers, clients and controls.
It also has classes which wrap common COM interfaces, enabling
easy access to frequently used COM functions.

Net Express:

COM Component
Classes for working with COM components.

There are some references in the class library documentation to parts of


the class libraries that are private. Wherever something private is
documented, this is noted in the text. You should not subclass from
private classes, or make use of private methods in your OO COBOL
applications. Unless something in the documentation is marked as
private, you can assume that it is part of the public interface. Public and
private are explained in the sections below.
As well as this documentation, we supply the source code for the class
libraries. We supply this for the following reasons:

As additional examples of OO COBOL programming.

To enable you to see how the class libraries work.

To enable you to recompile and animate the class libraries sometimes this is helpful when debugging your own applications.

To enable you to change the class libraries if you need to (but see
the Warning note at the end of the section Animating the Class
Libraries).

Object-oriented Programming with COBOL

oppubb.book Page 147 Tuesday, March 16, 2004 12:23 PM

Public and Private Interfaces

Public and Private Interfaces


The public interface to the class libraries consists of those methods and
classes in the class libraries that are intended for use by programmers
creating OO COBOL applications.
The private interface to the class libraries consists of those methods and
classes that are not intended for use by programmers using the class
library. They are part of the implementation of the class libraries and
are subject to change in future releases.
Private methods are marked as such in the comments to the class library
source code.
The private interface also includes all class and instance data in class
library objects. You should not make direct use of this data in any
subclasses, but should use the methods in the superclass to get access to
this data.

Class Library Method Parameter Types


Methods in the supplied Micro Focus Class Library consistently use the
same COBOL data types for passing integers and boolean values. The
table below summarizes these:
Parameter

Declare as

Signed integers

PIC S9(9) COMP-5.

Unsigned integers

PIC X COMP-5

Booleans

Booleans
Where TRUE is numeric 1 and FALSE is
numeric 0.

PIC S9(9) COMP-5 and PIC X(4) COMP-5 are both 4-byte data types.
For consistency, we suggest you adopt these conventions when writing
your own classes.

Object-oriented Programming with COBOL

147

oppubb.book Page 148 Tuesday, March 16, 2004 12:23 PM

148

Chapter 14 Introduction to the Class Libraries

Class Library Documentation


The documentation for the class libraries is split into two:

Frameworks

Public interface to classes

The frameworks are documented in this manual. The public interface to


classes is documented in the Class Library Reference, which provides, for
every class in the class libraries, a description of:

The class

Every public class method (including inherited methods, excluding


those inherited from Base)

Every public instance method (including inherited methods,


excluding those inherited from Base)

Private methods are not documented. Methods inherited from Base are
not documented as all objects in the Base class Library inherit these,
except where they have been explicitly overridden. You can see these
methods, which are common to all objects, by looking at the
documentation for the Base class.
Net Express:

Server Express:

From the Net Express Help Contents click Reference, OO Class Library,
Class Library Reference, then click the Class Library Reference icon at
the foot of the help topic.
In the Server Express bookshelf, click Reference Help Topics, OO COBOL,
OO COBOL Class Library Reference.

Frameworks
Frameworks are the way in which different types of object interact
together. Individual class and instance objects have interfaces which
describe the way you communicate with that object.
A framework is a protocol used by several different types of object cooperating to implement a particular function. The other chapters in this

Object-oriented Programming with COBOL

oppubb.book Page 149 Tuesday, March 16, 2004 12:23 PM

Animating the Class Libraries

part of the book document the main frameworks used in the class
libraries. For example, the chapter Collection Frameworks describes the
messages a collection sends to its elements.

Animating the Class Libraries


You might want to be able to animate parts of the class libraries,
possibly to help you understand how they work, or maybe to help you
track down a bug in your own application. You can animate the
following class libraries:

Base

Net Express:

GUI

Net Express:

COM

We strongly recommend that you only try to animate one or two class
library programs at a time from your application.
The run-time system itself uses the class libraries during startup, so if
you attempt to animate a whole class library you might find yourself
stepping through code in which you are not interested before your
application is loaded.
Net Express:

To animate a class library:


1

Click Animate > Settings.

On the right-hand side of Animate Settings dialog box, check the


class libraries you want to animate:

Base Class Library

GUI Class Library

COM Class Library

Click OK.

Start animating your application.


As you step through your application, whenever you step onto a
statement that invokes a method in a class library you have checked

Object-oriented Programming with COBOL

149

oppubb.book Page 150 Tuesday, March 16, 2004 12:23 PM

150

Chapter 14 Introduction to the Class Libraries

for animation, execution switches to animating through the class


library code.
Server Express:

To animate the Base Class Library:


1

Run the supplied shell script, $COBDIR/src/oops/bldclanm.sh to


compile the class library for animation.

Set the OOSW environment variable:


OOSW=-l
export OOSW

This switch tells the run-time system not to load the class library
supplied with Server Express, but to use the individual class library
files you have just compiled. The class library files must either
appear on the path set in the environment variable COBDIR, or in
the current directory from which you run your application.
3

Start animating your application.


As you step through your application, whenever you step onto a
statement which invokes a method in the Base Class Library,
execution switches to animating through the class library code.

Warning: We strongly advise you not to make changes to the class


library sources. Implementation details are considered private, and may
change between releases. We do not prevent you from making these
changes, but cannot guarantee that they will be supported in future
releases.

Object-oriented Programming with COBOL

oppubb.book Page 151 Tuesday, March 16, 2004 12:23 PM

151

15 Collection Frameworks
This chapter introduces the frameworks used by the collection classes in
the Base Class Library. Collection frameworks are mainly concerned
with the communication between collections and the elements they
store.
All the code shown in this chapter uses the Micro Focus alternatives to
the ISO 2002 syntax.

Overview
The COBOL collection classes assume that their elements are objects. A
collection sends messages to its elements to get information such as
the elements size and content. Even when you store intrinsic data (as
opposed to objects), the collection uses the methods implemented in
the intrinsic classes and uses the INVOKE ... AS verb to send messages to
the data.
The elements stored in a collection need to include in their interface
the methods to respond to those messages. Default versions of most of
these are provided in the Base class, but you may want to override
these to provide different or more efficient behavior for particular
types of object.
You will also need to provide methods which conform to a particular
interface for the collection class sort and iterator methods.

Object-oriented Programming with COBOL

oppubb.book Page 152 Tuesday, March 16, 2004 12:23 PM

152

Chapter 15 Collection Frameworks

Different Categories of Collection


The different types of collection in the Base Class Library can all be
categorized by the following properties:

Indexed or non-indexed
You can access any particular element in an indexed collection by
giving its position. This is similar to using a conventional array. In
non-indexed collections, elements are not stored in a defined order.

Automatically or manually growable


Automatically growable collections get bigger when you exceed the
capacity for which you created the collection. A manually growable
collection only gets bigger when you send it the "grow" message.

Allow or disallow duplicate elements


Some collections disallow duplicate elements; trying to add an
element which has the same value as one already in the collection
will cause an exception.

Here are some of the collection classes available, with their properties:
Bag

Non-indexed, automatically growable, duplicates


allowed

Array

Indexed, manually growable, duplicates allowed

CharacterArray

Indexed, manually growable, duplicates allowed

OrderedCollection

Indexed by insertion order, automatically


growable, duplicates allowed

SortedCollection

Indexed by sort order, automatically growable,


duplicates allowed

ValueSet

Non-indexed, automatically growable, duplicate


values disallowed

IdentitySet

Non-indexed, automatically growable, duplicate


object handles disallowed

Dictionary

Indexed by key, automatically growable,


duplicate key values disallowed

IdentityDictionary

Indexed by key, automatically growable,


duplicate key object handles disallowed

Object-oriented Programming with COBOL

oppubb.book Page 153 Tuesday, March 16, 2004 12:23 PM

Different Categories of Collection

ValueSet and IdentitySet differ only in the way they determine


duplicate elements. ValueSets compare the values of elements and
disallows duplicate values; IdentitySets compare object references, and
disallow storing the same object more than once.
Dictionary and IdentityDictionary are special types of collection which
store key/data pairs. They determine duplicate keys in the same way
that ValueSet and IdentitySet determine duplicate elements.

Creating Collections
You can create a collection to store either objects (a collection of
references) or intrinsic data (a collection of values). A collection of
references can contain more than one sort of object, whereas a
collection of values is initialized for storing data of a particular type and
length.
Before you create a collection, you need to decide which type to create.
You need to decide:

Do you want it indexed or non-indexed?

Do you want it to disallow duplicates?

Do you want it to grow automatically when you exceed its initial


capacity?

The available types of collection cover most of the combinations above.


To create a collection of references, send the "ofReferences" message
to the class of collection you want to create passing the initial size and
template as parameters.
To create a collection of values:
1

Clone a template for the intrinsic data from one of the intrinsic data
classes; see the section the section Cloning an Intrinsic Data Class in
the chapter Intrinsic Data.

Send the "ofValues" message to the class of collection you want to


create passing the initial size and template as parameters.

Many of the collection classes have additional create methods. For


further information see the Class Library Reference.

Object-oriented Programming with COBOL

153

oppubb.book Page 154 Tuesday, March 16, 2004 12:23 PM

154

Chapter 15 Collection Frameworks

Creating Dictionaries
Dictionaries are a special sort of indexed collection, which store keydata pairs (known as associations). In a dictionary, the key is used as the
index when you store or retrieve the data. Dictionaries do not allow you
to store duplicate keys.
Like the other collection types, you can store either objects or intrinsic
data in a dictionary. In a dictionary though, either the key or the data
part can be an intrinsic or an object. This gives you the following
possible combinations for intrinsic or object storage:

Key and data portions both objects

Key as intrinsic and data as object

Key as object and data as intrinsic

Key and data portions both as intrinsic

If the keys are objects, they must provide methods for hashing and
equality comparisons. Objects like CharacterArray already provide these
methods, but if you are using your own types of objects as keys, you
need to provide your own mechanisms.
When you create a dictionary you have to give it a template so that it
knows how the key and data portions are to be stored. The template is
either the Association class, or a clone of the Association class.
The Association class is another clonable class, like the classes for
intrinsic data classes, used for creating templates for data storage. An
Association template actually consists of two templates; one for the key
and one for the data. To create any type of dictionary you need to
create an Association template.
Having created a template for your dictionary object, there are two
methods you can use to create a dictionary itself; "ofValues" or
"ofAssociations". A dictionary "ofValues" stores each element as a key
data pair. A dictionary "ofAssociations" stores each element as an
instance of the Association template you used to create the dictionary.

Object-oriented Programming with COBOL

oppubb.book Page 155 Tuesday, March 16, 2004 12:23 PM

Different Categories of Collection

A dictionary "ofAssociations" in effect stores three items for every entry


in the dictionary:

The association instance


An object that contains the key and data

The key contained inside the association


This could be an object or an intrinsic value

The data contained inside the association


This could be an object or an intrinsic value

A dictionary "ofValues" stores the key and data directly without


wrapping them inside an association object. When would you use a
dictionary "ofAssociations" and when would you use a dictionary
"ofValues"?
A dictionary "ofValues" is slightly more efficient at run time in terms of
speed and memory if you simply want to store data items against key
items. However, if your application uses associations elsewhere to
manage key/data pairs, a dictionary "ofAssociations" is a better choice
as the actual dictionary only stores the object handles to the
associations, and you dont have to extract the key and value from the
association before putting it in the dictionary.
The following example shows the creation of a dictionary with an
intrinsic key and data, and the creation of the templates.
00001
00002
00003
00004
00005
00006

local-storage section.
01 aKeyTemplate
object reference.
01 aDataTemplate
object reference.
01 anAssocTemplate
object reference.
01 aDictionary
object reference.
01 aLength
pic x(4) comp-5.

...
00020
00028
00029
00030
00031
00032
00033

procedure division.
...
move 3 to aLength
invoke CobolCompX "newClass" using aLength
returning aKeyTemplate
move 20 to aLength
invoke CobolPicX "newClass" using aLength
returning aDataTemplate

Object-oriented Programming with COBOL

155

oppubb.book Page 156 Tuesday, March 16, 2004 12:23 PM

156

Chapter 15 Collection Frameworks

00034
00035
00036
00037
00038
00039

invoke Association "newClass using aKeyTemplate


aDataTemplate
returning anAssocTemplate
invoke Dictionary "ofValues" using anAssocTemplate
aLength
returning aDictionary

Lines 1-6

Declares storage for the templates.

Lines 28-29

Creates a template for a PIC X(3) COMP-X numeric key.

Line 31-32

Creates a template for a PIC X(20) data portion.

Line 34

Creates an association template.

Line 37

Creates a dictionary of values with an initial size of 20


elements. This will grow to accommodate extra elements
once 20 elements have been added. Each grow operation
approximately doubles the size of the dictionary.

Working with CharacterArray Objects


A CharacterArray is an object that contains a string of any length.
CharacterArrays are a convenient way of passing strings as parameters
when sending messages or making calls.

Creating a CharacterArray Object


There are many ways to create a CharacterArray. The two most
convenient are listed below.

Use the "withValue" method:


invoke CharacterArray "withValue"
using zstring
returning aCharArray

Use the "withLengthValue" method:


invoke CharacterArray "withLengthValue"
using aLength aLiteral
returning aCharArra

Object-oriented Programming with COBOL

oppubb.book Page 157 Tuesday, March 16, 2004 12:23 PM

Different Categories of Collection

where:
zString

Any null-terminated string

aCharArray

Object reference

aLiteral

Any COBOL literal, or data item


containing one.

aLength PIC X(4) COMP-5.

Length in characters of aLiteral.

Querying a CharacterArray Object


There are many ways to get data from a CharacterArray object. Three
are given below:

To get the length of the string held:


invoke aCharArray "size"
returning aLength

To get the value of the string held:


invoke aCharArray "getValue"
returning aValue

To get the value of the string held, as a null-terminated string


invoke aCharArray "asParameter"
returning aValue

where:
aCharArray

Object reference; contains the handle to


the CharacterArray object

aLength PIC X(4) COMP-5.

Length in characters of the


CharacterArray object

aValue PIC X(n)

Value of the CharacterArray object. It is


your responsibility to see that aValue is
long enough to hold the result.
The "asParameter" method returns a
string one byte longer than the result
from the "getValue" method, to allow for
the null at the end.

Object-oriented Programming with COBOL

157

oppubb.book Page 158 Tuesday, March 16, 2004 12:23 PM

158

Chapter 15 Collection Frameworks

Comparison Between Elements


Collections carry out two types of comparison on elements:

Equality

One element greater than another

Equality
A collection compares two elements by sending the "equal" message to
one element, giving it the other element as a parameter. The default
"equal" method in Base simply compares the object references of the
two objects (that is, they are equal only if they are the same object).
For many applications you will want to compare part or all of the
elements instance data to determine equality. Implement the interface
to "equal" as follows:
method-id. "equal".
linkage section.
01 lnkElement
object reference.
01 lnkEqualityResult
pic x comp-5.
88 isEqual
value 1.
88 isNotEqual
value 0.
procedure division using lnkElement
returning lnkEqualityResult.
* Code to compare lnkElement to self and return
* lnkEqualityResult.
exit method.
end method "equal".

Relative Value of Objects


The default sort method of a SortedCollection instance sends the
"lessThanOrEqual" message (if it is a collection "ofReferences") or the
"lessThanOrEqualByLengthValue" message (if it is a collection
"ofValues") to all the elements in the collection. There is no default
method for this in Base, although it is implemented by the Intrinsic
classes and by CharacterArray.

Object-oriented Programming with COBOL

oppubb.book Page 159 Tuesday, March 16, 2004 12:23 PM

Hashing Elements

You may need to implement this method so that two objects can
compare themselves using part of their instance data. Use the following
interface to implement the "lessThanOrEqual" method:
method-id. "lessThanOrEqual".
...
linkage section.
01 lnkString
object reference.
01 lnkResult
pic x comp-5.
88 isEqual
value 1.
88 isNotEqual
value 0.
procedure division using lnkString returning lnkResult.
* Code to compare lnkElement to self and return a result
exit method.
end method "lessThanOrEqual".

Use the following interface to implement the


"lessThanOrEqualbyLengthValue" method:
method-id. "lessThanOrEqualbyLengthValue".
linkage section.
01 lnkElement
object reference.
01 lnkSize
pic x(4) comp-5.
01 lnkResult
pic x comp-5.
88 isLessThanOrEqual
value 1.
88 isNotLessThanorEqual
value 0.
procedure division using lnkElement lnkSize
returning lnkResult.
* Code to compare lsElement to self and return
* isNotLessThanOrEqual if lsElement is greater than
* self. The lsSize parameter is the value returned
* by element in response to the "size" message.
exit method.
end method "lessThanOrEqualbyLengthValue".

Hashing Elements
The dictionary and set classes use hash values to store and retrieve
elements. The default "hash" mechanism in Base returns the object
reference to the object.

Object-oriented Programming with COBOL

159

oppubb.book Page 160 Tuesday, March 16, 2004 12:23 PM

160

Chapter 15 Collection Frameworks

You will often need to override the default with a hash mechanism
which creates a hash value using the objects instance data. There are
two reasons for this:

Dictionaries and sets will otherwise allow you to add elements or


keys with duplicate instance data, because the hash values returned
from the default method are different.

Retrieval of data is more efficient. With the default method, the


hash value returned to search for an element or key will not relate
to the data of the element or key, and the set or dictionary will have
to search until it finds the correct object.

Implement the interface to "hash" as follows:


method-id. "hash".
linkage section.
01 lnkHashValue
pic s9(9) comp-5.
procedure division returning lnkHashValue.
* Code to return a hashvalue based on objects attributes.
exit method.
end method "hash".

Separate objects that have the same value must always return identical
results from "hash". Hash values do not have to be unique for each
element, but the more duplicate hash values a dictionary contains, the
less efficient its storage and retrieval of elements. Hash values should
always be positive numbers.

Display Mechanisms
There are two mechanisms you can use to display the contents of a
collection. You can send the message "display" to the collection or you
can display the collection on a Listbox.

Using the display Message


If you send the "display" message to a collection, it displays on the
console all the elements of the collection between parentheses "()". To
do this, it sends the message "display" to every element in the

Object-oriented Programming with COBOL

oppubb.book Page 161 Tuesday, March 16, 2004 12:23 PM

Collection Sort Methods

collection. The default "display" method in Base displays a description


of the object. For example, if you had a CheckAccount object, the
default "display" method would show:
an instance of the class checkaccount

CharacterArray and the COBOL intrinsic classes implement their own


"display" methods that display their contents. You can implement
"display" in your own objects using the following interface:
method-id. "display".
...
procedure division.
* Code to display self on the console.
exit method.
end method "display".

Display on a Listbox
You can display a collection of CharacterArrays or intrinsic data by
passing it to a Listbox with the "setContents" message. The Listbox
displays each element of the collection as a string on a separate line.

Collection Sort Methods


Instances of SortedCollection sort elements into order as they are
added. The default sorting mechanism provided sends the
"lessThanOrEqual" message (if a collection "ofReferences") or the
"lessThanOrEqualbyLengthValue" message (if a collection "ofValues")
to elements to compare their relative values (see the section Relative
Value of Objects).
You can set your own sort method for an instance of SortedCollection.
The method you provide must compare two elements and return a
value indicating which element should appear before the other.
To override the default sort method you must create a Callback for your
method and pass the Callback to the SortedCollection.

Object-oriented Programming with COBOL

161

oppubb.book Page 162 Tuesday, March 16, 2004 12:23 PM

162

Chapter 15 Collection Frameworks

Implement the interface to your sort method as follows:


method-id. "sortMethod".
linkage section.
01 lnkElement1
object reference.
01 lnkElement2
object reference.
01 lnkResult
pic x comp-5.
88 element1first
value 1.
88 element2first
value 0.
procedure division using lsElement1 lsElement2
returning lnkResult.
* Code to compare lsElement1 to lsElement2 and set
* lnkResult to determine which element should precede
* the other.
exit method.
end method "sortMethod".

Iterator Methods
The collection classes implement four iterator methods which enable
you to access all the elements of your collection by sending a single
message to the collection. To use any of the iterator methods you need
to provide a Callback object. The Callback is passed each element of the
collection as a parameter in turn.
This section shows you the interface the method in the Callback must
have to work with the iterator methods. The iterator methods provided
are:
"do"

Passes every element in the collection to a callback.

"select"

Passes every element in the collection to a callback. Any


elements for which the callback returns "true" (by
setting a PIC X COMP-5 to value 1) are stored in a new
subcollection.

"reject"

Passes every element in the collection to a callback. Any


elements for which the callback returns "false" (by
setting a PIC X COMP-5 to value 0) are stored in a new
subcollection.

Object-oriented Programming with COBOL

oppubb.book Page 163 Tuesday, March 16, 2004 12:23 PM

Iterator Methods

"collect"

Passes every element in the collection to a callback. The


Callback returns an object (which can be the same or
different to the original element). All the objects
returned are collected into a new collection of the same
type as the original collection.

Implement the interface for a callback method for "do" as follows:


method-id. "doMethod".
linkage section.
01 lnkElement
object reference.
procedure division using lnkElement.
* Any code to process the element.
exit program.
end method "doMethod".

Implement the interface for a callback method for "select" as follows:


method-id. "selectMethod".
linkage section.
01 lnkElement
object reference.
01 lnkselectResult
pic x comp-5.
88 selectThisElement
value 1.
88 dontSelectElement
value 0.
procedure division using lnkElement
returning lnkSelectResult.
* Code to determine whether lnkElement should be included in
* the new subcollection.
exit method.
end method "selectMethod".

Implement the interface for a callback method for "reject" as follows:


method-id. "rejectMethod".
linkage section.
01 lnkElement
object reference.
01 lnkRejectResult
pic x comp-5.
88 rejectThisElement
value 1.
88 dontRejectElement
value 0.
procedure division using lnkElement
returning lnkRejectResult.
* Code to determine whether lnkElement should be included in
* the new subcollection.
exit method.
end method "rejectMethod".

Object-oriented Programming with COBOL

163

oppubb.book Page 164 Tuesday, March 16, 2004 12:23 PM

164

Chapter 15 Collection Frameworks

Implement the interface for a callback method for "collect" as follows:


method-id. "collectMethod".
linkage section.
01 lnkElement
object reference.
01 lnkReturnElement
object reference.
procedure division using lnkElement
returning lnkReturnElement.
* Code to return an element for the new collection.
exit method.
end method "collectMethod".

Object-oriented Programming with COBOL

oppubb.book Page 165 Tuesday, March 16, 2004 12:23 PM

165

16 Intrinsic Data
This chapter explains how you can send messages to the types of
intrinsic data supported by the Base Class Library, and how you can
write classes to support other types.
All the code shown in this chapter uses the Micro Focus alternatives to
the ISO 2002 syntax.

Overview
The Base Class Library includes a set of classes corresponding to some of
COBOLs intrinsic data types. Objects from these classes correspond to
COBOL data items. This enables you to store and manipulate intrinsic
data in object-oriented ways.
The intrinsic data mechanism is used by the collection classes to store
intrinsic data without creating objects for every item of intrinsic data in
the collection. You can think of intrinsic data as being static objects
whose data is allocated by the Compiler at compile time; all other
objects in Micro Focus OO COBOL are dynamic and their data is
allocated at run time.
The three COBOL data types supported by the Class Library are:

PIC X(n)

PIC X(n) COMP-X

PIC X(n) COMP-5

Object-oriented Programming with COBOL

oppubb.book Page 166 Tuesday, March 16, 2004 12:23 PM

166

Chapter 16 Intrinsic Data

Using Intrinsic Data


You can use the intrinsic data classes in several different ways:

To store intrinsic data in a collection

To send messages directly to intrinsic data, without creating an


instance at run time

To create dynamic instances containing intrinsic data

The supplied intrinsic classes can only store data of a preset length. If
you want to use them for intrinsic data of any other length, you must
first clone the class, creating a new class for the length of data you
require.

Cloning an Intrinsic Data Class


There are three classes for representing intrinsic data:
Class

Data Length

COBOLPICX

1 byte

COBOLCOMP5

4 bytes

COBOLCOMPX

4 bytes

To store different length data you need to clone the class for a different
length. To do this, send the message "newClass" to one of the intrinsic
data classes, supplying the length as a parameter. It returns a class
capable of storing data of the length given with the "newClass"
method.
For example:
move 6 to aLength
invoke cobolPICX "newClass"
using aLength
returning aNewPicXClass

where:
aLength

is declared as a PIC X(4) COMP-5.

aNewPicXClass

is declared as an OBJECT REFERENCE.

Object-oriented Programming with COBOL

oppubb.book Page 167 Tuesday, March 16, 2004 12:23 PM

Using Intrinsic Data

You can use cloned classes as templates for INVOKE...AS, and for
creating collections of intrinsic values. You can also create instances of
intrinsic classes using the "new" method.

Sending a Message to an Intrinsic Data


Type
You can send a message to COBOL intrinsic data by using INVOKE...AS.
The example below sends the "hash" message to a numeric data item:
00001
00002
00003
00004
00010
00016
00017
00018
00019
00020

working-storage section.
01 aValue
pic x(2) comp-5.
01 cloneX2Class
object reference.
01 aLength
pic x(4) comp-5.
...
procedure division.
...
move 2 to aLength
invoke COBOLCOMP5 "newClass" using aLength
returning cloneX2Class
...
invoke aValue as cloneX2Class "hash"
returning aHashValue
...

This is what the code above is doing:


Lines 1-4

Declaring data.

Lines 16-18

Cloning the COBOLCOMP5 to create a new class for


comp-5 data items two bytes long.

Line 19

Sending a message to the data in data item aValue.

The invoke...as statement uses the data item as an instance of the


cloned class. You can think of an intrinsic object as a static object that
has memory allocated to it at compile time. Static objects do not have
object handles, unlike the dynamic objects created by the OO run-time
system. Intrinsic data objects are the only examples of static objects in
OO COBOL.

Object-oriented Programming with COBOL

167

oppubb.book Page 168 Tuesday, March 16, 2004 12:23 PM

168

Chapter 16 Intrinsic Data

Writing New Intrinsic Classes


If you want to use a type of intrinsic data not supported by any of the
classes in the Base Class Library, you can create your own new intrinsic
class. You do this by writing a class that inherits from Intrinsic, with
data.
The next two sections deal with the code you need to write for the:

Class object code

Instance object code

Code for an Intrinsic Class Object


The class initialization code for your intrinsic class must set a default size
in bytes for the data to be represented by instances, and put it in data
item STORAGEREQUIREMENTS. This is declared in Intrinsic as follows:
01

storageRequirements

pic x(4) comp-5.

The class cloning mechanism enables users of your intrinsic class to


handle data of different lengths.
You must also code the following class methods:

"baseClass"
Returns the object handle to this class object.

"maximumSize"
Returns the maximum number of bytes allowable for this type of
intrinsic data. For example, a COMP-X data item cant be more than
eight bytes long, so the "maximumSize" method in the
COBOLCOMPX class returns eight.

Code the method interface for "baseClass" like this:


method-id. "baseClass"
linkage-section.
01
lnkHandle

Object-oriented Programming with COBOL

object reference.

oppubb.book Page 169 Tuesday, March 16, 2004 12:23 PM

Writing New Intrinsic Classes

procedure division returning lnkHandle.


* Substitute the class-id of your class for
* nameOfThisClass in the following statement.
set lnkHandle to nameOfThisClass
exit method.
end method "baseClass"

The "baseClass" method returns the object handle of the named class,
rather than SELF, so that the correct handle is returned for the baseClass
even when the message is sent to a clone of your intrinsic class.
Code the method interface for "maximumSize" like this:
method-id. "maximumSize".
linkage-section.
01
lnkSize
pic x(4) comp-x.
procedure division returning lnkSize.
* Code to return the maximum allowable size.
exit method.
end method "maximumSize".

Code for an Intrinsic Instance Object


You must code comparison methods for instances of an intrinsic class,
for use by the Collection class. There are two separate methods for each
type of comparison; one compares this intrinsic object to another
object, the other compares it to a value.
You need to provide the following methods for comparing intrinsic
objects:

"equal"

"lessThan"

"greaterThan"

These are the methods for comparing objects with intrinsic data items:

"equalByLengthValue"

"lessThanByLengthValue"

"greaterThanByLengthValue"

Object-oriented Programming with COBOL

169

oppubb.book Page 170 Tuesday, March 16, 2004 12:23 PM

170

Chapter 16 Intrinsic Data

The value of an intrinsic instance is held in an inherited instance data


item, INSTANCEDATA. This is declared as:
01

instanceData

pic x.

Although it is only declared as a single byte in length, it always


references a memory area of the correct length for your intrinsic data.
To get at the data in it, use reference modification. For instance, to see
the first four bytes of instance data, you can refer to:
instanceData(1:4)

Code the method interface to any of the object comparison methods as


follows:
method-id. "equal".
linkage section.
01 lnkBoolean
03 isTrue
03 isFalse
01 lnkIntrinsic

pic x comp-x.
value 1.
value 0.
object reference.

procedure division using lnkIntrinsic


returning lnkBoolean.
* Code to compare the value in lnkIntrinsic to
* the value in this instance. Set isTrue if
* the result of the comparison is true, otherwise
* set isFalse.
exit method.
end method "equal".

Code the interface to any of the intrinsic data comparison methods as


follows:
method-id. "equalByLengthValue".
linkage section.
01 lnkBoolean
03 isTrue
03 isFalse
01 lnkLength
01 lnkValue

pic x comp-x.
value 1.
value 0.
pic x(4) comp-x.
pic x occurs 1 to maxSize

procedure division using lnkLength lnkValue


returning lnkBoolean.
* Code to compare the value in lnkValue to
* the value in this instance. Set isTrue if
* the result of the comparison is true, otherwise

Object-oriented Programming with COBOL

oppubb.book Page 171 Tuesday, March 16, 2004 12:23 PM

Writing New Intrinsic Classes

* set isFalse.
exit method.
end method "equalByLengthValue".

Object-oriented Programming with COBOL

171

oppubb.book Page 172 Tuesday, March 16, 2004 12:23 PM

172

Chapter 16 Intrinsic Data

Object-oriented Programming with COBOL

oppubb.book Page 173 Tuesday, March 16, 2004 12:23 PM

173

17 Callback Frameworks
This chapter shows you how to create Callback instances, and how you
can use them in your own applications.
All the code shown in this chapter uses the Micro Focus alternatives to
the ISO 2002 syntax.

Overview
An instance of the Callback class contains an object and the name of a
method. When you send the message "invoke" to the Callback, it sends
a message to the object it contains, invoking the named method.
A Callback instance is like a pointer to a block of code. It enables you to
pass a block of code to a class or object method for later execution. For
example, to implement an exception handling method, you create a
Callback containing the method and pass the Callback to the
ExceptionHandler.
The Base Class Library also contains a class called EntryCallback which
enables you to create a Callback to any COBOL entry point. You can use
an EntryCallback with Class Library objects anywhere you can use a
Callback, enabling you to use Class Library functionality like collection
iterators with procedural COBOL code. All the rules for using Callbacks
apply equally to EntryCallbacks.

Using Callbacks
There are two stages to using Callbacks:

Creating a Callback instance

Invoking a Callback instance


Object-oriented Programming with COBOL

oppubb.book Page 174 Tuesday, March 16, 2004 12:23 PM

174

Chapter 17 Callback Frameworks

When you are using Callbacks with Class Library objects, you only need
to know how to create the Callback instance. The instance is then
passed to the Class Library object, which invokes it when needed.
However, you might want to use Callbacks in the classes you write, so
this chapter also shows you how can invoke a Callback.

Creating a Callback
To create a Callback object, send the "new" message to the Callback
class. You must supply the object that implements the method you want
written into the Callback, and the message name to invoke the method.
Terminate the message name with a null byte (x"00). The Callback
"new" method looks for a null to find the end of the message name.
You can add a null byte to a literal very easily with the syntax shown
below:
01 wsLiteral
*> equivalent to

pic x(16) z"null-terminated".


pic x(16) "null-terminated" & X"00".

You can create a Callback as shown below:


invoke Callback "new" using anObject z"aMethod"
[p1] [p2] [p3] [p4] [p5] [p6]
returning aCallback

where the parameters are:


anObject

contains the object handle to the class or instance


object containing the method you want in the Callback.

aCallback

an object reference to the Callback created.

[p1]...[p6]

are up to six optional parameters for the method.


These are passed to the method every time it is
invoked. All parameters must be declared as USAGE
OBJECT REFERENCE.

Invoking a Callback
You do not need to know how to invoke Callbacks in order to use them
with the objects in the supplied Class Library, but you may want to use

Object-oriented Programming with COBOL

oppubb.book Page 175 Tuesday, March 16, 2004 12:23 PM

Using Callbacks

them in classes of your own. To execute the method stored in a


Callback, send the message "invoke" to the Callback instance. You can
also pass up to three parameters along with the "invoke" message.
These will be passed to your Callback method following any parameters
specified when the Callback was created (see the section Creating a
Callback).
invoke aCallback "invoke" [using p1 [p2] [p3] ]
[returning result]

If the method in a Callback returns a parameter, you must include a


returning clause on the invoke to the Callback, with a parameter of
matching size.

Object-oriented Programming with COBOL

175

oppubb.book Page 176 Tuesday, March 16, 2004 12:23 PM

176

Chapter 17 Callback Frameworks

Object-oriented Programming with COBOL

oppubb.book Page 177 Tuesday, March 16, 2004 12:23 PM

177

18 Exception Handling
Frameworks
Exception handling is the mechanism by which objects raise and trap
errors. This chapter shows you how you can use this mechanism in the
objects you write.
All the code shown in this chapter uses the Micro Focus alternatives to
the ISO 2002 syntax.

Overview
Exception handling gives you a flexible mechanism for handling errors
in OO COBOL programs. When an object traps an error, it raises an
exception. Each different kind of error is represented by a different
exception number.
Objects in the supplied class libraries react to error conditions by raising
exceptions. The Class Library has a set of exception numbers, and a file
of error messages. You can define your own exception conditions for
objects you create, associating each set of exception conditions with its
own error messages file.
An object raises an exception by sending itself the "raiseException"
message, passing an exception number as a parameter. The Base class
implements the "raiseException" method, so it is inherited by all
objects. Exception handlers trap errors raised by objects through the
"raiseException" mechanism; they do not trap run-time system errors.
The ExceptionManager class in the Base Class Library provides most of
the logic for actually handling exceptions, including a system exception
handler. The system exception handler displays an error message and
shuts down the application when an object raises an exception, but an
application can define its own exception handlers and attach them to
individual classes or objects to redefine their behavior.

Object-oriented Programming with COBOL

oppubb.book Page 178 Tuesday, March 16, 2004 12:23 PM

178

Chapter 18 Exception Handling Frameworks

You can replace the system exception handler with a system exception
handler of your own.

Creating an Error Message File


Create a file with the extension .err, using the Editor. It should start
with the statements:
$quote x
$set 1

where x is the character you wish to use as a quote character. Then,


write each error message in the format:
nnnnn

"error-message-text"

where:
nnnnn is the exception number
"error-message-text" is the text of the error message you wish to
output for this exception number.
The double-quote character (") is assumed to be the quote character set
in the $quote statement above. You can change quote statements at
any point during the .err file; each change applies to all the messages
which follow it up until the next $quote statement. You can also enter
comments, by starting a line with a $ followed by a space. Here is an
example:
$quote "
$
$set 1
1 "Invalid key type"
2 "Failed to open file for dictionary"
3 "Using a key of different size"
4 "Record exceeds maximum allowed length"
5 "Error reading control record"
6 "Indexed file has wrong key structure"
7 "Key not found in file"
8 "Attempt to write a record which has been deleted"

Object-oriented Programming with COBOL

oppubb.book Page 179 Tuesday, March 16, 2004 12:23 PM

Registering an Exception Message File

...
$ ************************************************************
$ Last modified on 95/08/01
$ ************************************************************

Net Express :

Next, add the .err file to the project for your application. The IDE
compiles this to a .lng file.
Right-click on the .lng file, and package it as a Micro Focus library (.lbr)
file. Name the library file filenamedf.lbr. For example, an error message
file you refer to in your source code as myerrors has the filename
myerrorsdf.lbr.

Server Express:

Run the shell script, mfmsg to create a .lng file and copy it into the
message directory structure under $COBDIR/lang/. You need to be
logged in as the superuser to run this script successfully. To run the shell
script:
mfmsg output.lng input.err

Note: Earlier versions of OO COBOL only supported a single user error


file, user.err, with exception numbers starting at 10,000. The
ExceptionManager did not require you to register this file. This
mechanism still works for backwards compatibility; any exception
numbers in the range 10,000 to 65535 are assumed to refer to messages
in user.err. All new error message files should use exception numbers
starting from 1, and should be registered explicitly with the
ExceptionManager as described in this chapter.

Registering an Exception Message File


Before an object can raise any exceptions, an error message file must
have been registered with the ExceptionManager. When you register a
message file with the ExceptionManager, it returns an error file offset.
This is an integer number which uniquely identifies the file.
Any number of classes or objects can share the same error message file,
and it doesnt matter if the file is registered more than once; the
ExceptionManager will always return the same offset value during a
particular run of an application.

Object-oriented Programming with COBOL

179

oppubb.book Page 180 Tuesday, March 16, 2004 12:23 PM

180

Chapter 18 Exception Handling Frameworks

The offset value returned depends on how many other message files
have been previously registered during the application run. Never hardcode an error file offset value into your classes; always query the
ExceptionManager for the value.
To register an error file:
invoke ExceptionManager "registerMessageFile"
using library errfile
returning anOffset

where:

library

Name of the library containing the error file

errfile

The name of the file containing your error messges.

anOffset

PIC X(4) COMP-5.


The error file offset value.

Server Express:

The library name is ignored by the mechanisms which find the message
file. It is still used by the ExceptionManager as part of the registration of
the message file. You must use the same value for both parameters
when you send a "queryMessageFile" message to the
ExceptionManager referring to the same file. Although the first
parameter is not strictly needed on Server Express, including it as part of
the method interface keeps source code compatibility between Server
Express and Net Express.
The example below is a method that registers an error message file with
the ExceptionManager.
method-id. "registerFile".
local-storage section.
01 errorFile
01 libraryFile
01 anOffset

pic x(8)
pic x(6)
pic x(4) comp-5.

procedure division.
move spaces to libraryFile, errorFile
move "mylibf" to libraryFile
move "err-file" to errorFile
invoke ExceptionManager "registerMessageFile"
using libraryFile errorFile
returning anOffset
exit method.
end method "registerFile".

Object-oriented Programming with COBOL

oppubb.book Page 181 Tuesday, March 16, 2004 12:23 PM

Raising an Exception

Raising an Exception
Whenever a method detects an error (for example, a value out of
range) it should raise an exception. Each different exception has an
exception number relating it to a message in an error message file.
Before raising the exception, you add the error file offset to the
exception number to get a unique exception ID. The object raising the
exception may not be the object which registered the error message
file, so it can query the ExceptionManager to get the offset for its
associated error file. It then raises the exception by sending itself the
"raiseException" message.
The "raiseException" method is implemented in the Base class and is
inherited by all subclasses. If no exception handler is registered for the
object, the system exception handler displays the exception number and
error message, then terminates the application.
If you have registered an exception handler for the object, execution
returns to the statement following the "raiseException" after your
exception handler has been invoked.
In order of descending priority, the ExceptionHandler will try to call
exception handlers registered with:
1

The object instance.

The class of the object.

The system exception handler.

To raise an exception:
1

Get the error message file offset for this type of object, by sending
the "queryMessageFile" to the ExceptionManager

Calculate the exception ID by adding the exception offset to the


exception number.

Send the "raiseException" message to self using the exception ID as


a parameter.

The basic "raiseException" message doesnt allow you to supply any


information about an error apart from the exception number. The

Object-oriented Programming with COBOL

181

oppubb.book Page 182 Tuesday, March 16, 2004 12:23 PM

182

Chapter 18 Exception Handling Frameworks

following variations on "raiseException" enable you to send text with


the exception number to provide extra information:
"raiseExceptionWithText"

Enables you to pass up to six


CharacterArrays as parameters
with the exception number.

"raiseExceptionWithTextZ"

Enables you to pass up to six


null-terminated strings as
parameters with the exception
number.

"raiseExceptionWithTextCollection"

Enables you to pass an


OrderedCollection of
CharacterArrays with the
exception number.

The code fragment below is an example of how to raise an exception:


*

Get the error offset.

invoke ExceptionManager "queryMessageFile"


using "mylibf"
"err-file"
returning errorOffset
Calculate the exception ID
add errorOffset to errorNumber giving exceptionId
Raise the exception
invoke self "raiseException" using exceptionId
returning anObject

ErrorOffset, ErrorNumber and ExceptionId are all declared as PIC X(4)


COMP-5.

Providing Your Own Exception Handlers


An exception handler is a CallBack to a method which knows how to
deal with the exception. When the object raises an exception your
exception handling method is invoked. To create an exception handler,
you need to:

Write an exception handler method.

Object-oriented Programming with COBOL

oppubb.book Page 183 Tuesday, March 16, 2004 12:23 PM

Providing Your Own Exception Handlers

Register the method against a class or instance object with the


ExceptionManager.
If you register an exception handler against a class object, then all
instances of the class are also automatically registered against the
same exception handler. You can override the registration by
registering a differnt exception handler agianst a particular
instance.
You can cancel an exception handler that has been registered
against an object at any time. Once you do this, any exceptions
raised by the object will be dealt with by the system exception
handler

Writing Exception Handler Methods


An exception method enables you to handle an error raised by a COBOL
object in the way that best suits the application. By registering your
exception method against a class or instance object, you ensure that it
gets invoked whenever those objects raise exceptions.
An exception method is passed the handle to the object that raised the
exception, and the exception ID. The exception method needs to
calculate the exception number from the exception ID. To do this, the
exception method does the following:
1

Queries the ExceptionManager for the exception offset for the error
message file. The exception method either needs to know the name
of the error message file, or the object raising the exception must
implement a method to return it.

Subtracts the error file offset from the exception ID to get the
exception number.

Once the exception method has the exception number, it should test it
to see if it has a value it expects. If it doesnt recognize the error, it
should reraise the exception. The exception can then be trapped either
by an exception handler that knows what to do with it, or by the system
exception handler, which terminates your application.

Object-oriented Programming with COBOL

183

oppubb.book Page 184 Tuesday, March 16, 2004 12:23 PM

184

Chapter 18 Exception Handling Frameworks

The code below is an example of an exception handling method:


method-id. "exceptionMethod".
local-storage section.
01
01

errorNumber
lsOffset

pic x(4) comp-5.


pic x(4) comp-5.

linkage section
01 anObject
01 anExceptionId
01 aDataItem
01 aTextCollection

object reference.
pic x(4) comp-5.
object reference.
object reference.

procedure division using anObject


anExceptionId
aTextCollection
returning aDataItem.
*
Calculate the exception number
invoke ExceptionManager "queryMessageFile"
using "err-lib"
"err-file"
returning lsOffset
subtract lsOffset from exceptionId giving errorNumber
*
process the error
evaluate errorNumber
when knownError1
*
Handle the error
when knownError2
*
Handle the error
when other
*
Unknown error, so reraise the exception.
invoke self "raiseExceptionWithTextCollection"
using anExceptionId
aTextCollection
returning aDataItem
end-evaluate
exit method.
end method "exceptionMethod".

where:
anObject

is the object which originally raised the error.

anExceptionId

is the number representing the error raised.

Object-oriented Programming with COBOL

oppubb.book Page 185 Tuesday, March 16, 2004 12:23 PM

Replacing the System Exception Method

aDataItem

is an object returned by your exception method. This


enables you to return a default parameter from a
method which has raised an exception, provided the
method is coded to pass back the parameter it
receives from the "raiseException" method.

Registering an Object with the


Exception Handler
To register an exception handler against an object:, you invoke the
"register"method of the ExceptionManager class:
invoke ExceptionHandler "register" using anObject
anExceptionMethod

where anObject is the object reference to the object you want to


register, and anExceptionMethod is a Callback to your exception
method. For more information about Callbacks see the chapter Callback
Frameworks.

Canceling an Exception Registration


To cancel the registration of an object with the ExceptionHandler, send
it the "cancel" message:
invoke ExceptionHandler "cancel" using anObject
returning aBool

where anObject is the object to deregister, and aBool is a PIC X COMP-5.


It contains the value 1 if the deregistration is successful.

Replacing the System Exception Method


The system exception method is an exception method registered for the
whole system. It is invoked whenever an object not explicitly registered
with the exception handler raises an exception. The default behaviour is

Object-oriented Programming with COBOL

185

oppubb.book Page 186 Tuesday, March 16, 2004 12:23 PM

186

Chapter 18 Exception Handling Frameworks

to display the exception number with an error message, then end the
program.
You can replace the system exception method with your own. Create a
Callback for an exception method. Then send the "setSystemHandler"
message to the ExceptionManager.
The "setSystemHandler" method returns you a handle to a CallBack for
the existing system exception handler. If your replacement system
exception method gets an exception it does not know how to handle,
reraise the exception, and the default SystemHandler will actually still
get invoked.
The example below shows you how to replace the system exception
method:
invoke ExceptionManager "setSystemHandler" using newHandler
returning oldHandler

where:
newHandler

is the object handle to the Callback for your exception


method.

oldHandler

is the object handle to the Callback for the system


exception method you have replaced.

Object-oriented Programming with COBOL

oppubb.book Page 187 Tuesday, March 16, 2004 12:23 PM

187

19 Component Frameworks
This chapter describes the component framework. This provides a
mechanism for communication between objects that is an alternative
to the sending of messages.
All the code shown in this chapter uses the Micro Focus alternatives to
the ISO 2002 syntax.

Overview
The component framework provides a mechanism which enables you
to treat objects like pluggable components. Once you have defined an
object as a component, you can:

Define output signals that the component can send

Define input sockets, which can receive signals from other


components. You can define more than one input socket for any
component.

Connect the output of a component to the input socket of another


component. You can connect a component to any number of input
sockets.

The input socket of a component does not have to define behavior for
every signal it might receive when connected to the output of another
component.
When a component sends a signal, it doesnt send it to a particular
object. It sends it to all the components that are connected to it. Each
component that receives a signal can either ignore it or respond to it.
Figure 19-1 shows an interface component using signals to
communicate with database and application components.

Object-oriented Programming with COBOL

oppubb.book Page 188 Tuesday, March 16, 2004 12:23 PM

188

Chapter 19 Component Frameworks

Figure 19-1. A Component

This is different to the situation with a message, where you must specify
a single destination object when you send a message. If you dont
specify a valid object, or specify one that doesnt understand the
message, the application breaks. With the component mechanism, you
can define objects (or groups of cooperating objects) which act as
common building blocks. You then build your application by plugging
together groups of components.
At every stage of creating and connecting components, you can use
requirements-based vocabulary that we supply. For more information
about using vocabularies see the chapter Requirements-based
Vocabulary.

Defining Output Signals


A component must define a name for all the signals it will generate. A
signal can be any null-terminated string (a literal ending with x"00"), up
to 32 characters long. Each output signal defined for a particular

Object-oriented Programming with COBOL

oppubb.book Page 189 Tuesday, March 16, 2004 12:23 PM

Defining Output Signals

component must have a unique name. Before you can define output
signals for an object, you must make it into a component.
To make an object into a component, send it the "makeComponent"
message. Include the following statement somewhere in the objects
initialization code.
make component

MAKE COMPONENT is vocabulary defined in base.if. You must put this


as a copyfile at the beginning of your program to use the MAKE
COMPONENT verb. Using MAKE COMPONENT is an alternative syntax
to:
invoke self "makeComponent"

Names do not have to be unique throughout an application. You can


have many different components that define signals with the same
names. Each component that wants to receive signals defines a
different input socket for each different type of component to which it
wants to connect. So even if different types of components define
signals with the same names, there are no name clashes.
We recommend that you define all the literals for your signal names as
level 78 data items in a copyfile, and always refer to the signals by the
names in the copyfile. When you compile a program, you will get a
compile-time error if you have mistyped the dataname for the signal. If
you use literals directly in your code, mistyping a signal name will not
raise an error until run time.
The statement to define a signal is:
define signal signalId

where:
signalId

is a null-terminated (ends in x"00") string

DEFINE SIGNAL is vocabulary defined in base.if. You must put this as a


copyfile at the beginning of your program to use the DEFINE SIGNAL
verb. DEFINE SIGNAL is alternative syntax to:
invoke self "defineOutSignal" using SignalId

Object-oriented Programming with COBOL

189

oppubb.book Page 190 Tuesday, March 16, 2004 12:23 PM

190

Chapter 19 Component Frameworks

This is an example piece of code defining a set of signals:


*Define
define
define
define
define

signals
signal new-signal
signal open-signal
signal save-signal
signal exit-signal

The signals in this example are defined as level-78s in a copyfile:


78
78
78
78

exit-signal
new-signal
open-signal
save-signal

value
value
value
value

z"001".
z"002".
z"003".
z"004".

Defining Input Sockets


To receive signals from another component, you must define an input
socket for the component. Identify each input socket with a unique
name. You can define as many input sockets for a component as you
want, as long as each one has a different name. Different components
can have the same input socket name.
The statement to declare an input socket is:
declare socket socketName

where:
socketName

is a null-terminated string (a literal ending with


x"00"), up to 32 characters long, naming the socket.

DECLARE SOCKET is vocabulary defined in base.if. You must put this as


a copyfile at the beginning of your program to use the DECLARE
SOCKET verb. Using DECLARE SOCKET is alternative syntax to:
invoke self "declareSocket" using socketName

Having defined an input socket, you need to map all the signals you
expect to receive on that input socket to methods in the component.
The socket name and signal names are all declared as level-78 data
items in a copyfile (see the previous section).

Object-oriented Programming with COBOL

oppubb.book Page 191 Tuesday, March 16, 2004 12:23 PM

Connecting Components

The statement to map a signal to a method is:


map signal signalId from socketName
to methodName

where:
signalId

Null-terminated string (a literal ending with x"00")


naming the signal.

socketName

Null-terminated string (a literal ending with x"00")


naming the socket.

methodName

Null-terminated string (a literal ending with x"00")


naming the method.

MAP SIGNAL is vocabulary defined in base.if. You must put this as a


copyfile at the beginning of your program to use the MAP SIGNAL verb.
MAP SIGNAL is alternative syntax to:
invoke self "defineInSignal" using signalId
socketId methodName

The following example shows an object making itself into a component,


declaring a socket, and setting up mapping for a set of signals.
make component
declare socket mainApplicationSocket *> declare a socket
map signal fileOpen-signal from mainApplicationSocket
to method z"onSignalFileOpen"
map signal fileOpenfailed-signal from mainApplicationSocket
to method z"onSignalOpenFailed"

Connecting Components
Output signals and input sockets only do anything when they are
connected together. You can connect an output component to any
number of input sockets, and any input socket can be connected to the
outputs of more than one component.

Object-oriented Programming with COBOL

191

oppubb.book Page 192 Tuesday, March 16, 2004 12:23 PM

192

Chapter 19 Component Frameworks

In this example, two components are connected together, through a


socket defined on the input component. The socket is named by a level
78 data item in a copyfile.
connect output to input at socketId

where:
output

is an OBJECT REFERENCE containing a handle to the


output component

input

is an OBJECT REFERENCE containing a handle to the input


component

socketId

is a null-terminated string (a literal ending with x"00")


naming the socket on the input component.

CONNECT is vocabulary defined in base.if. You must put this as a


copyfile at the beginning of your program to use the CONNECT verb.
CONNECT is alternative syntax to:
invoke outputcomponent "connect" using inputComponent socketId

Sending Signals
When a component sends a signal, if it is connected to an input socket
which recognizes that signal, it invokes the method defined by the
input socket. You might have the component connected to separate
input sockets on different components, in which case all input sockets
which recognize that signal invoke methods. Methods are invoked in
the order that the components were connected together.
You can optionally send one object handle as a parameter with a signal.
This enables you to send some data with the signal. Sometimes you
want to send a signal which is a request for data; in this case, the
receiving component should define a signal for sending the data back.
For example, an interface component might request a list of customer
accounts for display, by sending a "retrieve-accounts" signal. The
retrieval component receives this signal, and if it finds the data, sends a
"display-accounts" signal, with the account information as data. The
SymbolTable class in the Base Class Library enables you to package up

Object-oriented Programming with COBOL

oppubb.book Page 193 Tuesday, March 16, 2004 12:23 PM

Sending Signals

several pieces of information into a single object, each of which is


identified by a separate key.
In this example, a component sends a signal. The signal name is defined
as a level 78 in a copyfile. The parameter, dataBlock, contains an object
handle which is sent as data with the signal.
signal signalId dataBlock

where:
signalId

is a null-terminated string (a literal ending with x"00")


naming the signal

dataBlock

is an OBJECT REFERENCE containing the handle to an


object to be sent with the signal as data

This code uses vocabulary defined in base.if. You must put this as a
copyfile at the beginning of your program to use the SIGNAL verb.
SIGNAL is alternative syntax to:
invoke self "signal" using

signalId dataBlock

Object-oriented Programming with COBOL

193

oppubb.book Page 194 Tuesday, March 16, 2004 12:23 PM

194

Chapter 19 Component Frameworks

Object-oriented Programming with COBOL

oppubb.book Page 195 Tuesday, March 16, 2004 12:23 PM

195

Part 6: Micro Focus OO COBOL


Tutorials
This part contains the following chapters:

Chapter 20, Inheritance Tutorial

Chapter 21, Collections, Intrinsics and Dictionaries Tutorial

Chapter 22, Exception Handling Tutorial

Chapter 23, Requirements-based Vocabulary Tutorial

Object-oriented Programming with COBOL

oppubb.book Page 196 Tuesday, March 16, 2004 12:23 PM

196 Part 6: Micro Focus OO COBOL Tutorials

Object-oriented Programming with COBOL

oppubb.book Page 197 Tuesday, March 16, 2004 12:23 PM

197

20 Inheritance Tutorial
This tutorial is intended to demonstrate how inheritance works in OO
COBOL. It uses the example of different types of bank account, and
shows how they can inherit common behavior from a single class, while
adding new behavior or changing as necessary for individual types of
account.
This tutorial uses Micro Focus alternatives and extensions to the ISO
2002 OO COBOL syntax.
This tutorial consists of the following sessions:
1

The Account Classes

Some Simple Account Transactions

The Account Classes


This section introduces the Account classes used in this tutorial. In the
next session you will use Animator to see how they work together.
There are four account classes altogether:

Account

CheckAccount
Subclass of Account which adds behavior for checking accounts
(checks overdraft limit on withdrawals)

SavingsAccount
Subclass of Account which adds behavior for savings accounts (pays
interest)

HighRateAccount
Subclass of SavingsAccount which adds a method for checking for a
minimum starting balance to open an account
Object-oriented Programming with COBOL

oppubb.book Page 198 Tuesday, March 16, 2004 12:23 PM

198

Chapter 20 Inheritance Tutorial

CheckAccount and SavingsAccount both inherit from Account, and


HighRateAccount inherits from SavingsAccount. This hierarchy view
shows that the Account class is the superclass of all other account types.
The Account class implements the behavior common to all the different
types of bank account.
Look at the source code for the Account and SavingsAccount classes.
The Account class implements methods for constructing new accounts
"openAccount", and for debiting ("withdraw") and crediting
("deposit") accounts. The SavingsAccount class has far fewer methods,
and inherits most of its behavior from Account.
All the classes (except Account) have a method "printStatement". Each
type of account prints a different type of statement, but does it when
sent the message "printStatement". This is an example of
polymorphism.
These classes also contain methods that are not used at all in this
tutorial. The reason is that these classes are also used in the GUI bank
examples available on Windows platforms.
In the next session, you will use the Bank program to see how
inheritance works in these classes. This is a simple program which
creates accounts and sends messages to them.

Simple Account Transactions


In this session you will animate bank1.cbl, to see some simple account
transactions and how inheritance works in practice.
To animate bank1:
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory.

Run the supplied shell script bankscrp.


This compiles bank1.cbl and the account classes.

Start animating bank1. Enter the following command line:


anim bank1

Object-oriented Programming with COBOL

oppubb.book Page 199 Tuesday, March 16, 2004 12:23 PM

Simple Account Transactions

Animator starts with the statement below tag B001 is highlighted


ready for execution.
4

Step through the first three statements.


When you step invoke CheckAccount, execution switches to the
"initializeClass" method of the Account class. The method is used in
this case to execute some code for setting up error handling. For
more information about class initialization see the section Class
Initialization in the chapter Classes.
This code is the subject of another tutorial, so we execute it without
animating through it.

Push the Prfm Step keys, then the Step key again. Execution
switches to the line below tag A001 in the Account class.
CheckAccount does not implement the "openAccount" method, but
inherits it from Account.

Step statement invoke super "new".


This sends the "new" message to this object, but tells the run-time
system to start looking for methods in the code for the superclass of
Account (class Base). It returns an instance of CheckAccount.

Step the invoke statement below tag A002.


This takes you to the "setNextAccountNumber" method of Account.

Step the first statement of this method (if nextAccountNumber =


0).
Data item nextAccountNumber is declared with a value clause of 0.
When the account class or any of its subclasses is initially loaded this
data item is set to 0. The method "setNextAccountNumber" tests
this value, and if it is zero, sets an initial value. This is the first time
the CheckAccount class has received the "openAccount" message,
so nextAccountNumber needs initializing.

Step the next statement (invoke self


"getFirstAccountNumber").
Execution switches to the "getFirstAccountNumber" method of
CheckAccount. In this case, self refers to the CheckAccount class
object; although we were executing code implemented by the
Account class, the original "openAccount" message was sent to the
CheckAccount class object, which inherited its "openAccount"
method from Account.

Object-oriented Programming with COBOL

199

oppubb.book Page 200 Tuesday, March 16, 2004 12:23 PM

200

Chapter 20 Inheritance Tutorial

This method returns a value for the "openAccount" method to start


numbering accounts. Each of the subclasses of Account starts
account numbers from a different value, and they all implement
"getFirstAccountNumber" to return the starting value.
10 Step through the code up until and including the exit method.
This takes you back to the exit method statement of
"setNextAccountNumber".
11 Step the exit method statement.
This returns you to the "openAccount" method.
12 Step the next statement (invoke lsAccount "initAccount"
...).
The object handle to the newly created account object is in
lsAccount, which we are going to initialize with name, balance
and account number.
13 Step through the code up until and including the exit method.
This takes you back to the exit method statement of
"openAccount".
14 Step the exit method statement.
Execution returns to Bank1, which now has an object handle to an
instance of the CheckAccount class.
15 Step the two statements below tag B002.
This deposits $1000 in the CheckAccount instance. Again, the code
for this is all in the Account class.
16 Step through the Account code until you return to the statement
below tag B003 in Bank1.
17 Step through the two statements below tag B003.
These withdraw $50 from the CheckAccount instance. This time the
invoke switches execution to code inside CheckAccount. This is
because the CheckAccount class implements its own "withdraw"
method, which checks the withdrawal against the value allowed for
the overdraft.

Object-oriented Programming with COBOL

oppubb.book Page 201 Tuesday, March 16, 2004 12:23 PM

Simple Account Transactions

18 Step the statements below tag C010.


If the withdrawal were to exceed the overdraft set for this instance
of CheckAccount, the object would raise an exception (error
condition). In this case, the withdrawal amount is OK, so execution
proceeds as normal.
The application in this case has not registered an exception handler
to deal with account exceptions, so the error would get trapped at
the system level which would display the error number and halt
application execution. Example applications used in some of the
other OO COBOL tutorials also use these account classes, but
register an exception handler to deal with this type of error.
19 Step through the application until you reach tag B007.
Each time you open a type of account which Bank1 hasnt used
before, you have to step through the code to get an initial account
number. Also, each time you open a type of account which Bank1
hasnt used before, the class initialization code is executed, because
it is impossible to know whether other types of account have been
opened since the application started running, and therefore
whether the class initialization code has already been run.
As you execute the code, you will see that most of the code for the
different types of bank account is inherited from the Account class,
with only some methods being implemented in the subclasses.
The subclasses all inherit from the Account class with data (see the
class-idstatements at the top of each program). This means that
as well as inheriting the methods of Account, they also have direct
access to the data items declared in account. All the different
account types can access variables balance,aName and
accountNumber.
Without the with data clause in the class-id of the Account
subclasses, they could not access this data directly. Instead, they
would have to send messages to the superclass (invoke super...)
to access this data. The programmer of the Account class would
have to implement methods which respond to these messages.
20 Step the statements below B007 to open a HighRateAccount. This
takes you to tag H010 of HighRateAccount. HighRateAccount
implements its own version of "openAccount", to check the amount
of cash being used to open the account. But once it has verified this,
it still uses the "openAccount" method of Account, by sending a
message to super.
Object-oriented Programming with COBOL

201

oppubb.book Page 202 Tuesday, March 16, 2004 12:23 PM

202

Chapter 20 Inheritance Tutorial

21 Step through the rest of the code until you get to tag B008 of
Bank1.
This code demonstrates the use of polymorphism between objects
descended from a common class. All account types implement the
"printStatement" method in order to print out a statement suitable
for the different account types.
22 Step through the code to print the statements.
23 When Animator displays the "Stop run encountered..." message,
press Esc to exit.

Summary
This concludes the tutorial on inheritance. In this tutorial you learned:

How to use inheritance to reuse code.

How to use polymorphism.

Object-oriented Programming with COBOL

oppubb.book Page 203 Tuesday, March 16, 2004 12:23 PM

203

21 Collections, Intrinsics and


Dictionaries Tutorial
This tutorial is about using the collection classes. Collections are very
useful in object-oriented programming. They are used to store groups
of objects. You usually store objects of the same type in any particular
collection, although you can also store objects of different types in a
collection.
OO COBOL also enables you to store COBOL intrinsic data in
collections. This is done by a mechanism which enables you to treat an
item of intrinsic data, for example a PIC X(20), as though it were an
object. You cannot mix intrinsic data and objects inside a single
collection, or mix different types of intrinsic data.
Finally, this tutorial covers dictionaries, which are another type of
collection.
This tutorial uses Micro Focus alternatives and extensions to the ISO
2002 OO COBOL syntax.
This tutorial consists of the following sessions:

Collections

Using Intrinsics

Dictionaries

Iterator Methods

Collections
In this session you will animate a simple COBOL program, coll0.cbl
which illustrates some of the differences and similarities between the
main types of collection. The program is not an OO COBOL class

Object-oriented Programming with COBOL

oppubb.book Page 204 Tuesday, March 16, 2004 12:23 PM

204

Chapter 21 Collections, Intrinsics and Dictionaries Tutorial

program, but procedural COBOL code which uses the Class Library
collection objects.
For an explanation of the different types of collection, see the section
Different Categories of Collection in the chapter Collection
Frameworks.
To animate coll0.cbl
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory.

Compile coll0.cbl ready for animation. Enter the following


command line:
cob -a coll0.cbl

Start animating coll0. Enter the following command line:


anim coll0

Scroll through the Working-Storage Section until you see the


declaration for fruitData.
This is a set of strings the program stores in different types of
collection.

Step through the statements from A001 to A005 to create instances


of the different types of collection.
You need to specify an initial size for all types of collection. In the
case of an Array, you cant exceed the initial capacity of the
collection unless you send it the "grow" message. Other types of
collection will grow in size if you add more elements than initially
specified.
However, growing collections can be an expensive operation at runtime, so you should still always try to pick an initial size which will
reduce the number of times a collection needs to grow.

Step through the statements below tag A006 (move 20 to i).


Data item i holds the length for the instances of CharacterArray
which will be created as elements for the different types of
collection.

Object-oriented Programming with COBOL

oppubb.book Page 205 Tuesday, March 16, 2004 12:23 PM

Collections

Step the statement below tag A007 (invoke CharacterArray


"withLengthValue"...).
A CharacterArray is an object for storing strings. The
"withLengthValue" message creates a new instance of
CharacterArray and initializes it with some data.

Step the statements below tag A008 (invoke aBag "add"...)


until the end-perform statement.
With all the different collection types, except Array, you use the
"add" message to add new elements. With the Array, which does
not grow automatically, you use "atPut" which stores the element
at the specified index position.
Although OrderedCollection is indexed, you cant use "atPut" until
you have added elements to the collection. For example, once you
have used "add" to add the first five elements, you can use "atPut"
and an index between one and five to replace any of those
elements. You cant do an "atPut" with an index greater than five
until you have added more elements.
You cant ever use "atPut" to put an element in a SortedCollection.
A SortedCollection uses the value of each element to determine its
position in the collection.

Press P then E.
This completes execution of the perform loop without you needing
to step through each statement in turn.

10 Step the statements up to tag A011 (display " ").


This retrieves the object reference to the fourth element in the
Array instance. Sending the "display" message to the
CharacterArray displays it on the screen. Its contents should be the
word "banana". Press F2=View to see the console contents, and any
other key to return to the Animator display.
11 Step the next statement (invoke aBag "includes"...).
Because a Bag is not indexed, you cant retrieve elements from it
directly. Instead, you can query it to find out whether it has one or
more occurrences of an object with a given value.
The "includes" message returns 1 if a Bag contains an object with a
matching value and 0 if it doesnt. You can also examine the

Object-oriented Programming with COBOL

205

oppubb.book Page 206 Tuesday, March 16, 2004 12:23 PM

206

Chapter 21 Collections, Intrinsics and Dictionaries Tutorial

contents of unindexed collections (Bags and ValueSets) by using the


iterator methods. These are covered later in this tutorial.
12 Step the statements up until tag A012 (display " ").
These test the result of the returned value and tell you whether or
not the bag contained an object with a matching value.
13 Step the statement below tag A012 (invoke aBag "add"...).
This adds the string to the Bag again. A Bag stores objects with
duplicate values by recording the number of occurrences of each
object with a different value.
14 Step the statement below tag A013 (invoke aBag
"occurrencesOf"...).
The "occurrencesOf" message returns the number of elements a
collection has which match the specified object in value.
15 Step the statements up until tag A014 (display " ").
This displays the information that this Bag has two occurrences of
the specified string.
16 Step the statements between tag A014 (invoke anArray
"occurrencesOf"...) and A015 (display " ").
This code demonstrates how the Array also responds to the
"occurrencesOf" message. You can use "occurrencesOf" and
"includes" on indexed collections as well as instances of Bag and
ValueSet. This tells you whether or not the element exists, but not
its position.
17 Step the first statement below tag A015 (invoke aValueSet
"add"...).
Instances of ValueSet do not maintain duplicate elements. The
ValueSet already contains an element with value "banana", so it
will not be added a second time.
18 Step the next statement (invoke aValueSet
"occurrencesOf"...).
This message always returns 1 or 0 for ValueSet instances.
19 Step the other statements to tag A016 (display " ").
This displays the result of the "occurrencesOf" message.

Object-oriented Programming with COBOL

oppubb.book Page 207 Tuesday, March 16, 2004 12:23 PM

Collections

20 Press Z to execute the rest of the code in the program.


The statements below tag A016 (display "Collection
contents") display every string in the OrderedCollection and
SortedCollection in indexed order. The elements in the
OrderedCollection appear in the order in which they were added.
The elements in the SortedCollection appear sorted into ascending
alphabetical order. Ascending order is the default for a
SortedCollection.
21 Push the Esc key to exit Animator.
At the end of this section, you may have some questions to ask:

How does a collection object find out the value of an element? If all
the elements are objects, doesnt this break object encapsulation?

Similarly, how can a SortedCollection decide whether one element


has a greater value than another one?

Program coll0.cbl stores instances of CharacterArray in the collections it


creates. An instance of a CharacterArray is a simple object, with an
obvious single value (the string you store in it). But if you stored
Account objects, like the ones used in the Inheritance Tutorial in a
collection, how would you determine the value? Would it be the name,
the balance or the account number?
The answer is that the collection objects provide a framework within
which objects stored as elements must work. When a collection needs to
know whether two objects are equal, it sends one object the "equal"
message, passing it the other as a parameter. It is then up to the object
to interrogate the other element and decide whether they are equal or
not.
The default sort method for the SortedCollection works in a similar way.
The SortedCollection sends one element the "lessThanOrEqual" method
and a second element as a parameter. The receiving element can then
compare itself to the second element and return a result.
If you are writing your own objects to store in collections, you may need
to implement these methods yourself, unless you are subclassing from a
class like CharacterArray, which implements them for you. There is also
a default "equal" method in Base which compares the object handles of
two objects. This implementation of "equal" will only find two
elements equal if they are actually the same object.
For full information on the methods you might need to implement to
use the Collection classes, see the chapter Collection Frameworks.
Object-oriented Programming with COBOL

207

oppubb.book Page 208 Tuesday, March 16, 2004 12:23 PM

208

Chapter 21 Collections, Intrinsics and Dictionaries Tutorial

Using Intrinsics
In the previous session, you looked at a program which stored objects in
different types of collection. There may be occasions when you want to
store intrinsic COBOL data, like numbers, in collections. You can do this
by using the intrinsic classes of the Base Class Library.
Micro Focus OO COBOL provides a mechanism that enables you to send
a message to an intrinsic data item, as though it were an object, using
the INVOKE...AS statement.
Before you can send messages to intrinsic data, you have to clone an
intrinsic class to create a new class for the type and length of intrinsic
data you are using. The Base Class Library includes classes for three
different types of intrinsic data (PIC X, PIC X COMP-X, PIC X COMP-5).
These classes are templates which handle data of fixed length. When
you clone the class, you specify the actual size of data you want to
handle.
We will now look at a short sample program, coll1.cbl, which uses the
intrinsic classes to store a set of integers in an array.
To animate coll1.cbl
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory.

Compile coll1.cbl ready for animation. Enter the following


command line:
cob -a coll1.cbl

Start animating coll1. Enter the following command line:


anim coll1

Step the two statements below tag A001 (move 4 to i).


The "newClass" message creates a clone of the CobolComp5 class,
initialized in this case for data four bytes in length. The object
returned is a new class object, and not an instance of CobolComp5.

Step the two statements below tag A002 (move 10 to i).


This creates an instance of Array with space for ten elements. This
time the message to create the Array instance is "ofValues" (in the
example in the previous section it was "ofReferences").

Object-oriented Programming with COBOL

oppubb.book Page 209 Tuesday, March 16, 2004 12:23 PM

Dictionaries

When a collection is created with the "ofValues" message, it stores


intrinsic data instead of object handles. The cloned class,
PicX4Comp5, is used as a template so that the Array knows how
much space to allocate for each element.
You cant mix objects and intrinsics inside a single collection. Once
you create a collection you can only store the type of data for which
it is initialized. If you want to mix many different kinds of data in a
collection, you should create the collection using "ofReferences",
and use different types of objects to represent the different types of
data. There is no restriction on mixing different kinds of object
inside a collection of references.
6

Step the first statement below tag A003 (move 10 to element).

Press P then S while the execution point is on the next statement


(perform varying from 1 ...).
This executes the entire perform loop to initialize the array.

Step the statements below tag A004.


This retrieves the fourth element from the array (which has a value
of 7) and displays it. Because a data item is returned, we can show it
using the display verb; when we got back objects in the previous
example we had to send them the "display" message to show them.

Press the Esc key to exit Animator.

This completes this part of the tutorial on using intrinsic data. For more
information, see the chapter Intrinsic Data.

Dictionaries
In this session you will animate through some code which uses a
dictionary to store account objects. The account objects are the ones
which were introduced in the Inheritance Tutorial
For more information about dictionaries, see the section Creating
Dictionaries in the chapter Collection Frameworks.

Object-oriented Programming with COBOL

209

oppubb.book Page 210 Tuesday, March 16, 2004 12:23 PM

210

Chapter 21 Collections, Intrinsics and Dictionaries Tutorial

Each account object is stored in the dictionary against the customer


name. We are going to use a simple program, coll2.cbl to demonstrate
the use of the dictionary.
To animate coll2.cbl
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory.

Compile coll2.cbl ready for animation. Enter the following


command line:
cob -a coll2.cbl

Start animating coll2. Enter the following command line:


anim coll2
Animator starts with the statement below tag A040 highlighted
ready for execution.

Step the two statements below tag A040 (move length of...).
The dictionary we want to create uses the customer name as the
key, and account objects as values. This code clones the intrinsic
class CobolPicX to create a class for representing strings the same
length as a customer name.

Step the two statements below tag A050 (set wsNull to null).
This code clones the Association class, to create a template for the
dictionary. The key portion represents strings the same length as
wsCustomer, the data portion is set to null and represents an object
handle.

Step the statements below tag A060 (invoke Dictionary


"ofValues"...).
This creates the new dictionary. It is initialized to store 10 elements,
but grows automatically if more elements than this are added.

Perform Step (press P then S) the statements below tag A070 (move
spaces to wsCustomer).
This creates a check account. Using Perform Step saves animating
through all the "openAccount" code.

Object-oriented Programming with COBOL

oppubb.book Page 211 Tuesday, March 16, 2004 12:23 PM

Iterator Methods

Step the statement below tag A080 (invoke wsDictionary


"atPut"...).
The "atPut" message stores the account object at the key in
wsCustomer.

Perform Step the statements below tag A090 (move "Mike" to


wsCustomer).
This creates two more accounts, and stores them in the dictionary.

10 Step the statements below tag A100 (move spaces to


wsCustomer).
The "at" message retrieves Bobs account from the dictionary.
11 Perform Step the statement below tag A110 (invoke wsAccount
"printStatement").
The "printStatement" message displays the account details on the
console. Press F2=view to switch the display from Animator to see
what is on the console. Press any key to return to the Animator
view.
Dont shut down Animator; the next session carries on directly from
this one.
This completes this section; in the next section you will use the already
running application to look at the iterator methods for collections.

Iterator Methods
This session shows how coll2.cbl uses the iterator methods to carry out
operations on all accounts. The instructions below assume that you are
continuing directly from the end of the previous section, and have not
stopped animating coll2.cbl.
For more information about iterator methods, see the section Iterator
Methods in the chapter Collection Frameworks.

Object-oriented Programming with COBOL

211

oppubb.book Page 212 Tuesday, March 16, 2004 12:23 PM

212

Chapter 21 Collections, Intrinsics and Dictionaries Tutorial

To see the use of iterators:


1

Step the statement below tag A120 (invoke EntryCallback


"new"...).
Iterator methods pass elements in the collection to a piece of code.
An EntryCallback is an object which contains an entry-point name;
in effect it is a piece of code wrapped up inside an object. The class
library also includes a Callback class, which contains an object
handle and a message name; in effect wrapping a method up inside
an object.

Step the statement below tag A130 (invoke wsDictionary


"do"...).
The callback is passed to the "do" method inside dictionary. The
"do" method uses the callback to call the entry-point "printAll" for
each object in the dictionary. Execution switches to the the
statement below tag A160.

Perform step the statements below tag A160 (invoke lnkAccount


"printStatement").
Execution jumps straight back to the top of entry point, below tag
A160. The "do" method in the dictionary has passed its next
account object to the entry point. The entry point is called once for
every single account in the dictionary. All collections respond to the
"do" message.

Press the Zoom key to finish running the application.


The iterator prints statements for the remaining accounts in the
dictionary. You can see how the combination of collection iterator
methods, and polymorphic methods is a powerful programming
technique.

This completes the tutorial.

Object-oriented Programming with COBOL

oppubb.book Page 213 Tuesday, March 16, 2004 12:23 PM

Summary

Summary
This tutorial covered the following:

The main collection types

Intrinsic data

Dictionaries

Callbacks

Collection iterator methods

Object-oriented Programming with COBOL

213

oppubb.book Page 214 Tuesday, March 16, 2004 12:23 PM

214

Chapter 21 Collections, Intrinsics and Dictionaries Tutorial

Object-oriented Programming with COBOL

oppubb.book Page 215 Tuesday, March 16, 2004 12:23 PM

215

22 Exception Handling Tutorial


This tutorial shows you how to use the exception handling mechanism
available in the COBOL Base Class Library.
This tutorial uses Micro Focus alternatives and extensions to the ISO
2002 OO COBOL syntax.
This tutorial contains the following sessions:
1

Raising an exception

Registering an exception handler

Writing an exception handler

Raising an Exception
An object raises an exception when it has trapped an error. The objects
in the supplied class libraries define approximately ninety exception
conditions altogether.
The ExceptionManager class provides most of the logic for actually
handling exceptions, including a default exception handler. The
default exception handler displays an error message and shuts down
the application when an object raises an exception, but an application
can define its own exception handlers and attach them to individual
classes or objects to redefine their behavior.
An object raises an exception by sending itself the "raiseException"
message, passing an error number as a parameter. The Base class
implements the "raiseException" method, so it is inherited by all
objects.
The error number is used to identify a message from an error file; it is
also passed to an exception handler for the object if one is registered.

Object-oriented Programming with COBOL

oppubb.book Page 216 Tuesday, March 16, 2004 12:23 PM

216

Chapter 22 Exception Handling Tutorial

We will use the Bank application introduced in the previous tutorial to


show you how to raise and trap exceptions. When an account object
traps an error, it responds by raising an exception. For example,
attempting to open a high rate account with an initial balance of less
than $1000 is an error condition.
To animate error raising code
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory.

Run the supplied shell script exepscrp to compile all the programs
and classes needed for this tutorial.

Start animating bank3.cbl. Enter the following command line:


anim bank3
Animator starts with the first statement of bank3.cbl highlighted
ready for execution.

Move the text cursor down to the first statement below tag B010
(move "Mike" to aCustomer), and press R then C to reset to the
cursor postion.
The first statement in this program registers an exception handler.
You will look at this code later in this tutorial, so for now we skip
over it.

Step the statements below tag B010 (move "Mike" to


aCustomer).

Step the statement below tag B020 (invoke HighRateAccount


"openAccount"...).
This is the first message sent to the HighRateAccount class, so
before executing the "openAccount" method, the class
initialization code is run. The execution point appears inside the
Procedure Division of the initializeClass method.

Step the statement below tag A000 (invoke ExceptionManager


"registerMesageFile"...).
The account classes have their own set of exception numbers, and
their own set of error messages. The "registerMessageFile" message
sets up an error message file of account.lng, contained in the
appropriate COBOL default language directory. The directory
searched depends on the setting of the LANG environment variable.

Object-oriented Programming with COBOL

oppubb.book Page 217 Tuesday, March 16, 2004 12:23 PM

Raising an Exception

The way you compile and package error files is described in the
chapter Exception Handling Frameworks.
Each exception must have a unique numeric identifier, but when
you write an error message file for a set of classes, you dont
necessarily know what application those classes will be used in, and
what other message files will be in use.
The registration mechanism provided by the ExceptionManager
enables you to number your messages starting from 1. Then, when
you register a message file you are returned an offset. Each message
is then identified by adding its number in the file to the offset to
create a unique exception number. We dont need to store the
offset, since we can fetch it from the ExceptionManager when it is
needed.
8

Step the exit method statement.


Now that the class initialization code has executed, control passes to
the start of the "openAccount" method of the HighRateAccount
class.

Step the statement below tag H010 (if lsInitialValue <


1000).
The test succeeds, indicating an exception condition.

10 Step the statement below tag H011 (invoke ExceptionManager


"queryMessageFile"...).
This message returns the offset for Account class exception
numbers.
11 Step the next statement (add
insufficientFundsForAccount...).
The exception numbers are all defined as level-78 data items in
copyfileaccinfo.cpy. Adding the exception number to the offset
returned by the ExceptionManager gives us a unique exception
number which the ExceptionManager can use to fetch the error
message and display the error.
12 Step the next statement (invoke self "raiseException"...).
There is no exception handler registered for this object, so the
ExceptionManager uses the default handler, which displays the
error message and gives you the option to continue or terminate
the program.

Object-oriented Programming with COBOL

217

oppubb.book Page 218 Tuesday, March 16, 2004 12:23 PM

218

Chapter 22 Exception Handling Tutorial

13 Press T to terminate the application.


14 Press Escape to exit Animator.
In the next session we will look at how you can register an exception
handler to provide different behavior for handling exceptions.

Registering an Exception Handler


In the previous session, you saw how to raise an exception. This session
shows you how you can register an exception handler for an object. An
exception handler is a method which gets the exception number and
the object raising the exception as parameters.
You can register an exception handler for a class or an instance object. If
you register an exception handler against a class, then it is invoked for
exceptions raised by all instances of the class as well as by the class itself.
Exception handler registration is a two step process:
1

Create a CallBack for the exception method.

Register the CallBack against an object with the ExceptionHandler.

Next you will animate through the code which sets exception handlers
for the Account classes in the Bank application.
To animate the exception registration code
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory.

Start animating bank3.cbl. Enter the following command line:


anim bank3
Animator starts with the first statement of bank3.cbl highlighted
ready for execution.

Step the statement below tag B000 (invoke


AccountExceptionHandler "initializeHandlers").
Execution switches to the "initializeHandlers" method of
AccountExceptionHandler.

Object-oriented Programming with COBOL

oppubb.book Page 219 Tuesday, March 16, 2004 12:23 PM

Writing an Exception Handler

Step the statement below tag E010 (invoke CallBack "new"...).


This creates the callback for the exception handling method,
"onExceptionAccountError", which is a method of self (the
AccountExceptionHandler class). A callback is an object which
represents a particular method in a particular object. For more
information about CallBacks, see the chapter Callback Frameworks.

Step the statements below tag E020 (invoke ExceptionManager


"register"...).
This registers lsAccountError (the callback we just created) as an
exception handler for the Account class. Any exceptions raised by
the Account class or instances of the Account class will be passed to
this method.

Step through the remaining statements up to and including exit


method.
These register the same exception handler for exceptions raised by
the other account classes. The execution point is now set to the
statement below tag B010 in bank3.

Leave animator running. The next session carries on directly from


this one.

In the next session, you will look at the exception handler method, and
see how it deals with an exception raised by the account classes.

Writing an Exception Handler


This session shows you how to write an exception handler method to
deal with exceptions raised by an object. The method you write should
have an interface like the one shown below:
method-id. "errorMethod".
...
linkage section.
01 errorNumber
01 errorObject
01 aParameter

pic x(4) comp-5.


object reference.
object reference.

Object-oriented Programming with COBOL

219

oppubb.book Page 220 Tuesday, March 16, 2004 12:23 PM

220

Chapter 22 Exception Handling Tutorial

procedure division using errorNumber errorObject


returning aParameter
...
exit method.
end method "errorMethod".

The parameter returned from your exception handler can be used by


the method which raised the exception. For example, our example
exception handler returns a null object handle when an attempt to
open an account fails. The "openAccount" method code in the
HighRateAccount class which raises the exception returns the parameter
from the exception handler in place of a valid handle to an account
object.
Next you will animate the account exception handler. The instructions
below assume that you are continuing this session directly from the
previous one.
To animate the exception method
1

Set a program breakpoint on the AccountExceptionHandler class.


a

Press the keys: E P S.

Enter acexhand into the Enter Name of Program window.


acexhand is the executable program for the
AccountExceptionhandler class.

Press Z.
Execution halts inside the "onExceptionAccountError" method of
AccountExceptionHandler.

Step the statement below tag E030 (set lnkReturnObject to


null).
The parameter lnkReturnObject is ultimately returned as the
object reference to the account the application is attempting to
create.

Step the statement below tag E040 (invoke ExceptionManager


"queryMessageFile"...).
So that the exception handler knows what action to take, it must
extract the exception number from the exception id passed through
to the method. The "queryMessageFile" message gets the offset
value currently being used for account objects.

Object-oriented Programming with COBOL

oppubb.book Page 221 Tuesday, March 16, 2004 12:23 PM

Writing an Exception Handler

Step the statement below tag E050 (subtract lsOffset


from....).
The result in lsException corresponds to the exception numbers
defined in the error message file.

Step the statement below tag E060 (if lsException < 4).
The exception handler must now determine what type of exception
has been raised in order to take the appropriate action. If the
exception type isnt one it knows how to deal with, it raises the
exception again (see the code below tag E080).
More sophisticated exception handlers take different action
depending on the type of exception; this exception handler simply
categorizes account exception numbers between one and three as
being those it understands, and those of four or greater as
exceptions to be raised again.

Step the statements below tag E070 (invoke ExceptionManager


"errorMessage"...).
This code fetches the error message (which is returned as a
CharacterArray object) from the ExceptionManager and displays it.
The only difference between this and the default exception handler
is that this handler doesnt terminate the application. Push F2=View
to see the message, and any other key to return to the Animator
display.

Step the code up to and including the exit method statement.


Execution returns to the HighRateAccount class, at the point below
the statement which raised the exception. The return parameter
from the "raiseException" message is lsAccount - this was set to null
by the exception handler. lsAccount is the result returned from the
"openAccount" method, so the code which sent the "openAccount"
message can test the handle returned - if it is null an exception has
occurred.

Step through the application until you see the Stop Run message
from Animator.

10 Press Escape to exit Animator.


This concludes this tutorial on exception handling.

Object-oriented Programming with COBOL

221

oppubb.book Page 222 Tuesday, March 16, 2004 12:23 PM

222

Chapter 22 Exception Handling Tutorial

Summary
In this tutorial you learned how to:

Raise an exception

Register an exception handler

Write an exception handler

Object-oriented Programming with COBOL

oppubb.book Page 223 Tuesday, March 16, 2004 12:23 PM

223

23 Requirements-based
Vocabulary Tutorial
Requirements-based vocabulary enables you to create new verbs and
functions related to types of application you are working on. This
tutorial demonstrates this feature, using the bank account classes
introduced in the chapter Inheritance Tutorial.
This tutorial uses Micro Focus alternatives and extensions to the ISO
2002 OO COBOL syntax.
This tutorial consists of the following sessions:
1

Vocabulary for the Account Classes

Using Requirements-based Vocabulary

Introducing the Vocabulary Example


In this session you will load an example application similar to the one
used in the inheritance tutorial. The only difference is in the driver
program, bank2.cbl, which uses a vocabulary defined for the account
classes to send them messages, instead of the INVOKE statement.
To look at the Bank vocabulary example:
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory.

Load bank2.cbl into the Editor.

The first two statements in the program are COPY statements


(page down to just below the introductory comments).
Account.if and saccount.if are copyfiles used by bank2. They are
the class interface files which define new vocabulary for use with
the Account and SavingsAccount classes. Because the methods of

Object-oriented Programming with COBOL

oppubb.book Page 224 Tuesday, March 16, 2004 12:23 PM

224

Chapter 23 Requirements-based Vocabulary Tutorial

Account are inherited by all types of account, with no interface


changes, the vocabulary defined in account.if applies to all the
account classes. The saccount.if file defines extra vocabulary
appropriate to SavingsAccount (and HighRateAccount which is a
subclass of SavingsAccount).
4

Put the cursor on the statement copy account.if and press AltF2=library to view account.if.
The class-id header at the start of account.if defines it as an
external class. The Compiler does not generate any code for
external classes.

Find the "openAccount" method.


This has the same method-id, linkage section and procedure
division headers as the "openAccount" method in account.cbl.
However, there are no executable statements in the Procedure
Division. Instead, there is a syntax definition of a new verb, Create.

Look at the definition of the create verb.


Below the procedure division header is the invoked as
phrase. The words in brackets [ ] are noise words, included for
readability. You dont have to include them when you use the
create verb.
Words inside angle brackets <> are the parameters to the routine,
with the exception of <self>. <self> is the object reference to the
object which receives the message. Every parameter in the
definition of the verb is in the procedure division header using
and returning clauses. The procedure division and linkage
section headers match exactly those in the openAccount method
of the Account class itself.
The syntax for defining new verbs and functions is covered in the
chapter Requirements-based Vocabulary.

This is the end of the first session. In the next session you will look at
some code which uses the new syntax.

Object-oriented Programming with COBOL

oppubb.book Page 225 Tuesday, March 16, 2004 12:23 PM

Using Requirements-based Vocabulary

Using Requirements-based Vocabulary


In this session you will animate bank2.cbl, which does exactly the same
as bank1.cbl, which you animated in the inheritance tutorial. However
it does it using the new verbs defined in the interface files you looked
at in the previous session of this tutorial.
To animate the vocabulary example source code
1

Use Infomgr to locate the demonstration programs and transfer


them to a working directory.

Run the supplied shell script vocascrp.


This compiles bank2.cbl and the account classes.

Start animating bank2. Enter the following command line:


anim bank2
Animator starts with the statement below tag B002 highlighted
ready for execution.

Step the lines below tag B002.


The message to open a new CheckAccount is sent by the new verb
create, which is defined in account.if. Execution switches to the
"openAccount" method of Account (CheckAccount inherits the
"openAccount" method from Account).

Step through the account creation code until execution returns to


the line below tag B003 of bank2.int.

Step through the code of bank2.cbl until you reach tag B008.
As you step through the code, you can see how the same verbs can
be used for SavingsAccounts and CheckAccounts.

Step the line below B008 (if balance(asAccount)...).


This conditional statement uses the balance function. This is an
example of a function definition. You can use it in the same sorts of
ways as you can use an intrinsic COBOL function; for example in a
conditional statement or as part of a compute statement. This
function is defined in account.if along with the other verbs used in
this tutorial.

Object-oriented Programming with COBOL

225

oppubb.book Page 226 Tuesday, March 16, 2004 12:23 PM

226

Chapter 23 Requirements-based Vocabulary Tutorial

Step through the code until you reach the stop run statement.

Press Escape to exit Animator.

This ends this tutorial on Requirements-based Vocabulary. You can


study account.if and saccount.if to see how you can define vocabulary
for any objects you create.

Summary
This tutorial covered the following:

How new verbs are defined and made available to client programs
How to use the verbs defined for a set of classes.

How to use the verbs defined for a set of classes.

Object-oriented Programming with COBOL

oppubb.book Page 227 Tuesday, March 16, 2004 12:23 PM

227

Part 7: Appendices
This part contains the following chapters:

Appendix A , Descriptions of OO Run-time Switches

Object-oriented Programming with COBOL

oppubb.book Page 228 Tuesday, March 16, 2004 12:23 PM

228 Part 7: Appendices

Object-oriented Programming with COBOL

oppubb.book Page 229 Tuesday, March 16, 2004 12:23 PM

229

A Descriptions of OO Run-time
Switches
This appendix describes the available switches for the OO support in
the run-time system. Each entry describes the effect of the switch when
it is set on. The default setting that applies if you do not explicitly set
any of these switches is also given.
All OO RTS switches are set in the environment variable OOSW. Specify
a minus "-" before a switch to turn it off, and a plus "+" to turn it on.
You can concatenate several switch settings into OOSW at a time. For
example:
OOSW=-v+d
export OOSW

turns off the v switch and turns on the d switch.


Switch names are all case sensitive.
The following switches are available:
d

Debug switch.

Set name of trace file.

lfilename

Class Library load switch.

Generate trace file.

+g1

Set guard page before object storage and memory


allocations

+g2

Set guard page after object storage and memory


allocations

Object-oriented Programming with COBOL

oppubb.book Page 230 Tuesday, March 16, 2004 12:23 PM

230

Appendix A Descriptions of OO Run-time Switches

List of Switches
d - Debug Switch
Enables debugging by preventing reuse of object handles from finalized
objects.
Properties:
Remarks:

Default:

-d

In normal operation, each time an object is finalized its object handle is


available for reuse by the run-time system and can be assigned when a
new object is created. Setting +d prevents the run-time system from
reallocating object handles.
Do not use this switch for production applications: the run-time system
can eventually run out of memory to allocate new handles. For more
information, see the section Preventing Reallocation of Object Handles
in the chapter Compiling and Debugging Object COBOL Applications.

f - Trace File Name


Enables you to name the message trace file. Properties:
Default:
Remarks:

+ftrace.log

Setting this switch to -f also has the effect of naming the log file
trace.log.

g1 - Guard page before storage


Sets a guard page before Object-Storage Sections and before memory
allocated through class library method "malloc".
Properties:
Remarks:

Default:

-g1

You cannot set +g1 and +g2 at the same time. Only set +g1 when
debugging as it increases memory overhead.

Object-oriented Programming with COBOL

oppubb.book Page 231 Tuesday, March 16, 2004 12:23 PM

List of Switches

This switch is not available on all UNIX platforms. Check the release
notes for your platform.

g2 - Guard page before storage


Sets a guard page after Object-Storage Sections and after memory
allocated through class library method "malloc".
Properties:
Remarks:

Default:

-g2

You cannot set +g1 and +g2 at the same time. Only set +g2 when
debugging as it increases memory overhead.
This switch is not available on all UNIX platforms. Check the release
notes for your platform.

l - Class Library Load Switch


Sets the Class Library to be preloaded by the run-time system.
Properties:
Remarks:

Default:

+lclass

Set the class library load switch to -l to disable loading of the class
libraries. You can use this if you want to animate classes (see the section
Animating the Class Libraries in the chapter Introduction to the Class
Libraries).
If you have your own class library in a .lbr file, you can load that instead
of the Micro Focus class libraries. Set:
+lfilename

You can load more than one class library with the +l switch; separate
the names with colons ":". For example:
+llib1:lib2

Do not leave any spaces between the names.

Object-oriented Programming with COBOL

231

oppubb.book Page 232 Tuesday, March 16, 2004 12:23 PM

232

Appendix A Descriptions of OO Run-time Switches

t - Trace File
Generate a trace file showing every message sent by your application.
Properties:
Remarks:

Default:

-t

A trace file shows you the messages sent by your application and is
useful for debugging. Do not set this switch when running production
applications: trace slows down execution, and the log file will grow in
size continuously while the application runs.

Object-oriented Programming with COBOL

oppubb.book Page 233 Tuesday, March 16, 2004 12:23 PM

233

Index

A
ACTUAL-PARAMS Compiler directive 62, 79,
81
ALIGN Compiler directive 81
Animating
class libraries 149
Associations 154
Attributes 22
Automatically growable collections 152

B
Base class 28, 50, 54
Base Class Library 145
Behavior class 50, 54, 69, 85
Binding
dynamic 25
Browse tool 18

C
Callback frameworks 173
Called program not found RTS error 90
CASE Compiler directive 81
Character arrays 156
Class libraries 28, 145
animating 149
Classes 23, 47
declaring 34
extending 134

initialization 57
intrinsic data 168
parameterized 60
structure 48, 127
tutorial 101
Class-id 102
.cls file 83, 131
CobolComp5 class 166
CobolCompX class 166
CobolPicX class 166
"collect" method 163
Collection frameworks 151
tutorial 203
COM Class Library 145
COM Component Class Library 145
Comparison
elements of collection 158
Compiler directive
ACTUAL-PARAMS 62, 79, 81
ALIGN 81
CASE 81
FASTCALLS 81
FASTLINK 81
FIXOPT 81
OO program 81
OOCTRL 81, 129
PARAMCOUNTCHECK 81
RDFPATH 81
REENTRANT 81
REPOSITORY 41, 81
SERIAL 81
Compiling
OO program 81
Component Framework 187
Conformance checking 35, 39, 40, 60, 78
Connecting components 191
Object-oriented Programming with COBOL

oppubb.book Page 234 Tuesday, March 16, 2004 12:23 PM

234

D
Data
factory objects 56
inheritance 54, 130
instance objects 58
methods 65
DATA IS PRIVATE clause 131
DATA IS PROTECTED clause 130
Data item
PROPERTY clause 72
Debugging
OO program 84
DECLARE SOCKET verb 190
"deepFinalize" method 44
DEFINE SIGNAL verb 188
Demand loading 57
Development
OO programs 18
Dictionaries 154
tutorial 209
Direct data inheritance 130, 132
compilation 83
Display mechanisms
collections 160
"do" method 162
Duplicate elements
collections 152
Dynamic binding 25
Dynamic filename assignment
OO programs 55

E
Elements of collection
comparison 158
Encapsulation 26
Entry points
creating callback 173
EntryCallback class 173

Object-oriented Programming with COBOL

Environment variable
OOSW 85, 87, 229
Equality comparisons 158
Error handling 177
Error message files
creating 178
registering 179
Exception handler 182
Exception handling 177
tutorial 215
Exceptions
raising 181
Extension
class 134
EXTERNAL clause 55
External repository 34, 41

F
Factory
data 103
methods 57, 103
Factory objects 23, 48, 103
data 56, 57
data inheritance 54
method inheritance 51
writing 56
"FactoryObject" method 68
FASTCALLS Compiler directive 81
FASTLINK Compiler directive 81
File
.cls 83
.if 141
.ins 83
.cls 131
.ins 131
trace.log 87
File connectors 55
File handling
OO programs 55
File sharing 55

oppubb.book Page 235 Tuesday, March 16, 2004 12:23 PM

235

Files
OO programs 55
"finalize" method 43
Finalized object references 44
FIXOPT Compiler directive 81
Framework
component 187
Frameworks 148
Callbacks 173
collection 151
exception handling 177
Function signature 139

G
Garbage collection 43
Get property methods 40, 71
"getNumberOfObjects" method 85
Guard pages 86
GUI Class Library 145

H
Hash mechanisms
collections 159
Hierarchy of classes 27, 50
Hierarchy of interfaces 75

I
.if file 141
Implementation
interface 75, 77
Indexed collections 152
Inheritance 27, 50, 75
data 54, 130
methods 51

polymorphism 29
tutorial 197
Initialization
classes 57
instance objects 59
Inline method invocation 39
tutorial 111
Input socket 190
.ins file 83, 131
Instance methods 60
Instance objects 23, 48, 104
creating 42, 69
data 58
data inheritance 54
initialization 59
method inheritance 51
writing 58
Interfaces 25, 40, 75
inheritance 29
parameterized 78
polymorphism 29
tutorial 119
Intrinsic data 165
storing 153, 154
tutorial 208
INVOKE statement 39
INVOKE...AS statement 167
ISO 2002 COBOL 17, 127
Iterator methods 162
tutorial 211

J
Java domain Class Library 145
Java support Class Library 145

L
Linkage Section
OO program 65
Object-oriented Programming with COBOL

oppubb.book Page 236 Tuesday, March 16, 2004 12:23 PM

236

Local-Storage Section
OO program 65

M
MAKE COMPONENT verb 188
Manually growable collections 152
MAP SIGNAL verb 190
Memory exceptions 89
Memory leaks 43
finding 85
Message
send 97
Messages
sending 25, 38
sending to intrinsic data 167
tracing 87
Metaclass 50
Method
interface definition 139
Method definition
PROPERTY clause 72
Method prototypes 24, 25, 75
Method selector 26
Methods 24, 65
data 65
exception handler 183
executing 25, 38
factory 57, 103
inheritance 51
inline invocation 39
instance 60
invocation 89
invocation using object properties 40, 71
parameter types 147
parameters 66
Working-Storage Section 129
Micro Focus OO COBOL 17, 127
Multiple inheritance 28, 50, 131
interfaces 75
methods 51
tutorial 111
Object-oriented Programming with COBOL

N
"new" method 42, 69
"newClass" method 166
NIL predefined object reference name 68
Non-indexed collections 152
NULL predefined object reference name 68
Null-terminated literals 174

O
Object data guard pages 86
Object handles 35, 69, 84
preventing reallocation 84
reallocation 44
Object properties 40, 71
syntax 73
tutorial 111
Object reference names
predefined 67
Object references 35
finalized 44
querying 84
Object views 37
tutorial 111
Object-oriented analysis and design 19
Object-oriented COBOL
syntax 17
Objects 22, 33
canceling exception registration 185
creating 42, 69
destroying 43
passing 37
registering with exception handler 185
storing 153, 154
Object-Storage Section 86, 129
OO COBOL
RTS switches 229
toolbar 18
OO wizard 18
OOCTRL Compiler directive 81, 129

oppubb.book Page 237 Tuesday, March 16, 2004 12:23 PM

237

OO-DESKTOP external variable 68


OOSW environment variable 85, 87, 229
Output signal 188

P
PARAMCOUNTCHECK Compiler directive 81
Parameter types
methods 147
Parameterized classes 60
tutorial 119
Parameterized interfaces 78
Parameters
methods 66
Polymorphism 29, 37
Predefined object reference names 67
Private data 131
Private interfaces 147
Procedures 22
Program not found RTS error 90
PROPERTY clause
data item definition 72
method definition 72
Protection violations 89
Public interfaces 147, 148

S
"select" method 162
SELF predefined object reference name 67
SELFCLASS predefined object reference name
68
Sending messages 25, 38, 97
Sending signals 192
SERIAL Compiler directive 81
Set property methods 40, 71
SET statement 37
Shared data 128, 129
Signal 187
SIGNAL verb 192
Socket 187
Sort methods
collections 161
Subclasses 27, 50
SUPER predefined object reference name 68
Superclasses 27, 50
Symbol redefined RTS error 90
Syntax
comparison 127
System exception method 185

T
R
RDFPATH Compiler directive 81
REENTRANT Compiler directive 81
"reject" method 162
Relative value comparisons 158
REPOSITORY Compiler directive 41, 81
Repository paragraph 34
Requirements-based vocabulary 137
tutorial 223
RTS switches
OO COBOL 229

trace.log file 87
Tracing messages 87
Tutorial
collections 203
dictionaries 209
exception handling 215
inheritance 197
interfaces 119
intrinsic data 208
iterator methods 211
more complex class 111
parameterized classes 119
requirements-based vocabulary 223
simple class 101

Object-oriented Programming with COBOL

oppubb.book Page 238 Tuesday, March 16, 2004 12:23 PM

238

Typed object references 35

U
Universal object references 35, 39
Untyped object references 35
User-defined function
creating 141

V
Verb signature 139
Vocabulary
see Requirements-based vocabulary

W
WITH DATA phrase 130
Wizard
OO program 18
Working-Storage Section 86, 103
classes 128
ISO 2002 COBOL 129
methods 129
OO program 65

Object-oriented Programming with COBOL

Вам также может понравиться