Method programming in COBOL refers to the object-oriented (OO) features added in COBOL 2002 and supported by some compilers: classes, object references, and methods. You call methods with the INVOKE statement, passing parameters with USING and receiving return values with RETURNING. This page introduces method invocation, object references, and when OO COBOL is used.
A method is an action that belongs to an object or a class. In procedural COBOL you use CALL or PERFORM to run code. In OO COBOL you say INVOKE and name the object and the method, like "tell this account object to do DEBIT." The object holds the data; the method does something with it. INVOKE is how you "tell" the object to run that method. Creating a new object is usually done by invoking the class's "NEW" method, which gives you back a new object reference.
INVOKE calls a method on an object reference or on a class. Basic form: INVOKE object-reference method-name. You can pass arguments with USING and receive a result with RETURNING. Optional ON EXCEPTION and NOT ON EXCEPTION handle success or failure. The method that runs is determined at runtime by the object's class (polymorphism).
12345678910111213141516*> Assume MY-OBJECT is an OBJECT REFERENCE, and "DO-SOMETHING" is a method INVOKE MY-OBJECT "DO-SOMETHING" USING WS-INPUT RETURNING WS-RESULT ON EXCEPTION DISPLAY "Method failed" NOT ON EXCEPTION DISPLAY "Result: " WS-RESULT END-INVOKE *> Create a new object (factory method) INVOKE MyClass "NEW" RETURNING MY-OBJECT ON EXCEPTION DISPLAY "Creation failed" END-INVOKE
An object reference is a data item that refers to an object. You declare it with OBJECT REFERENCE [class-name]. It does not hold the object's data; it points to the object. You get an object by invoking "NEW" on a class and RETURNING into the object reference, or by receiving it from another method or parameter. You then use that reference in INVOKE to call instance methods.
An instance method is invoked on an object reference (INVOKE my-obj method-name). It operates on that instance. A factory or static method is invoked on the class (INVOKE ClassName "NEW" RETURNING my-obj). "NEW" is the standard way to create a new instance. Other static methods might be called on the class name when they do not need instance data.
1. How do you call a method on an object in COBOL?
2. How do you create a new object in OO COBOL?