COBOL | Java |
---|---|
delegate-id MessageHandler (str as string). end delegate. class-id DelegatesEvents. 01 MessageArrived event type MessageHandler static. method-id Main static. *> explicit delegate construction invoke new MessageHandler(MyHandler) *> implicit delegate construction declare handler as type MessageHandler = method MyHandler *> subscribe to an event attach method MyHandler to MessageArrived *> raise the event invoke MessageArrived("Test message") *> unsubscribe from the event detach method MyHandler from MessageArrived *> Throws a null reference exception as there are no subscribers invoke MessageArrived("Test message 2") *> Safely raising an #event declare handler2 as type MessageHandler = MessageArrived if handler2 not equals null invoke handler1("Safe message") end-if end method. method-id MyHandler static (str as string). display str end method. end class. |
// Java has no concept of delegates or events. // Similar behavior is typically achieved by using // anonymous inner classes instead. |
Portions of these examples were produced by Dr. Frank McCown, Harding University Computer Science Dept, and are licensed under a Creative Commons License.