Preface – This post is part of the Object Oriented ABAP series.
Table of Contents
Introduction
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.
Definition
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.
EVENTS <event-name>….
- 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.
CLASS-EVENTS <event-name>….
Syntax
FOR EVENT <event-name> OF <class-name>.
Example
Lets’ pin down an example:
**** main class definition****
CLASS zcl_demo DEFINITION.
PUBLIC SECTION.
DATA : num1 TYPE I.
METHODS: compare IMPORTING num2 TYPE I.
EVENTS: event_compare.
ENDCLASS.
****event handler definition****
CLASS zcl_eventhandler DEFINITION.
PUBLIC SECTION.
METHODS: handling_compare FOR EVENT event_compare OF zcl_demo.
ENDCLASS.
****class implementation ****
CLASS zcl_demo IMPLEMENTATION.
METHOD compare.
num1 = num2.
If num1 > 10.
RAISE EVENT event_compare. “Raise an event
ENDIF.
ENDMETHOD.
ENDCLASS.
****event handler implementation ****
CLASS zcl_eventhandler IMPLEMENTATION.
METHOD handling_compare.
WRITE: “Event triggered… Num1 is greater than 10..”
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
****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
object_demo-> compare(2).
here importing parameter is 2. if its greater than 10 its trigger the event then only its display above output.
YES ABSOLUTELY!! IF NUM1 IS GREATER THAN 10, THE EVENT TRIGGERED OUTPUT IS DISPLAYED.. IF LESS THAN 10, EVENT WONT RAISE.