An OBJECT in object-oriented COBOL is an instance of a class that contains data (attributes) and can execute methods. Objects are created at runtime and represent specific instances of the class template.
Object creation and usage in COBOL involves several components:
1234* Declaring object references 01 my-object OBJECT REFERENCE. 01 employee-obj OBJECT REFERENCE Employee. 01 calculator-obj OBJECT REFERENCE Calculator.
OBJECT REFERENCE declares variables that can hold object instances.
123456789* Creating objects using factory methods INVOKE Employee "NEW" RETURNING employee-obj. * Alternative creation syntax SET employee-obj TO NEW Employee. * Creating with parameters INVOKE Employee "NEW" USING "John Doe", 1001 RETURNING employee-obj.
1234* Invoking methods on objects INVOKE employee-obj "GetName" RETURNING employee-name. INVOKE employee-obj "SetSalary" USING new-salary. INVOKE calculator-obj "Add" USING a, b RETURNING result.
Here are some practical uses of objects in COBOL:
12345678910111213141516171819202122232425* Working with employee objects 01 employee1 OBJECT REFERENCE Employee. 01 employee2 OBJECT REFERENCE Employee. 01 emp-name PIC X(30). 01 emp-salary PIC 9(7)V99. PROCEDURE DIVISION. MAIN-PROCESS. * Create employee objects INVOKE Employee "NEW" USING "John Doe", 50000 RETURNING employee1. INVOKE Employee "NEW" USING "Jane Smith", 60000 RETURNING employee2. * Access object methods INVOKE employee1 "GetName" RETURNING emp-name. INVOKE employee1 "GetSalary" RETURNING emp-salary. DISPLAY "Employee: " emp-name. DISPLAY "Salary: " emp-salary. * Modify object state INVOKE employee1 "SetSalary" USING 55000. STOP RUN.
Creating and manipulating employee objects.
12345678910111213141516171819202122* Working with calculator objects 01 calc OBJECT REFERENCE Calculator. 01 result PIC 9(6)V99. 01 a PIC 9(3) VALUE 10. 01 b PIC 9(3) VALUE 20. PROCEDURE DIVISION. CALCULATE. * Create calculator object INVOKE Calculator "NEW" RETURNING calc. * Perform calculations INVOKE calc "Add" USING a, b RETURNING result. DISPLAY "Sum: " result. INVOKE calc "Multiply" USING a, b RETURNING result. DISPLAY "Product: " result. INVOKE calc "Divide" USING b, a RETURNING result. DISPLAY "Quotient: " result. STOP RUN.
Using calculator objects for mathematical operations.
1. What is an OBJECT in object-oriented COBOL?
2. How do you create an object in COBOL?
3. What does the OBJECT-REFERENCE data type represent?
4. How do you invoke methods on an object?
5. What is the relationship between CLASS and OBJECT?