例子
Report ZPolymorphism1.
CLASS class_prgm Definition Abstract.
PUBLIC Section.
Methods: prgm_type Abstract,
approach1 Abstract.
ENDCLASS.
CLASS class_procedural Definition
Inheriting From class_prgm.
PUBLIC Section.
Methods: prgm_type Redefinition,
approach1 Redefinition.
ENDCLASS.
CLASS class_procedural Implementation.
Method prgm_type.
Write: 'Procedural programming'.
EndMethod. Method approach1.
Write: 'top-down approach'.
EndMethod. ENDCLASS.
CLASS class_OO Definition
Inheriting From class_prgm.
PUBLIC Section.
Methods: prgm_type Redefinition,
approach1 Redefinition.
ENDCLASS.
CLASS class_OO Implementation.
Method prgm_type.
Write: 'Object oriented programming'.
EndMethod.
Method approach1.
Write: 'bottom-up approach'.
EndMethod.
ENDCLASS.
CLASS class_type_approach Definition.
PUBLIC Section.
CLASS-METHODS:
start Importing class1_prgm
Type Ref To class_prgm.
ENDCLASS.
CLASS class_type_approach IMPLEMENTATION.
Method start.
CALL Method class1_prgm→prgm_type.
Write: 'follows'.
CALL Method class1_prgm→approach1.
EndMethod.
ENDCLASS.
Start-Of-Selection.
Data: class_1 Type Ref To class_procedural,
class_2 Type Ref To class_OO.
Create Object class_1.
Create Object class_2.
CALL Method class_type_approach⇒start
Exporting
class1_prgm = class_1.
New-Line.
CALL Method class_type_approach⇒start
Exporting
class1_prgm = class_2.
上面的代码产生以下输出 -
Procedural programming follows top-down approach
Object oriented programming follows bottom-up approach
ABAP 运行时环境在导入参数 class1_prgm 的分配期间执行隐式缩小转换。此功能有助于通用地实现“start”方法。与对象引用变量关联的动态类型信息允许ABAP运行时环境将方法调用与对象引用变量指向的对象中定义的实现动态绑定。例如,“class_type_approach”类中方法“start”的导入参数“class1_prgm”引用了一个永远无法自行实例化的抽象类型。
每当使用具体子类实现(例如 class_procedural 或 class_OO)调用该方法时,class1_prgm 引用参数的动态类型就会绑定到这些具体类型之一。因此,对方法“prgm_type”和“approach1”的调用引用的是class_procedural或class_OO子类中提供的实现,而不是类“class_prgm”中提供的未定义的抽象实现。