In Java you can define “static initializers”, which are run automatically when the class is initially loaded. In Java it’s something like this.
public class Test { static { // do initialization here. } }
Can this be done in Visual COBOL? I tried googling it, but google AI seems to be returning nonsense.
Best answer by Chris Glazier
This can be done by including a static “new” method within the class. This will be run when the class is loaded.
Example:
program-id. main as "teststatic.main". data division. working-storage section. 01 any-key pic x. 01 p procedure-pointer. procedure division. set p to entry "teststatic.myclass" display "in main" accept any-key
goback.
end program main.
class-id teststatic.myclass public. working-storage section. 01 any-key pic x static. method-id new static. procedure division. display "in static New". accept any-key goback. end method.
method-id testit. local-storage section. 01 any-key pic x. procedure division. display "in testit". accept any-key goback. end method. end class.
This can be done by including a static “new” method within the class. This will be run when the class is loaded.
Example:
program-id. main as "teststatic.main". data division. working-storage section. 01 any-key pic x. 01 p procedure-pointer. procedure division. set p to entry "teststatic.myclass" display "in main" accept any-key
goback.
end program main.
class-id teststatic.myclass public. working-storage section. 01 any-key pic x static. method-id new static. procedure division. display "in static New". accept any-key goback. end method.
method-id testit. local-storage section. 01 any-key pic x. procedure division. display "in testit". accept any-key goback. end method. end class.
Now I am curious why you did your example program as you did. I mean setting a procedure pointer instead of invoking the class to create an instance of it. Is this method useful in a real world situation?
I just wanted to show that the static new method was invoked automatically when loading the class without invoking any methods in the class and no, it would probably not be too useful in a real world situation.