Table of Contents
Events in ABAP Class are the functions in a class which triggers the event handlers of other class based on the outcomes. With the use of events, any number of event handler methods can be called. The link between the triggering event and event handler is decided at run-time.
An event is the mechanism by which a method of one class can invoke the method of other class without instantiating that class.
Steps to add Events in ABAP Class
- Define an event
- Define a method
- Link event and method
- Create a triggering method to raise the event
- Define SET HANDLER statement at an instance in the program
Points to consider
- Event handler method is defined by FOR EVENT <event-name> OF <class-name>.
- It has only output parameters.
- To pass output parameters to the event handler method, RAISE EVENT statement is used.
- SET HANDLER method is used to link the event to its handler methods in a program.
Types of Events
Events are of two types:
- Instance events: Instance events can only get triggered in instance methods. It is declared using EVENTS statement.
- Static events: Static events are triggered by both instance and static methods. And also static methods can only trigger static events. It is declared using CLASS-EVENTS.
FOR EVENT <event-name> OF <class-name>.
Lets’ pin down an example:
**** main class definition****
CLASS zcl_demo DEFINITION.
DATA : num1 TYPE I.
METHODS: compare IMPORTING num2 TYPE I.
****event handler definition****
CLASS zcl_eventhandler DEFINITION.
METHODS: handling_compare FOR EVENT event_compare OF zcl_demo.
****class implementation ****
CLASS zcl_demo IMPLEMENTATION.
num1 = num2.
If num1 > 10.
RAISE EVENT event_compare. “Raise an event
****event handler implementation ****
CLASS zcl_eventhandler IMPLEMENTATION.
WRITE: “Event triggered… Num1 is greater than 10..”
****creating class object****
DATA : object_demo TYPE REF TO zcl_demo,
****creating event handleobject****
object_eventhandler TYPE REF To zcl_eventhandler.
CREATE OBJECT object_demo.
CREATE OBJECT object_eventhandler.
SET HANDLER object_eventhandler-> handling_compare FOR zcl_demo. “Setting up handler