BudiBadu Logo
Samplebadu

COBOL by Example: Object-Oriented

COBOL 2002

Implementing object-oriented programming in COBOL 2002+ standard, defining classes with CLASS-ID and INHERITS for inheritance, encapsulating instance data in OBJECT paragraph, creating public methods with METHOD-ID and RETURNING values, and integrating with Java and .NET runtime environments.

Code

       IDENTIFICATION DIVISION.
       CLASS-ID. ACCOUNT INHERITS BASE.
       
       ENVIRONMENT DIVISION.
       CONFIGURATION SECTION.
       REPOSITORY.
           CLASS BASE.
           
       IDENTIFICATION DIVISION.
       OBJECT.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  BALANCE PIC 9(9)V99.
       
       PROCEDURE DIVISION.
       METHOD-ID. GET-BALANCE.
       DATA DIVISION.
       LINKAGE SECTION.
       01  RET-VAL PIC 9(9)V99.
       PROCEDURE DIVISION RETURNING RET-VAL.
           MOVE BALANCE TO RET-VAL.
       END METHOD GET-BALANCE.
       END OBJECT.
       END CLASS ACCOUNT.

Explanation

Modern COBOL (since 2002) supports Object-Oriented programming, allowing it to integrate seamlessly with Java and .NET environments. You can define classes with CLASS-ID, methods with METHOD-ID, and instantiate objects using the INVOKE statement.

In this example, we define a simple ACCOUNT class. It follows the standard OO encapsulation principle: the data (BALANCE) is defined in the Object paragraph and is private to the instance, while the behavior (GET-BALANCE) is exposed as a public method.

The structure is strictly hierarchical: A CLASS-ID contains an OBJECT paragraph (defining instance data), which in turn contains METHOD-ID blocks (defining code). This structure ensures clear separation of class-level and instance-level logic.

Code Breakdown

2
CLASS-ID. ACCOUNT. Defines the class name.
2
INHERITS BASE. Specifies inheritance. All COBOL classes must inherit from a base class (often provided by the runtime).
10
OBJECT. Starts the definition of the object instance. Data defined here (like BALANCE) exists for each object created.
15
METHOD-ID. GET-BALANCE. Defines a public method. It has its own Data and Procedure divisions.
17
LINKAGE SECTION. Used here to define the return value of the method.
19
PROCEDURE DIVISION RETURNING RET-VAL. Specifies that when the method finishes, the value of RET-VAL is sent back to the caller.