ABAP OO 的一些基本概念和语法

1. 类的基本知识
声明和实现类:

CLASS c1 DEFINITION.

ENDCLASS.

CLASS c1 IMPLEMENTATION

ENDCLASS.

可见性设置
PUBLIC SECTION.
PROTECTED SECTION.
PRIVATE SECTION.

实例变量和方法

DATA name TYPE string.

METHODS m1 IMPORTING msg TYPE string.

静态变量和方法

CLASS-DATA pi TYPE i.

CLASS-METHODS m3.

方法实现

METHOD m1.

ENDMETHOD.

构造函数

instance level: METHODS constructor.

class

level: CLASS-METHODS class_constructor.

2. 类的实例化和访问
创建实例

DATA v1 TYPE REF TO c1.

CREATE OBJECT v1.

类变量和方法访问
实例变量和方法:实例名称->变量/方法

v1->m1

静态变量和方法: 类名=>变量/方法

c1=>m3 or v1->m3
me的使用

Within the implementation of every instance method, an implicitly created local reference variable called me is available, which points to the instance in which the method is currently being executed.

3. 继承
定义:

CLASS c2 INHERITING FROM c1.

overload method,方法重载, only instance method can be redefined

METHODS m2 REDEFINITION.

调用基类的方法

super->method_name, 只能在重载的方法中使用,且method_name称必须是当前implementation的方法名

类型强制转换
DATA: my_object TYPE REF TO my_class,

object1 TYPE REF TO object.

my_object ?= object1.

4. 接口
定义

INTERFACE i_counter.

METHODS set_counter IMPORTING VALUE(set_value) TYPE I.

ENDINTERFACE.

实现
CLASS c_counter1 DEFINITION.

PUBLIC SECTION.

INTERFACES i_counter.

PRIVATE SECTION.

DATA count TYPE I.

ENDCLASS.

CLASS c_counter1 IMPLEMENTATION.

METHOD i_counter~set_counter.

count = set_value.

ENDMETHOD.

ENDCLASS.

调用接口
方法一:

data count1 TYPE REF TO c_counter1.

CREATE OBJECT count1.

count1->i_counter~set_counter( 5 ).

count1->display( ).

方法二:

data intf1 type REF TO i_counter.

intf1 = count1.

intf1->set_counter( 10 ).

count1->display( ).

5. 事件
定义事件:
CLASS c1 DEFINITION.
PUBLIC SECTION.

EVENTS e1.
ENDCLASS.

触发事件的语句:
RAISE EVENT e1.

定义事件响应:
CLASS c2 DEFINITION.
PUBLIC SECTION.

METHODS m2 FOR EVENT e1 of C1.
ENDCLASS.

注册事件:
DATA: v1 TYPE REF TO c1,

v3 TYPE REF TO c2.
CREATE OBJECT: v1, v3.

SET HANDLER v3->m2 FOR v1.

Comments are closed.