CLASS定义及实现
1.普通的class类调用
*类定义
CLASS application DEFINITION."定义的类名 application
PUBLIC SECTION.
METHODS:show_text."定义的方法名 show_text
PRIVATE SECTION.
DATA text(100) TYPE c VALUE 'This is my first ABAP Object.'.
ENDCLASS.
*类实现
CLASS application IMPLEMENTATION.
METHOD show_text."方法的实现
WRITE text.
ENDMETHOD.
ENDCLASS.
*第二个例子
*类定义
CLASS vehicle DEFINITION.
PUBLIC SECTION.
CLASS-DATA class_name(10) TYPE c VALUE 'Vehicle'.
METHODS:accelerate,"定义的方法 accelerate 和 show_speed
show_speed.
PROTECTED SECTION.
DATA speed TYPE i.
ENDCLASS.
CLASS vehicle IMPLEMENTATION."方法的实现
METHOD accelerate.
speed = speed + 1.
ENDMETHOD.
METHOD show_speed.
WRITE: / 'Speed:',speed.
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
*调用类中的方法
DATA ob_app TYPE REF TO application."重新生成新的类
CREATE OBJECT ob_app.
CALL METHOD ob_app->show_text."调用方法
*类调用
DATA obj_vehicle TYPE REF TO vehicle.
CREATE OBJECT obj_vehicle.
DO 10 TIMES.
CALL METHOD obj_vehicle->accelerate.
ENDDO.
CALL METHOD obj_vehicle->show_speed.
2.构造输入输出参数
CLASS circle DEFINITION.
PUBLIC SECTION.
METHODS get_area IMPORTING VALUE(i_radius) TYPE i
RETURNING VALUE(r_size) TYPE f.
PRIVATE SECTION.
* 定义静态变量
CONSTANTS pi TYPE f VALUE '3.14159265'.
ENDCLASS.
CLASS circle IMPLEMENTATION.
METHOD get_area.
r_size = i_radius ** 2 * pi.
ENDMETHOD.
ENDCLASS.
*弹出参数输入屏幕
PARAMETERS radius TYPE i.
DATA: o_circle TYPE REF TO circle,
area TYPE f.
START-OF-SELECTION.
CREATE OBJECT o_circle.
CALL METHOD o_circle->get_area
EXPORTING i_radius = radius
RECEIVING r_size = area.
WRITE: / area.
3.传递构造参数
CLASS vehicle DEFINITION.
PUBLIC SECTION.
METHODS: accelerate IMPORTING rate TYPE i,
* 定义构造函数,有一个输入参数
constructor IMPORTING i_speed TYPE i,
show_speed.
PRIVATE SECTION.
DATA speed TYPE i VALUE 0.
ENDCLASS.
CLASS vehicle IMPLEMENTATION.
METHOD accelerate.
speed = speed + rate.
ENDMETHOD.
METHOD show_speed.
WRITE: / speed.
ENDMETHOD.
METHOD constructor.
speed = i_speed.
ENDMETHOD.
ENDCLASS.
DATA o_vehicle TYPE REF TO vehicle.
START-OF-SELECTION.
* 这个构造函数传了参数进去
CREATE OBJECT o_vehicle EXPORTING i_speed = 4.
CALL METHOD o_vehicle->accelerate EXPORTING rate = 2.
CALL METHOD o_vehicle->accelerate EXPORTING rate = 2.
CALL METHOD o_vehicle->show_speed.