SAP ABAP

abap object-oriented-简单的类的实现

2018-07-12  本文已影响7人  46b61a5f089d

这一节通过一个最简单的例子来介绍如何使用类,以及类的属性和方法。

先把背景介绍一下:
创建一个lcl_airplane类,通过方法set_attributes设置它的属性,通过display_attributes显示实例的属性,通过display_n_o_airplanes显示已经创建的实例的个数。

*----------------------------------------------------------------------*

* INCLUDE Z_SAMPLE_LCL_AIRPLANE *

*----------------------------------------------------------------------*

******************************************

* Definition part

******************************************

CLASS lcl_airplane DEFINITION.

*------------------------------

* Public section

*------------------------------

PUBLIC SECTION.

TYPES: t_name(25) TYPE c.

METHODS:

constructor, “初始化类

set_attributes IMPORTING p_name TYPE t_name

p_planetype TYPE saplane-planetype,

display_attributes,

display_n_o_airplanes.

*------------------------------

* Private section

*------------------------------

PRIVATE SECTION.

* Private attributes

DATA: name(25) TYPE c,

planetype TYPE saplane-planetype.

* Private static attribute

CLASS-DATA n_o_airplanes TYPE i.

ENDCLASS.

******************************************

* Implementation part

******************************************

CLASS lcl_airplane IMPLEMENTATION.

METHOD constructor.

* Counts number of instances

n_o_airplanes = n_o_airplanes + 1.

ENDMETHOD.

METHOD set_attributes.

name = p_name.

planetype = p_planetype.

ENDMETHOD.

METHOD display_attributes.

WRITE:/ 'Name:', name, 'Planetype:', planetype.

ENDMETHOD.

METHOD display_n_o_airplanes.

WRITE: / 'No. planes:', n_o_airplanes.

ENDMETHOD.

ENDCLASS.

---------------------------------------------------------------------------------------------

REPORT ZBOBO_OO_011 .

Include z_sample_lcl_airplane.

* Create reference to class lcl_airplane

DATA: airplane1 TYPE REF TO lcl_airplane,

airplane2 TYPE REF TO lcl_airplane.

START-OF-SELECTION.

* Create instance

CREATE OBJECT airplane1.

CALL METHOD: airplane1->display_n_o_airplanes.

CREATE OBJECT airplane2.

* Setting attributes using a method with parameters

CALL METHOD airplane1->set_attributes EXPORTING p_name = 'Kurt'

p_planetype = 'MD80'.

END-OF-SELECTION.

* Using methods

CALL METHOD: airplane1->display_n_o_airplanes,

airplane1->display_attributes.
上一篇下一篇

猜你喜欢

热点阅读