Methods are internal procedures in a class that defines the behavior of an object. Methods can access all class attributes that allows to change the object data content.
Methods have a parameter interface that is used to supply values while calling methods and receive values back from methods.
The method definition can code with class definition and method implementation can code in class implementation.
The method implementation syntax is –
METHOD <method-name>.
...
Statements-block
...
ENDMETHOD.
Methods can declare by using the CALL METHOD statement. Method statements-block should code in between METHOD ENDMETHOD.
Methods are three types and those are –
Class Methods | Description |
---|---|
Instance Methods | Instance methods are very specific to instance. Instance methods can declare using the METHODS statement. Instance methods can access all the class attributes of a class and can trigger all the class events. |
Static Methods | Static methods can be declared using the CLASS-METHODS statement. Static methods can only access static attributes and trigger static events. |
Special Methods | There are some special methods based on their definition and usage. When we first call a method using CALL METHOD, there are two special methods constructor and class_constructor that are automatically called. |
Example –
Simple example to define, call instance and static methods.
Code –
*&---------------------------------------------------------------------*
*& Report Z_METHODS
*&---------------------------------------------------------------------*
*& Written by TutorialsCampus
*&---------------------------------------------------------------------*
REPORT Z_METHODS.
* Class & Methods Definition
CLASS classnew DEFINITION.
PUBLIC SECTION.
* Instance method definitions
METHODS instmethod.
*static method definition
CLASS-METHODS statmethod.
ENDCLASS.
* Class implementation
CLASS classnew IMPLEMENTATION.
* Instance method implementation
METHOD instmethod.
WRITE:/ 'Executing instance method'.
ENDMETHOD.
* Static method implementation
METHOD statmethod.
WRITE:/ 'Executing static method'.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
* Defining object objectnew for the class classnew
DATA: objectnew TYPE REF TO classnew.
* Creating object objectnew
CREATE OBJECT objectnew.
* Calling instance method, static method
CALL METHOD: objectnew->instmethod,
objectnew->statmethod.
Output –
Explaining Example –
In the above example, each and every statement is preceeded with a comment to explain about the statement. Go through them to get clear understanding of example code.
instmethod is instance method as it was defined by using METHODS clause. statmethod is static method as it was created by using CLASS-METHODS clause.