Calling Java Methods

Restriction: This applies to native code only.

You can call any of the methods on a Java object by sending it a message with the same name as the method. You can also call the static methods of a Java class - send the message to the classname declared in the Class-Control paragraph of your program. Method names in Java are case-sensitive, so the case of the message name in COBOL must match the case of the method in Java.

Java allows method overloading - where one method name has different implementations according to the number and type of parameters passed. COBOL handles this transparently for you, so that the correct Java method is always called.

For example, the Rectangle class has three different add() methods, which take different parameters. The Java code below shows three different ways you can call the add() method on a rectangle.

 Rectangle r1 = new Rectangle(0,0,0,0) ;
 Point pt = new Point(6,6) ; 
 Rectangle r2 = new Rectangle(3,4,9,9) ;  
 r1.add(4,5) ; // changes r1 to smallest rectangle 
               //  containing r1 and point 4,5
 r1.add(pt) ;  // changes r1 to smallest rectangle 
               //  containing r1 and Point pt. 
 r1.add(r2) ;  // changes r1 to union of r1 & r2 

The equivalent code in COBOL looks like this:

 repository.
     class jRectangle as"$java$java.awt.Rectangle"
     class jPoint as "$java$java.awt.Point"
     .
 working-storage section. 
 01 r1                 object reference. 
 01 r2                 object reference. 
 01 pt                 object reference. 

 procedure division. 
     invoke jRectangle "new" returning r1
     invoke jPoint "new" using 4 5 returning pt
     invoke jRectangle "new" using 3 4 9 9 returning r2
     invoke r1 "add" using 4 5  
     invoke r1 "add" using pt 
     invoke r1 "add" using r2 

Although r2 and pt are both data items of type object reference, the COBOL run-time system determines the type of Java object represented and calls the correct Java method.