Instantiating Java Objects

Restriction: This applies to native code only.

Each Java class has one or more constructor methods to instantiate objects. In Java, constructor methods have the same name as the class. To enable you to invoke these methods from COBOL, they are mapped to the "new" method name on the COBOL proxy object.

The different constructors on a Java class take different numbers and combinations of parameters to initialize the instance you are creating. For example, the Java Rectangle class can be instantiated in several different ways, including the two shown below in Java code:

 Rectangle r1 = new Rectangle () 
              //  rectangle (x,y) = 0,0, width=0, height=0
 Rectangle r2 = new Rectangle(4, 5, 10, 20) 
             // rectangle (x,y) = (4,5), width=10, height=20

The equivalent COBOL code is shown below:

 working-storage section. 
 01 r1                  object reference. 
 01 r2                  object reference. 
 ...

 procedure division. 
 ...
     invoke jRectangle "new" returning r1 
          *> rectangle (x,y) = 0,0, width=0, height=0
     invoke jRectangle "new" using 4, 5, 10, 20 
                         returning r2 
          *> rectangle (x,y) = (4,5), width=10, height=20

The COBOL run-time system uses the number and type of parameters to call the appropriate constructor on the Java class. You must be careful to provide parameters of the types expected by the Java class, as Java is a strongly typed language. The chapter Java Data Types explains how COBOL data types are mapped onto Java data types. The copybook javatypes.cpy also defines a set of data types for use in COBOL which correspond directly to Java data types; you are recommended to use these for transferring data between Java and COBOL.