SAP ABAP - 多型性



術語“多型性”字面意思是“多種形式”。從面向物件的角度來看,多型性與繼承一起工作,使繼承樹中的各種型別可以互換使用。也就是說,當存在類層次結構並且它們透過繼承相關聯時,就會發生多型性。ABAP 多型性意味著對方法的呼叫將導致執行不同的方法,具體取決於呼叫該方法的物件型別。

以下程式包含一個抽象類“class_prgm”、2 個子類(class_procedural 和 class_OO)以及一個測試驅動程式類“class_type_approach”。在此實現中,類方法“start”允許我們顯示程式設計型別及其方法。如果您仔細檢視方法“start”的簽名,您會注意到它接收型別為 class_prgm 的匯入引數。但是,在 Start-Of-Selection 事件中,此方法已在執行時使用 class_procedural 和 class_OO 型別的物件被呼叫。

示例

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”中提供的未定義抽象實現。

廣告