PARAMETER | INSTANCE VARIABLE | STATIC VARIABLE |
Access | The instance variable is accessed through the object of the class. An object must be created for the class in order to access the instance variable | The static variable is accessed through the class name. Object is not needed to access the variable value. |
Lifetime | Instance variables exists till the object exists. Once the object is destroyed,the instance variable is also destroyed | During the start of the program, the static variables are created. As soon as the program stops, the static variable is also destroyed |
Example | pr_object1->pv_inst_var = 10. Pv_inst_var is declared in public section. | zcl_static_instance=>static_variable = 20. |
value | Each object of the class holds their own value for the instance variable | There is only one static variable value for all the objects of the class. |
EXAMPLE: STATIC AND INSTANCE VARIABLE
CLASS zcl_static_instance DEFINITION.
PUBLIC SECTION.
METHODS set_instance_variable IMPORTING iv_instance_variable TYPE i.
METHODS get_instance_variable RETURNING VALUE(rv_instance_variable) TYPE i.
CLASS-DATA static_variable TYPE i.
PROTECTED SECTION.
PRIVATE SECTION.
DATA pv_instance_variable TYPE i.
ENDCLASS.
CLASS zcl_static_instance IMPLEMENTATION.
METHOD set_instance_variable.
Pv_instance_variable = iv_instance_variable.
ENDMETHOD.
METHOD get_instance_variable.
Rv_instance_variable = pv_instance_variable.
ENDMETHOD.
ENDCLASS.
REPORT 1.
DATA pr_object1 TYPE REF TO zcl_static_instance.
Pr_object1->set_instance_variable( iv_instance_variable = 10 ).
Lv_obj1_inst_val = pr_object1->get_instance_variable( ).
Zcl_static_instance=>static_variable = 10.
WRITE:/ ‘Object1 instance variable value:’, lv_obj1_inst_val.
WRITE:/ ‘Object1 static variable value:’, zcl_static_instance=>static_variable.
OUTPUT:
Object1 instance variable value: 10
Object1 static variable value: 10
REPORT 2.
DATA pr_object2 TYPE REF TO zcl_static_instance.
Pr_object2->set_instance_variable( iv_instance_value = 20 ).
Lv_obj2_inst_value = pr_object2->get_instance_variable( ).
Zcl_static_instance=>static_variable = 30.
WRITE:/ ‘Object2 instance variable value:’, lv_obj2_inst_value.
WRITE:/ ‘Object2 static value:’, zcl_static_instance=>static_variable.
OUTPUT:
Object2 instance variable value: 20
Object2 static value: 30