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 obj
Trang 2Copyright © 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 ROM, 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
CD-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
Trang 3Table of Contents
About this Book 11
Audience 11
Notation 11
Command Lines 12
Side Headings 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
2 OO Programming Concepts 21
Overview 21
Objects 22
Classes 23
Methods 24
Interfaces 25
Messages 25
Encapsulation 26
Inheritance 27
Polymorphism 29
Trang 4Part 2: Object-oriented COBOL Programming
3 Using Objects in Programs 33
Overview 33
Declaring Classes 34
Using Object References 35
Declaring Object References 35
Manipulating Object References 36
Object Views 37
Sending Messages 38
Using the INVOKE Statement 39
Inline Method Invocation 39
Invocation Using Object Properties 40
Conformance 40
Creating a New Instance Object 42
Destroying Objects 43
Object Destruction Methods 43
Finalized Object References 44
4 Classes 47
Overview 47
Class Structure 48
Inheritance 50
Method Inheritance 51
Data Inheritance 54
Files in OO Programs 55
Programming Factory Object Behavior 56
Factory Object Data 56
Class Initialization 57
Factory Methods 57
Programming Instance Object Behavior 58
Instance Data 58
Instance Initialization 59
Instance Methods 60
Trang 5Parameterized Classes 60
5 Methods 65
Overview 65
Method Data 65
Predefined Object Reference Names 67
Instance Creation Methods 69
Get and Set Property Methods 71
PROPERTY Clause in a Data Item Definition 72
PROPERTY Clause in a Method Definition 72
Coding the Object Property Syntax 73
6 Interfaces 75
Overview 75
Interface Source Elements 75
Interface Implementation 77
Parameterized Interfaces 78
7 Compiling and Debugging OO COBOL Applications 81 Compiling 81
Compiler Directives 81
Directly Inherited Data 83
Debugging 84
Preventing Reallocation of Object Handles 84
Finding Memory Leaks 85
Object Data Guard Pages 86
Message Tracing 87
Troubleshooting Tips 89
Memory Exceptions and Protection Violations on Method Invocations 89
Symbol Redefined 90
Program Not Found 90
Trang 6Part 3: Tutorials
8 Objects and Messages Tutorial 95
The Stopwatch Class 95
Sending Messages 97
Summary 100
9 Simple Class Tutorial 101
Structure of a Class 101
Identifying a Class 102
Identifying Classes Used by a Program 102
The Factory Object Source Element 103
Factory Methods 103
The Instance Object Source Element 104
Instance Methods 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
Trang 7Part 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 138
External Class Structure 138
Method Interface 139
User-defined Functions 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
Trang 815 Collection Frameworks 151
Overview 151
Different Categories of Collection 152
Creating Collections 153
Creating Dictionaries 154
Working with CharacterArray Objects 156
Creating a CharacterArray Object 156
Querying a CharacterArray Object 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
Trang 918 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 182
Writing Exception Handler Methods 183
Registering an Object with the Exception Handler 185
Canceling an Exception Registration 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
Trang 1022 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
Trang 11About 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
Trang 12Windows: 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 User’s Guide contains a UNIX
Key Usage Chart, listing how the keystrokes shown in the books map onto actual keystrokes
Trang 13Notation 13
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: This text applies to Server Express on UNIX
Net Express: This text applies to Net Express on Windows
Trang 17This 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
Trang 18Developing 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
Trang 19What to Read Next 19
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 oriented methodologies and technologies
object-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
Trang 20Rumbaugh 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 independent courses on OOD and OOA
Trang 21This chapter describes the key concepts supported by an oriented 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
• Encapsulation
• Inheritance
• Polymorphism The following sections describe these elements and characteristics in turn, and how they are implemented in OO COBOL
Trang 22An object is a combination of data and the procedures to operate on that data The data is known as the object’s 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
Trang 23An 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 class’s own data and behavior
The class does not have the same behavior as the instances it creates A class is like a printer’s 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
Trang 24Figure 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
Trang 25method 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).
Trang 26Messages 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 object’s 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
Trang 27Inheritance 27
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
Trang 28Inheritance 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
Trang 29Polymorphism 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 don’t 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)
Trang 30Figure 2-6 Polymorphism
Trang 31Part 2: Object-oriented COBOL Programming
This part contains the following chapters:
• Chapter 3, “Using Objects in Programs”
Trang 33This 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.
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
Trang 34Generally, 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
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 class’s 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
Trang 35Using Object References 35
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 anObject usage object reference
01 secdObject usage object reference factory of BankAccount
01 thirdObject usage object reference active-class
01 fourthObject usage object reference Rentable
The first line defines an untyped or universal object reference
Trang 36The 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:
Trang 37Using Object References 37
No other operations are valid, because the object reference contains only a handle to an object To change or interrogate an object’s 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
01 obj1 usage object reference class shape
01 obj2 usage object reference class circle
01 obj3 usage object reference class triangle
01 obj4 usage object reference class rectangle
set obj1 to obj2set obj1 to obj3set obj1 to obj4This 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 obj1This 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
Trang 38This 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
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
Trang 39Sending Messages 39
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 myObjectHowever, 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
Trang 40This 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-balanceThis 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
• An interface can also be a collection of method prototypes, specifying some behavior
Part of an object’s 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