ABAP 100
Object-Oriented Programming with SAP NetWeaver
1
© msg systems ag, 15.01.2013
ABAP Programming
2
© msg systems ag, 15.01.2013
Level 3
ABAP Dictionary
ABAP030 2 Days
Development of user dialogs
ABAP110 2 Days
Level 1
ABAP Workbench
basics and
concepts
ABAP 010 3 Days
Level 1
Basics of
SAP Web AS
SAP Basics ½ Day
ABAP Objects
Object Oriented
Programming
with SAP NetWeaver
ABAP 100 3 Days
Table Controls &�ALV Grids
ABAP111 1 ½ Days
Agenda
3
© msg systems ag, 15.01.2013
1. Objectives and Introduction
4
© msg systems ag, 15.01.2013
1. Objectives and Introduction�ABAP Objects – Level 3
5
© msg systems ag, 15.01.2013
Advanced Business Application Programming
for
Object-Oriented Programming
ABAP Objects
1. Objectives and Introduction�Course Objectives
6
© msg systems ag, 15.01.2013
This course provides knowledge to:
1. Objectives and Introduction�Course Learning Objectives
7
© msg systems ag, 15.01.2013
You will acquire knowledge to:
1. Objectives and Introduction�Overview
8
© msg systems ag, 15.01.2013
????
A travel agency maintains business connections to business partners
2. Introduction to Object-Oriented Programming
9
© msg systems ag, 15.01.2013
2. Introduction to Object-Oriented Programming –�History of Selected Programming Languages
10
© msg systems ag, 15.01.2013
1950
1952
1954
1956
1958
1960
1962
1964
1966
1968
1970
1972
1974
1976
1978
1980
1982
1984
1986
1988
1990
1992
1994
1995
1996
1997
1998
Machine language
Assembler
C++
ABAP Objects
ABAP
Java
Fortran
LISP
Cobol
APL
APL2
Algol 60
Basic
Prolog
Logo
Simula 67
Algol 68
PL1
BCPL
Pascal
Smalltalk
Smalltalk-80
FP1
Ada
Modula-2
C
Object Pascal
Modula-3
Miranda
Eiffel
Eiffel-3
Oberon
Oberon-2
Ada-95
2. Introduction to Object-Oriented Programming
11
© msg systems ag, 15.01.2013
2. Introduction – Procedural Programming�Characteristics of Procedural Programming
12
© msg systems ag, 15.01.2013
Daten
Daten
Daten
Daten
Daten
Funktion
Funktion
Funktion
Funktion
Funktion
Funktion
Funktion
Funktion
2. Introduction – Procedural Programming�Typical Procedural ABAP Program
13
© msg systems ag, 15.01.2013
REPORT zabap_demo
* -----------------
TYPES: ...
DATA: ...
...
PERFORM f1 ...
CALL FUNCTION ...
...
* -----------------
FORM f1 ...
...
ENDFORM.
2. Introduction – Procedural Programming�Encapsulating Data Using Function Groups
14
© msg systems ag, 15.01.2013
Main program Function groups
Global data objects
Function group 1
Global data
Function module 1
Function group 2
Global data
Function module 2
Function module ...
Function module 1
Function module 2
Subroutines
Interface
Interface
2. Introduction – Procedural Programming�Example: Function Group Counter – Definition
15
© msg systems ag, 15.01.2013
FUNCTION-POOL counter.
DATA: count TYPE I.
FUNCTION SET_COUNTER.
* Local interface IMPORTING VALUE(set_value)
count = set_value
ENDFUNCTION.
FUNCTION INCREMENT_COUNTER.
ADD 1 TO count.
ENDFUNCTION.
FUNCTION GET_COUNTER.
* Local interface EXPORTING VALUE(get_value)
get_value = count.
ENDFUNCTION.
2. Introduction – Procedural Programming�Example: Function Group Counter – Usage
16
© msg systems ag, 15.01.2013
DATA: number TYPE I VALUE 3.
CALL FUNCTION 'SET_COUNTER'
EXPORTING set_value = number.
DO 4 TIMES.
CALL FUNCTION 'INCREMENT_COUNTER'.
ENDDO.
CALL FUNCTION 'GET_COUNTER'
IMPORTING get_value = number.
WRITE: ..., number, ...
2. Introduction – Procedural Programming�Several Counters
17
© msg systems ag, 15.01.2013
Function group COUNTER
SET_COUNTER
INCREMENT_COUNTER
GET_COUNTER
COUNTER
1 counter any number of counters
2. Introduction – Procedural Programming�Instantiation in object-oriented languages
18
© msg systems ag, 15.01.2013
Several instances�(Objects)�of the same Blueprint�(Type or better Class)�are a fundamental property of object-oriented languages.
ABAP Program with Data
External Session
Internal session of an ABAP program
n. Instance, Class 1
Schnitt-
stelle
Datea
1. Instance, Class 1
Interface
Data
n. Instance, Class m
Schnitt-
stelle
Datea
1. Instance, Class m
Interface
Data
2. Introduction to Object-Oriented Programming
19
© msg systems ag, 15.01.2013
2. Introduction – Object-Oriented Programming
20
© msg systems ag, 15.01.2013
Kran
Real world
Data and functions
Daten
Functions
Functions
Functions
Daten
Functions
Functions
Functions
Daten
Functions
Functions
Functions
Encapsulation of data and functions
Data
Data
Data
Data
Data
Functions
Functions
Functions
Functions
Functions
Functions
Functions
Functions
2. Introduction – Object-Oriented Programming�Characteristics of the Object-Oriented approach
21
© msg systems ag, 15.01.2013
Kran
Real world
2. Introduction – Object-Oriented Programming�Additional Concepts of the Object-Oriented Programming Model
22
© msg systems ag, 15.01.2013
Data
Functions
Functions
Father
Child 1
Child 2
Code 3
Code 2
display_data
Code 1
Code 4
2. Introduction – Object-Oriented Programming�Additional Concepts of the Object-Oriented Programming Model
23
© msg systems ag, 15.01.2013
myNumber
doCall
beCalled
register
Telephone
Telephone
myNumber
register
doCall
beCalled
2. Introduction – Object-Oriented Programming�Additional Concepts of the Object-Oriented Programming Model
24
© msg systems ag, 15.01.2013
CellPhone
mySMS
sendSMS
getSMS
Telephone
myNumber
register
doCall
beCalled
OfficePhone
myContacts
addContact
callContact
deleteContact
2. Introduction – Object-Oriented Programming�Additional Concepts of the Object-Oriented Programming Model
25
© msg systems ag, 15.01.2013
beCalled
beCalled
beCalled
MP3
2. Introduction – Object-Oriented Programming�Additional Concepts of the Object-Oriented Programming Model
26
© msg systems ag, 15.01.2013
register_me
msg
Phone
Center
2. Introduction – Object-Oriented Programming�Client/server behavior
27
© msg systems ag, 15.01.2013
CALL METHOD server->do_it
Server
Data
Methods
do_it
Data
Methods
call_it
Client
2. Introduction – Object-Oriented Programming�Compatibility and design goals
28
© msg systems ag, 15.01.2013
Compatibility:
Design goals:
* ABAP Objects Program
DATA: counter TYPE i,
wa TYPE kna1.
...
CLASS lcl_car DEFINITION.
...
ENDCLASS.
*--- main program ---------
CREATE OBJECT ...
counter = counter + 1.
MOVE wa TO ...
CLASS lcl_car DEFINITION.
...
ENDCLASS.
CREATE OBJECT ...
2. Introduction – Object-Oriented Programming�ABAP Main Memory and Encapsulation
29
© msg systems ag, 15.01.2013
Internal session
Internal session
Global data objects
Global data objects
Data
Functions
Modularization units
Data
Functions
2. Introduction – Object-Oriented Programming�The Software Development Process
30
© msg systems ag, 15.01.2013
Test
Implementation
(ABAP Objects)
Requirement,
Idea
Analysis and
Design
Iteration
Mentioned in the course!
2. Introduction – Object-Oriented Programming�Summary
31
© msg systems ag, 15.01.2013
You should now be able to:
3. Analysis and Design
32
© msg systems ag, 15.01.2013
3. Analysis and Design – Classification�Class creation / modeling
33
© msg systems ag, 15.01.2013
lcl_people
lcl_vehicle
Excerpt of the real world
3. Analysis and Design – Classification�Classes as Abstraction Forms
34
© msg systems ag, 15.01.2013
Scrap-merchant
Weight�weight
Make�make
Model� model
PS
HP
Doors�doors
Wheels�wheels
Scrap value�scrapvalue
Color�color
Configuration�configuration
Price�price
Car enthusiast
lcl_vehicle
- make
- ...
- weight
- scrapvalue
lcl_vehicle
- set
- ...
- price
- configuration
3. Analysis and Design – Classification�Classes and Objects
35
© msg systems ag, 15.01.2013
lcl_vehicle
…
…
or
or
Class:
Object (Instance):
lcl_vehicle
(5) lcl_vehicle
3. Analysis and Design
36
© msg systems ag, 15.01.2013
3. Analysis and Design – Modeling in UML
37
© msg systems ag, 15.01.2013
visualization, and documentation of models for software systems
Diagram types:
3. Analysis and Design – Classification�Class diagram in UML notation
38
© msg systems ag, 15.01.2013
Attributes
(Properties)
Methods
(Functions)
lcl_vehicle
make
model
.....
price
color
set_make()
display_attributes()
increases_speed()
…
Assoziationsme
Optional,
does not have to be specified
Events + Handlers
brake
accelerate
Class name
3. Analysis and Design – Modeling in UML�Example of a Class Diagram
39
© msg systems ag, 15.01.2013
lcl_car
lcl_rental
lcl_vehicle
lcl_bus
lcl_customer
1
0..*
0..*
1
1
1..*
1..*
1
lcl_wheel
lcl_truck
lcl_booking
3. Analysis and Design – Modeling in UML�Association
40
© msg systems ag, 15.01.2013
A customer can rent any amount of cars
Description of the association
Common cardinalities
* or 0..* any amount
1 exactly one
1..* at least one
0..1 no more than one
1
0..*
lcl_booking
lcl_customer
A booking refers to a single customer
◀books
3. Analysis and Design – Modelling with UML�Aggregation und Composition
41
© msg systems ag, 15.01.2013
Aggregation is a special�case of association,�a whole-part relationship.
Composition is a special�case of aggregation, an�existence-dependent�a whole-part relationship.
Composition Symbol
Aggregation Symbol
lcl_vehicle
lcl_booking
1..*
1..1
lcl_vehicle
lcl_wheel
1..1
0..*
3. Analysis and Design – Modelling with UML�Generalization and Specialization
42
© msg systems ag, 15.01.2013
or
Generalization
Specialization
Generalization
Specialization
lcl_truck
lcl_vehicle
lcl_car
lcl_vehicle
lcl_truck
lcl_car
Arrow for Inheritance
3. Analysis and Design – Modelling with UML�Sequence diagram: Example
43
© msg systems ag, 15.01.2013
Lifeline
of the object
Control focus
Return value
Create Object
Time
Process description
(optional)
Object :Class
Object :Class
1:Method(parameter)
3. Analysis and Design – Modelling with UML�Sequence diagram : Delegation
44
© msg systems ag, 15.01.2013
re_level = � fuel / fuel_max * 100.
re_level = � tank->get_fuel_level( ).
1: get_fuel_level( )
2: get_fuel_level( )
re_level
re_level
:lcl_car
:lcl_driver
:lcl_tank
3. Analysis and Design – Summary
45
© msg systems ag, 15.01.2013
You should now be able to
Exercise
46
© msg systems ag, 15.01.2013
Exercise
Analysis and Design
UML Class Diagrams
MIN
HOURS
4. Fundamentals of Object-Oriented Programming
47
© msg systems ag, 15.01.2013
4. Fundamentals of Object Oriented Programming�Example of a Class
48
© msg systems ag, 15.01.2013
Public access:
Private Access:
lcl_vehicle
Private
components
Methods:
Implementation
make
model
Public
components
set_make()
get_make()
4. Fundamentals of Object Oriented Programming�Defining Classes
49
© msg systems ag, 15.01.2013
CLASS lcl_periode DEFINITION.
ENDCLASS.
CLASS lcl_periode IMPLEMENTATION.
ENDCLASS.
ABAP-Coding
lcl_vehicle
Private
Components
Method
Implementation
Public
Components
4. Fundamentals of Object Oriented Programming�Attributes
50
© msg systems ag, 15.01.2013
(5) lcl_car
Private
make TYPE STRING,
...�� �r_motor � TYPE REF TO ...
Public
(5) lcl_rental
r_car
4. Fundamentals of Object Oriented Programming�Attributes, Types and Constants: Syntax
51
© msg systems ag, 15.01.2013
CLASS <Class_name> DEFINITION.
...
TYPES: <normal type_definition>.
CONSTANTS: mc_constant TYPE <Type> VALUE <Value>.
DATA: mv_var1 TYPE <Type>,
ms_var2 TYPE <DDIC-Type>,
mv_var3 LIKE mv_var1,
mv_var4 TYPE <Type> VALUE <value>,
mv_var5 TYPE <Type> READ-ONLY,
mo_var6 TYPE REF TO <Class>,
mo_var7 TYPE REF TO <Interface>.
CLASS-DATA: mv_only_once TYPE ... .
ENDCLASS.
TYPES:
CONSTANTS:
DATA:
CLASS-DATA:
4. Fundamentals of Object Oriented Programming�Attributes and Visibility
52
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
...
PRIVATE SECTION.
DATA: make TYPE string.
ENDCLASS.
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
DATA: make TYPE string.
PRIVATE SECTION.
ENDCLASS.
PUBLIC SECTION.
PRIVATE SECTION.
4. Fundamentals of Object Oriented Programming�Accessing Private Attributes
53
© msg systems ag, 15.01.2013
r_vehicle
Client
(5) lcl_vehicle
Private
make
Public
set_make()
get_make()
…
4. Fundamentals of Object Oriented Programming�Instance attributes and static attributes
54
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
...
PRIVATE SECTION.
DATA: make TYPE string,
...
CLASS-DATA: n_o_vehicles TYPE i.
ENDCLASS.
CLASS-DATA: n_o_vehicles TYPE i.
DATA: make TYPE string,
4. Fundamentals of Object Oriented Programming�Instance attributes and static attributes
55
© msg systems ag, 15.01.2013
Global data objects
Internal session
(2) lcl_vehicle
n_o_vehicles
Static attribute
(3) lcl_vehicle
...
3
r_vehicle1
r_vehicle3
r_vehicle2
(1) lcl_vehicle
...
Static attributes
exist only once
Instances /
objects
4. Fundamentals of Object Oriented Programming�Methods: Syntax
56
© msg systems ag, 15.01.2013
CLASS <Class_name> IMPLEMENTATION.
METHOD <Method_name>.
...
ENDMETHOD.
ENDCLASS.
CLASS <Class_name> DEFINITION.
...
METHODS:
<Method_name>
IMPORTING <im_par> TYPE <Type>
EXPORTING <ex_par> TYPE <Type>
CHANGING <ch_ar> TYPE <Type>
RETURNING value(<re_par>) TYPE <Type>
EXCEPTIONS <Exceptions (not class based)>� RAISING <class based exceptions>.
ENDCLASS.
Methods can
have a signature
The method implementation governs the ‚behavior‘ of the objects .
METHODS:
METHOD
ENDMETHOD.
4. Fundamentals of Object Oriented Programming�Accessing Private Methods
57
© msg systems ag, 15.01.2013
(5) lcl_vehicle
Private
make
...
init_make()
Public
...
set_make()
r_vehicle
Client
4. Fundamentals of Object Oriented Programming�Methods and Visibility
58
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS: set_make
IMPORTING im_make TYPE string.
PRIVATE SECTION.
METHODS: init_make.
DATA: make TYPE string.
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
METHOD init_make.
make = 'No make'.
ENDMETHOD.
METHOD set_make.
IF im_make IS INITIAL.
init_make( )
ELSE.
make = im_make.
ENDIF.
ENDMETHOD.
ENDCLASS.
init_make( )
PUBLIC SECTION.
PRIVATE SECTION.
4. Fundamentals of Object Oriented Programming�Instance methods and static methods
59
© msg systems ag, 15.01.2013
Rules
4. Fundamentals of Object Oriented Programming�Instance- and static methods: Example
60
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS: set_make IMPORTING im_make TYPE string.
CLASS-METHODS: get_count EXPORTING ex_count TYPE i.
PRIVATE SECTION.
DATA: make TYPE.
CLASS-DATA: n_o_count TYPE i.
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
...
METHOD get_count.
ex_count = n_o_count.
ENDMETHOD.
ENDCLASS.
CLASS-METHODS:
METHOD
ENDMETHOD.
4. Fundamentals of Object Oriented Programming�Summary and UML Notation
61
© msg systems ag, 15.01.2013
lcl_vehicle
- make:string
- model:string
- n_o_vehicles:i
…
+ set_make(im_make:string)
- init_make()
+ get_count():i
…
+ indicates public components
- indicates private components
_ static components are underlined
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS: set_make IMPORTING im_make TYPE string.
CLASS-METHODS: get_count EXPORTING ex_count TYPE i.
PRIVATE SECTION.
DATA: make TYPE.
CLASS-DATA: n_o_count TYPE i.
ENDCLASS.
Exercise
62
© msg systems ag, 15.01.2013
Exercise
OOP Fundamentals
Creating a class
MIN
HOURS
4. Fundamentals of Object-Oriented Programming
63
© msg systems ag, 15.01.2013
4. Fundamentals of Object-Oriented Programming�Creating objects
64
© msg systems ag, 15.01.2013
(5) lcl_vehicle
Private
make�modell�ser_no�...
Public
set_make
get_count
…
CREATE OBJECT r_vehicle
r_vehicle
Rules
lcl_vehicle
- make
- model
- ser_no
- n_o_vehicles …
+ set_make()
- init_make()
+ get_count()
…
4. Fundamentals of Object-Oriented Programming�Definition of Reference Variables
65
© msg systems ag, 15.01.2013
...
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
...
PRIVATE SECTION.
...
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
...
ENDCLASS.
DATA: r_vehicle1 TYPE REF TO lcl_vehicle,
r_vehicle2 TYPE REF TO lcl_vehicle.
START-OF_SELECTION.
...
r_vehicle1
r_vehicle2
?
?
What do these
reference variables
point to?
TYPE REF TO
TYPE REF TO
DATA:
4. Fundamentals of Object-Oriented Programming�Creating Objects
66
© msg systems ag, 15.01.2013
DATA: r_vehicle1 TYPE REF TO lcl_vehicle,
r_vehicle2 TYPE REF TO lcl_vehicle.
START-OF-SELECTION.
CREATE OBJECT r_vehicle1.
CREATE OBJECT r_vehicle2.
r_vehicle1
r_vehicle2
(4) lcl_vehicle
Private
Public
(3) lcl_vehicle
Private
Public
CREATE OBJECT
CREATE OBJECT
START-OF-SELECTION.
4. Fundamentals of Object-Oriented Programming�Garbage Collector
67
© msg systems ag, 15.01.2013
DATA: r_vehicle1 TYPE REF TO lcl_vehicle,
r_vehicle2 TYPE REF TO lcl_vehicle.
START-OF-SELECTION.
CREATE OBJECT r_vehicle1.
CREATE OBJECT r_vehicle2.
r_vehicle2 = r_vehicle2.
r_vehicle2
(4) lcl_vehicle
Private
Public
(3) lcl_vehicle
Private
Public
r_vehicle2 = r_vehicle2.
r_vehicle1
4. Fundamentals of Object-Oriented Programming�Garbage Collector: Approach
68
© msg systems ag, 15.01.2013
(5) lcl_object
CLEAR r_object
(4) lcl_object
(2) lcl_object
4. Fundamentals of Object-Oriented Programming�Reference Buffering
69
© msg systems ag, 15.01.2013
DATA: r_vehicle TYPE REF TO lcl_vehicle,
itab TYPE TABLE OF REF TO lcl_vehicle.
CREATE OBJECT r_vehicle.
APPEND r_vehicle TO itab.
CREATE OBJECT r_vehicle.
APPEND r_vehicle TO itab.
LOOP AT itab INTO r_vehicle.� " work with the current instance �ENDLOOP.
...
(2) lcl_object
(3) lcl_object
APPEND r_vehicle TO itab.
APPEND r_vehicle TO itab.
LOOP AT itab INTO r_vehicle.
ENDLOOP.
4. Fundamentals of Object-Oriented Programming�Aggregation Example
70
© msg systems ag, 15.01.2013
(2) lcl_wheel
(3) lcl_wheel
(4) lcl_wheel
(5) lcl_wheel
(5) lcl_vehicle
Private
Public
itab_wheels
Exercise
71
© msg systems ag, 15.01.2013
Exercise
OOP Fundamentals
Object instantiation
MIN
HOURS
4. Fundamentals of Object-Oriented Programming
72
© msg systems ag, 15.01.2013
4. Fundamentals of Object-Oriented Programming�Calling Methods
73
© msg systems ag, 15.01.2013
r_vehicle
(5) lcl_vehicle
Private
Public
motor_on()
r_vehicle->motor_on( )
Client
Reference
Object component selector
Method
4. Fundamentals of Object-Oriented Programming�EXPORTING and IMPORTING
74
© msg systems ag, 15.01.2013
Main program
Method
IMPORTING
im_distance
ex_fuel
EXPORTING
When creating a method:
Received values 🡺 IMPORTING
Returned values 🡺 EXPORTING
4. Fundamentals of Object-Oriented Programming�EXPORTING and IMPORTING
75
© msg systems ag, 15.01.2013
Main program
EXPORTING
CALL METHOD …
EXPORTING
im_distance = 500
IMPORTING
ex_fuel = lv_fuel.
IMPORTING
Method
IMPORTING
im_distance
ex_fuel
EXPORTING
When creating a method:
EXPORTING in the IMPORTING parameter
IMPORTING in the EXPORTING parameter
4. Fundamentals of Object-Oriented Programming�Calling Instance Methods: Syntax
76
© msg systems ag, 15.01.2013
Instance methods:
Shorter syntax:
(see online documentation)
CALL METHOD <InstRef>-><InstMethod>
EXPORTING <InpParam> = <Value>
IMPORTING <ExpParam> = <Variable>
CHANGING <ChgParam> = <Variable>
RECEIVING <ReturnVal> = <Variable>
EXCEPTIONS <Exception> = <Nr>.
<InstRef>-><InstMethod>( <Parameter> )
DATA: r_vehicle TYPE REF TO lcl_vehicle.
DATA: make_name TYPE string.
...
make_name = `the make of the car`.
CALL METHOD r_vehicle->set_make EXPORTING im_make = make_name.�* as of NW 6.1 keyword EXPORTING can be left out
r_vehicle->set_make( make_name )
* now getting something back from method...
r_vehicle->get_make( IMPORTING ex_make = make_name ).
CALL METHOD
->
r_vehicle->set_make
r_vehicle->get_make
->
SPACE!
No space before opening bracket
4. Fundamentals of Object-Oriented Programming�Calling Static Methods: Syntax
77
© msg systems ag, 15.01.2013
CALL METHOD <KlassenName>=><KlassenMethode>(
[Parameter] )
<KlassenName>=><KlassenMethode>( [Parameter] )
DATA: r_vehicle TYPE REF TO lcl_vehicle.
DATA: make_name TYPE string,
count TYPE i.
...
* get_count has one interface-parameter re_count
CALL METHOD lcl_vehicle=>get_count( IMPORTING re_count = count ).�
* other variant, since 6.1 available, see documentation
lcl_vehicle=>get_count( IMPORTING re_count = count ).
CALL METHOD
=>
=>
lcl_vehicle=>get_count
lcl_vehicle=>get_count
Static methods:
4. Fundamentals of Object-Oriented Programming�Functional Methods
78
© msg systems ag, 15.01.2013
a = b +
Functional Method
Example
4. Fundamentals of Object-Oriented Programming�Functional Methods: Example
79
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS: get_average_fuel� IMPORTING im_distance TYPE s_distance,
im_fuel TYPE ty_fuel � RETURNING value(re_fuel) TYPE ty_fuel,
ENDCLASS.
DATA: r_vehicle1 TYPE REF TO lcl_vehicle, � r_vehicle2 TYPE REF TO lcl_vehicle,
avg_fuel TYPE ty_fuel.
...�* example for short syntax in aritmeth. operation
avg_fuel =
r_vehicle1->get_average_fuel( im_distance = 500 im_fuel = 50 )� + r_vehicle2->get_average_fuel( im_distance = 600 im_fuel = 60 ).
RETURNING value(
)
4. Fundamentals of Object-Oriented Programming�Non-class-based exceptions: Example
80
© msg systems ag, 15.01.2013
CLASS lcl_plane DEFINITION.
PUBLIC SECTION.
METHODS: get_tank_capacity� RETURNING value(rv_tankcap) TYPE saplane-tankcap
EXCEPTIONS unknown_tank_capacity.
PRIVATE SECTION.
DATA: mv_planetype TYPE saplane-planetype.
ENDCLASS.
DATA: lo_plane TYPE REF TO lcl_plane, � lv_tankcap TYPE saplane-tankcap.
* usage of non-class-based exceptions
lo_plane->get_tank_capacity( RECEIVING rv_tankcap = lv_tankcap
EXCEPTIONS unknown_tank_capacity = 1
OTHERS = 2 ).
IF sy-subrc EQ 0.
"Normal operation.
ELSE.
"Exception handling.
ENDIF.
EXCEPTIONS unknown_tank_capacity
EXCEPTIONS unknown_tank_capacity = 1
OTHERS = 2
RAISE unknown_tank_capacity.
4. Fundamentals of Object Oriented Programming�External Access to Public Attributes
81
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
DATA: make TYPE string READ-ONLY. "just a demo
CLASS-DATA: n_o_vehicles TYPE i READ-ONLY. "just a demo
...
ENDCLASS.
...
DATA: r_vehicle TYPE REF TO lcl_vehicle.
DATA: make_name TYPE string,
count TYPE i.
START-OF-SELECTION.
*---------------------------------------
* main program, think of a client !
CREATE OBJECT r_vehicle.
make_name = r_vehicle->make. "only if public attr.�count = lcl_vehicle=>n_o_vehicles. "only if public attr.
(2) lcl_vehicle
make�...
r_vehicle
r_vehicle->make
lcl_vehicle=>n_o_vehicles
Exercise
82
© msg systems ag, 15.01.2013
Exercise
Fundamentals of OOP
Method Calls
MIN
HOURS
4. Fundamentals of Object Oriented Programming
83
© msg systems ag, 15.01.2013
4. Fundamentals of Object Oriented Programming�Constructor
84
© msg systems ag, 15.01.2013
lcl_vehicle
- make
- model
- n_o_vehicles
…
+ constructor()
…
CREATE OBJECT
METHODS:
constructor
IMPORTING <InpParam>� EXCEPTIONS <Exception>� RAISING <class-based exceptions>.
constructor
(3) lcl_vehicle
Private
Public
4. Fundamentals of Object Oriented Programming�Constructor: Example
85
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS constructor IMPORTING im_make TYPE string
im_modell TYPE string.
PRIVATE SECTION.
DATA: make TYPE string, weight TYPE p.
CLASS-DATA n_o_vehicles TYPE i.
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
METHOD constructor.
make = im_make.
modell = im_modell.
ADD 1 TO n_o_vehicles.
ENDMETHOD.
ENDCLASS.
DATA r_vehicle TYPE REF TO lcl_vehicles.
...
CREATE OBJECT r_vehicle� EXPORTING im_make = 'Ferrari'
im_modell = 'F40'.
Automatic call of constructor
Call from the main program
constructor
constructor
CREATE OBJECT
4. Fundamentals of Object Oriented Programming�Overview: Static Constructor
86
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
CLASS-METHODS: class_constructor.
PRIVATE SECTION.
CLASS-DATA: n_o_vehicles TYPE I.
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
METHOD class_constructor.
...
ENDMETHOD. ...
ENDCLASS.
CREATE OBJECT r_vehicle.
counter = lcl_vehicle=>n_o_vehicles. "if attribute is public
�lcl_vehicle=>get_count( IMPORTING re_count = counter ).
class_constructor
Implicit constructor call BEFORE
actual processing
CREATE OBJECT r_vehicle
counter = lcl_vehicle=>
lcl_vehicle=>get_count(
class_constructor
IMPORTING re_count = counter ).
n_o_vehicles. "if attribute is public
.
Exercise
87
© msg systems ag, 15.01.2013
Exercise
Fundamentals of OOP
Constructor
MIN
HOURS
4. Fundamentals of Object Oriented Programming
88
© msg systems ag, 15.01.2013
4. Fundamentals of Object Oriented Programming�Namespace inside a class
89
© msg systems ag, 15.01.2013
lcl_vehicle
Private
components
Attribute
make
Method
implementation
Public
components
Method
make
STOP
4. Fundamentals of Object Oriented Programming �The Reference Variable me
90
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS constructor
IMPORTING im_make TYPE string
im_modell TYPE string.
PRIVATE SECTION.
DATA make TYPE string. ...
ENDCLASS.
lcl_vehicle
Private
components
Attribute
mv_make
Method
implementation
me->make
Public
components
CLASS lcl_vehicle IMPLEMENTATION.
METHOD constructor.
DATA make TYPE string VALUE 'Benz'.
CONCATENATE im_make make
INTO me->make.
ENDMETHOD.
METHOD meth.
" inside class prefix 'me->' is not
" necessary for calling methods.
display_attributes( ).
ENDMETHOD.
ENDCLASS.
me->make
me->mv_make
4. Fundamentals of Object Oriented Programming �Summary
91
© msg systems ag, 15.01.2013
You should now be able to
Exercise
92
© msg systems ag, 15.01.2013
Exercise
Fundamentals of OOP
Calling a private method
MIN
HOURS
5. Inheritance
93
© msg systems ag, 15.01.2013
5. Inheritance�UML Example
94
© msg systems ag, 15.01.2013
„is a“
relationship
lcl_vehicle
- make
- model
- ser_no
- color
- n_o_vehicles …
+ constructor()
+ display_attributes()
+ get_count()
lcl_car
- car_type
- max_seats
- acceleration
+ …
+ get_type()
lcl_truck
- max_cargo
- n_o_tanks
- n_o_wheels
+ …
+ get_cargo()
lcl_bus
- max_passengers
- lavatory
- television
+ …
+ get_passengers()
5. Inheritance�Multiple Inheritance?
95
© msg systems ag, 15.01.2013
Specialization
Generalization
no
multiple inheritance!
lcl_super1
lcl_super2
lcl_sub1
lcl_sub2
lcl_sub3
STOP
5. Inheritance�Relationships between Super- and Subclasses
96
© msg systems ag, 15.01.2013
lcl_super
lcl_sub
new�components
Inherited�components
5. Inheritance�Syntax
97
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS: estimate_fuel
IMPORTING im_distance TYPE s_distance � RETURNING value(re_fuel) TYPE ty_fuel.
PRIVATE SECTION.
DATA: make TYPE string,
...
ENDCLASS.
CLASS lcl_truck DEFINITION
INHERITING FROM lcl_vehicle.
PUBLIC SECTION.
METHODS: get_cargo RETURNING VALUE(re_cargo) TYPE ty_cargo.
PRIVATE SECTION.
DATA: max_cargo TYPE ty_cargo.
...
ENDCLASS.
INHERITING FROM
5. Inheritance�Redefining Methods
98
© msg systems ag, 15.01.2013
CLASS lcl_truck IMPLEMENTATION.
METHOD estimate_fuel.
...
super->estimate_fuel(...) �
ENDMETHOD.
ENDCLASS.
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS: estimate_fuel
IMPORTING im_distance TYPE ty_distance � RETURNING value(re_fuel) TYPE ty_fuel.
ENDCLASS.
CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.
PUBLIC SECTION.
METHODS estimate_fuel REDEFINITION.� ...
ENDCLASS.
REDEFINITION
super
Signature must be retained!
New implementation of the inherited method
Refers to the superclass component
estimate_fuel
STOP
5. Inheritance�Inheritance and Redefinition of the constructor
99
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS: constructor IMPORTING
im_make TYPE string.
ENDCLASS.
CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.
PUBLIC SECTION.
METHODS: constructor IMPORTING im_make TYPE string
im_cargo TYPE ty_cargo.
PRIVATE SECTION.
DATA: max_cargo TYPE ty_cargo.
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
METHOD constructor.
make = im_make.
ENDMETHOD.
ENDCLASS.
CLASS lcl_truck IMPLEMENTATION.
METHOD constructor.
CALL METHOD super->constructor( im_make = im_make ).
max_cargo = im_cargo.
ENDMETHOD.
ENDCLASS.
Signature may be changed!
Call constructor of immediate superclass!
super->constructor
im_make TYPE string
im_make TYPE string
im_cargo TYPE ty_cargo
5. Inheritance�Rules for Calling the Constructor
100
© msg systems ag, 15.01.2013
DATA: r_2 TYPE REF TO lcl_2,
r_3 TYPE REF TO lcl_3.�
CREATE OBJECT r_2 EXPORTING im_1 = 100.
CREATE OBJECT r_3 EXPORTING im_1 = 100
im_2 = 1000.
Case 1�Class of instance to be created has constructor
Case 2 �Class of instance to be created has no constructor
lcl_1
a1:I
constructor( im_1:i )
lcl_3
a2:I
constructor( im_1:i� im_2:i )
lcl_2
has
has no
5. Inheritance�Inheritance and Visibility
101
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION. ...�
PROTECTED SECTION.� DATA tank TYPE REF TO lcl_tank.
PRIVATE SECTION.
DATA make TYPE string.
ENDCLASS.
PROTECTED SECTION
lcl_vehicle
- make
- model
# tank
…
+ constructor()
+ display_attributes()
+ get_count()
…
+ public
# protected
- private
static
# tank
5. Inheritance�Visibility of Protected Components
102
© msg systems ag, 15.01.2013
Addressable
for all clients
from the outside!
(5) lcl_bus
Private
Public
Protected
Inherited
tank
Geerbt
get_make()
set_make()�get_count()
display_attributes()�estimate_fuel()
Addressable
only inside the class
5. Inheritance�Rules for Redefinition of Methods
103
© msg systems ag, 15.01.2013
The method will be implemented in different ways!
lcl_vehicle
+ estimate_fuel()
lcl_car
+ estimate_fuel()
lcl_truck
+ estimate_fuel()
lcl_bus
+ estimate_fuel()
5. Inheritance�Redefinition for Methods: Example
104
© msg systems ag, 15.01.2013
lcl_truck
- max_cargo
…
+ constructor()
+ estimate_fuel()
lcl_bus
- max_passengers
…
+ constructor()
+ estimate_fuel()
METHOD estimate_fuel.
DATA: weight ...� weight = empty_load + max_cargo.
re_fuel = weight * im_distance
* factor.
ENDMETHOD.
METHOD estimate_fuel.
DATA: weight ...� weight = empty_load
+ max_passengers * average_weight.
re_fuel = weight * im_distance
* factor.
ENDMETHOD.
+ max_passengers * average_weight
+ max_cargo
5. Inheritance – Summary
105
© msg systems ag, 15.01.2013
You should now be able to
Exercise
106
© msg systems ag, 15.01.2013
Exercise
Inheritance
Class Hierarchies
MIN
HOURS
6. Casting
107
© msg systems ag, 15.01.2013
6. Casting�Types of Casts
108
© msg systems ag, 15.01.2013
lcl_vehicle
- make
- model
- ser_no
- color
- n_o_vehicles …
+ constructor()
+ display_attributes()
+ get_count()
lcl_car
- car_type
- max_seats
- acceleration
+ …
+ get_type()
lcl_truck
- max_cargo
- n_o_tanks
- n_o_wheels
+ …
+ get_cargo()
lcl_bus
- max_passengers
- lavatory
- television
+ …
+ get_passengers()
Upcast
Downcast
6. Casting�Upcast Principle
109
© msg systems ag, 15.01.2013
DATA: r_vehicle TYPE REF TO lcl_vehicle,� r_truck TYPE REF TO lcl_truck.
CREATE OBJECT r_truck.
* Upcast
r_vehicle = r_truck
r_truck
r_vehicle
r_vehicle
(5) lcl_truck
Public
Geerbt
get_make()
get_count()
Redefiniert
display_attributes()
set_attributes()
estimate_fuel()
get_cargo()
…
Inherited
get_make()
get_count()
Redefined
display_attributes()
set_attributes()
estimate_fuel()
r_vehicle = r_truck.
6. Casting�Compatibility und Upcast
110
© msg systems ag, 15.01.2013
DATA: r_vehicle TYPE REF TO lcl_vehicle,
r_truck TYPE REF TO lcl_truck,
level TYPE ty_level.
* Access via the subclass
level = r_truck->estimate_fuel( 1000 ).
* Upcast
r_vehicle = r_truck.
* Access via the superclass
level = r_vehicle->estimate_fuel( 1000 ).
=
->
r_vehicle
6. Casting�Generic Access?
111
© msg systems ag, 15.01.2013
lcl_rental
lcl_vehicles
lcl_truck
lcl_bus
(1) lcl_car
(5) lcl_truck
(4) lcl_bus
(2) lcl_car
1..*
1
Client
(1) lcl_rental
Private
itab
Public
?
6. Casting�Preparation for Generic Access (1)
112
© msg systems ag, 15.01.2013
(1) lcl_rental
Private
vehicle_list
Public
add_vehicle()
add_vehicle()
...
METHODS: add_vehicle
IMPORTING
im_vehicle TYPE REF TO lcl_vehicle.
...
Client
add_vehicle
(4) lcl_car
(3) lcl_truck
(2) lcl_bus
(5) lcl_car
Up Cast when
handing over!
6. Casting�Preparation for Generic Access(2)
113
© msg systems ag, 15.01.2013
CLASS lcl_rental IMPLEMENTATION.
METHOD add_vehicle.
APPEND im_vehicle TO vehicle_list.� ENDMETHOD.�
METHOD calc_estimated_fuel.� DATA:
r_vehicle TYPE REF TO lcl_vehicle.
re_fuel = 0.
LOOP AT vehicle_list
INTO r_vehicle.
re_fuel = re_fuel
+ r_vehicle->estimate_fuel(
im_distance ).� ENDLOOP.
ENDMETHOD.�ENDCLASS.
(2) lcl_bus
(4) lcl_truck
(3) lcl_bus
lcl_truck
estimate_fuel()
…
lcl_bus
estimate_fuel()
…
(5) lcl_truck
vehicle_list
6. Casting�Polymorphism – Generic Access
114
© msg systems ag, 15.01.2013
METHOD estimate_fuel.
total_weight = max_cargo + weight.
re_fuel = total_weight
* im_distance * factor.
ENDMETHOD.
estimate_fuel
METHOD estimate_fuel.� total_weight = max_passengers
* average_weight + weight.
re_fuel = total_weight � * im_distance * factor.
ENDMETHOD.
estimate_fuel
METHOD calc_estimated_fuel.� DATA: r_vehicle TYPE REF TO lcl_vehicle.� LOOP AT vehicle_list INTO r_vehicle.
ADD r_vehicle->estimate_fuel( im_distance ) TO re_fuel.
ENDLOOP.
ENDMETHOD.
vehicle_list
(5) lcl_truck
Public
Inherited/ redefined
…
estimate_fuel()
(2) lcl_bus
Public
Inherited / redefined
…
estimate_fuel()
r_vehicle->estimate_fuel
6. Casting�Static and dynamic Type of a Reference
115
© msg systems ag, 15.01.2013
DATA: r_vehicle TYPE
REF TO lcl_vehicle.
r_vehicle
(5) lcl_truck
Private
…
Public
IInherited / redefinied
estimate_fuel()
estimate_fuel()
(2) lcl_bus
Private
…
Public
Inherited / redefinied
estimate_fuel()
estimate_fuel()
6. Casting�Comparison to Procedural Programming
116
© msg systems ag, 15.01.2013
DATA: vehicle_list TYPE TABLE OF vehicle_list_type,
vehicle TYPE vehicle_list_type, ...
...
LOOP AT vehicle_list INTO vehicle.
CASE vehicle-category.
WHEN 'TRUCK'.
PERFORM estimate_fuel_truck ...
WHEN 'BUS'.
PERFORM estimate_fuel_bus ...
WHEN 'VAN'.
PERFORM estimate_fuel_van ...
ENDCASE.
ADD fuel TO needed_fuel.
ENDLOOP.
New vehicle category: truck
Procedural
Object Oriented
WHEN 'VAN'.
PERFORM estimate_fuel_van...
ADD r_vehicle->estimate_fuel( )
TO needed_fuel.
name category …
truck1
bus1
bus2
truck2
truck3
van1
vehicle_list
6. Casting
117
© msg systems ag, 15.01.2013
6. Casting�Motivation for Downcast
118
© msg systems ag, 15.01.2013
max_cargo
= 50
max_cargo� = 30
METHOD get_max_cargo.
DATA: r_vehicle TYPE REF TO lcl_vehicle.
LOOP AT vehicle_list INTO r_vehicle.
" Problem: is this really a truck?
" Determine the max cargo
ENDLOOP.�ENDMETHOD.
Client
Truck or other vehicle?
(2) lcl_bus
(3) lcl_truck
(4) lcl_car
(5) lcl_truck
(1) lcl_rental
Private
Public
get_max_cargo()
vehicle_list
6. Casting�Example for Downcast
119
© msg systems ag, 15.01.2013
(2) lcl_bus
(3) lcl_truck
(5) lcl_truck
(1) lcl_rental
Private
Public
get_max_cargo()
vehicle_list
METHOD get_max_cargo.
DATA: r_vehicle TYPE REF TO lcl_vehicle,� r_truck TYPE REF TO lcl_truck.
LOOP AT vehicle_list INTO r_vehicle.
TRY.
r_truck ?= r_vehicle.
" put max cargo in variable re_cargo... � CATCH cx_sy_move_cast_error.
" react on that cast error
ENDTRY.� ENDLOOP.
ENDMETHOD.
?=
cx_sy_move_cast_error
(4) lcl_car
max_cargo
= 50
max_cargo
= 30
Try and catch
possible errors.
✖
✔
✖
✔
6. Casting
120
© msg systems ag, 15.01.2013
6. Casting�Semantic and Use of Inheritance
121
© msg systems ag, 15.01.2013
Rules
6. Casting�Semantic and Use of Inheritance
122
© msg systems ag, 15.01.2013
Rules
car
car_red
car_blue
design ?
Superclass�“Rectangular”
Subclass�“square”
design ?
6. Casting – Summary
123
© msg systems ag, 15.01.2013
You should now be able to
Exercise
124
© msg systems ag, 15.01.2013
Exercise
Casting
Polymorphism (Part 1)
MIN
HOURS
Exercise
125
© msg systems ag, 15.01.2013
Exercise
Casting
Polymorphism (Part 2)
MIN
HOURS
7. Interfaces
126
© msg systems ag, 15.01.2013
7. Interfaces�Motivation for Interfaces
127
© msg systems ag, 15.01.2013
Shared components „Services“
lcl_airplane
lcl_vehicles
lcl_rental
Service 1�Service 2
Service 3
...
?
...
...
...
...
Interface
lcl_carrier
lcl_hotel
7. Interfaces�Services of the Interfaces
128
© msg systems ag, 15.01.2013
Shared components „Services“
lcl_airplane
lcl_vehicles
lcl_rental
display_partner
check_availability
...
...
...
...
...
lcl_carrier
lcl_hotel
Interface
lcl_travel_agency
describes and uses
7. Interfaces�UML Example
129
© msg systems ag, 15.01.2013
lcl_airplane
lcl_vehicles
lcl_rental
...
...
...
...
lcl_carrier
lcl_hotel
Implementation mehrerer Interfaces möglich!
lcl_travel_agency
«interface»
lif_partners
implements
Client
uses
Implementation of more than one Interface possible!
«interface»
lif_license
7. Interfaces�Definition and Implementation of an Interface
130
© msg systems ag, 15.01.2013
INTERFACE lif_partners.
METHODS: display_partner.
ENDINTERFACE.
CLASS lcl_rental DEFINITION.
PUBLIC SECTION.
INTERFACES lif_partners.
ENDCLASS.
CLASS lcl_rental IMPLEMENTATION.
METHOD lif_partners~display_partner .
"just call existing method that fits � display_attributes( ).
...
ENDMETHOD.
ENDCLASS.
Interface
resolution
operator
lif_partners
lif_partners
lif_partners~display_partner
7. Interfaces�Characteristics of Interfaces
131
© msg systems ag, 15.01.2013
super1
sub1
sub2
interf
Code 3
Code 2
display_partner
Code 1
Code 4
Exercise
132
© msg systems ag, 15.01.2013
Exercise
Interfaces
Definition of an Interface
MIN
HOURS
7. Interfaces
133
© msg systems ag, 15.01.2013
7. Interfaces�Working with Interface Components
134
© msg systems ag, 15.01.2013
CLASS lcl_rental IMPLEMENTATION.
...� METHOD lif_partners~display_partner.
"special coding to display partners or
"just calling existing method that fits � display_attributes( ).
ENDMETHOD.�
ENDCLASS.
DATA: r_rental TYPE REF TO lcl_rental.
...
�CREATE OBJECT r_rental.
* syntactically possible but not useful:
r_rental->lif_partners~display_partner( ).
implements
Interface resolution operator!
~
«interface»
lif_partners
display_partner()
check_availability()
…
lcl_rental
- name
- vehicle_list
…
+ add_vehicle()
+ display_attributes()
…
7. Interfaces�Upcast
135
© msg systems ag, 15.01.2013
DATA: r_rental TYPE REF TO lcl_rental,� r_lif TYPE REF TO lif_partners.
CREATE OBJECT r_rental.
* Up Cast
r_lif = r_rental
r_rental
r_lif
r_lif
(1) lcl_rental
Private
Öffentlich
Interface�components
display_partner
check_availability
...
lcl_carrier
lcl_rental
lcl_hotel
«interface»
lif_partners
Upcast
Downcast
7. Interfaces�Use of Interfaces
136
© msg systems ag, 15.01.2013
...
METHODS: add_partner IMPORTING im_partner TYPE REF TO lif_partner.
...
add_partner
(7) lcl_hotel
(1) lcl_rental
(6) lcl_carrier
(9) lcl_travel_agency
Private
Public
add_partner()
add_partner()
partner_list
lif_partner
Up Cast at
handing over!
7. Interfaces�Use of Interfaces
137
© msg systems ag, 15.01.2013
METHOD ...~display_partner.
display_attributes( ). ...
ENDMETHOD.
partner_list
METHOD ...~display_partner . � display_hotel_attributes( ). ... �ENDMETHOD.
METHOD ...~display_partner .
display_rental_data( ). ...
ENDMETHOD.
display_partner
display_partner
display_partner
METHOD display_agency_partners.� DATA: r_partner TYPE REF TO lif_partners. � LOOP AT partner_list INTO r_partner.
r_partner->display_partner( ).
ENDLOOP.
ENDMETHOD.
(6) lcl_carrier
(1) lcl_rental
(7) lcl_hotel
7. Interfaces�Interface References: Down Cast
138
© msg systems ag, 15.01.2013
(7) lcl_hotel
(1) lcl_rental
(6) lcl_carrier
(3) lcl_travel_agency
book_flight()
partner_list
METHOD book_flight.
DATA: r_carrier TYPE REF TO lcl_carrier,� r_partner TYPE REF TO lcl_partner.
LOOP AT partner_list INTO r_partner.
TRY.
r_carrier ?= r_partner.
r_carrier->... "Perform necessary operations.
CATCH cx_sy_move_cast_error.� "react on that cast error
ENDTRY.� ENDLOOP.
ENDMETHOD.
r_carrier
✖
✖
✔
?=
cx_sy_move_cast_error
7. Interfaces
139
© msg systems ag, 15.01.2013
7. Interfaces –�Compound Interfaces
140
© msg systems ag, 15.01.2013
Problem:�Extension of the Interface?
lcl_rental
lcl_hotel
lcl_carrier
«interface»
lif_partners
implements
book_room()
?
7. Interfaces –�Compound Interfaces
141
© msg systems ag, 15.01.2013
«interface»
lif_room_booking
lcl_rental
lcl_hotel
lcl_carrier
«interface»
lif_partners
implements
Solution:�Compound Interfaces
implements
interfaces:
7. Interfaces – �Compound Interfaces: Example
142
© msg systems ag, 15.01.2013
INTERFACE lif_partners.
METHODS display_partner.
ENDINTERFACE.
INTERFACE lif_room_booking.
INTERFACES lif_partners.
METHODS book_room.
ENDINTERFACE.
CLASS lcl_hotel DEFINITION.
PUBLIC SECTION.
INTERFACES lif_room_booking.
ENDCLASS.
CLASS lcl_hotel IMPLEMENTATION.
METHOD lif_partner~display_partner.
ENDMETHOD.
METHOD lif_room_booking~book_room.
ENDMETHOD.
ENDCLASS.
DATA: i_partner TYPE REF TO lif_partners,
i_room_book TYPE REF TO lif_room_booking,
...
i_partner = i_room_book. "Narrowing Cast
i_room_book->lif_partner~display_partner( ).
* i_partner->display_partner( ) also possible
i_room_book ?= i_partner. "Widening Cast
INTERFACES
7. Interfaces – Summary
143
© msg systems ag, 15.01.2013
You should now be able to
Exercise
144
© msg systems ag, 15.01.2013
Exercise
Interfaces
Use of Interfaces
MIN
HOURS
8. Events
145
© msg systems ag, 15.01.2013
8. Events – Overview
146
© msg systems ag, 15.01.2013
Recipient / Handler
* main program
CREATE OBJECT r_car EXPORTING …
Car rental company
Auto
Registration office
...
Sender
Event: vehicle_created
8. Events –�Properties
147
© msg systems ag, 15.01.2013
Sender is not aware of the receiver;�the reaction of the receiver is of no interest for the sender.
8. Events –�Triggering and Handling Events: Overview
148
© msg systems ag, 15.01.2013
Class defines an event� (EVENTS, CLASS-EVENTS)
Object or class triggers the event� (RAISE EVENT)�
Handler class defines and implements the handler method� ([CLASS-]METHODS... FOR EVENT ... OF ...)
„Handler object” or handler class is registered to events of specific objects/ classes at runtime� (SET HANDLER)
Rules
1
2
3
4
8. Events – �Defining and Triggering Events: Syntax
149
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS constructor IMPORTING ... .
EVENTS vehicle_created.
...
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
METHOD constructor.
...
RAISE EVENT vehicle_created
ENDMETHOD.
ENDCLASS.
CLASS <classname> IMPLEMENTATION.
METHOD <methodname>.
RAISE EVENT <event> EXPORTING <ex_par> = <act_par>.
car
RAISE EVENT
EVENTS
1.
RAISE EVENT
2.
vehicle_created
CLASS <classname> DEFINITION.
EVENTS: <event> EXPORTING VALUE(<ex_par>) TYPE <type>.
EVENTS
VALUE(
)
Typing of all parameters
8. Events – �Event handling and registering
150
© msg systems ag, 15.01.2013
Interested in this event?
carrier
registration
office
rental
car1
car2
truck
Sender
Handler
vehicle_created
vehicle_created
vehicle_created
8. Events –�Handling method
151
© msg systems ag, 15.01.2013
rental
add_vehicle
CLASS <class_handle> DEFINITION.
METHODS: <on_event> FOR EVENT <event>
OF <class/interfacename>
IMPORTING <ex_par1> ... <ex_parN> SENDER.
CLASS lcl_rental DEFINITION.
...
PRIVATE SECTION.
METHODS: add_vehicle FOR EVENT vehicle_created OF lcl_vehicle
IMPORTING SENDER.
ENDCLASS.
car1
3.
METHODS
FOR EVENT
OF
IMPORTING
SENDER
add_vehicle
OF
IMPORTING SENDER
vehicle_created
No Typing, only enumeration
8. Events –�Registering Event Handling: Syntax
152
© msg systems ag, 15.01.2013
CLASS lcl_rental IMPLEMENTATION.
METHOD constructor.
SET HANDLER add_vehicle FOR ALL INSTANCES. � ENDMETHOD.
METHOD ...
ENDCLASS.
SET HANDLER <ref_handle>-><on_event>
FOR <ref_sender> | FOR ALL INSTANCES
[ACTIVATION <var>].
CLASS lcl_rental DEFINITION.
...
PRIVATE SECTION.
METHODS: add_vehicle FOR EVENT vehicle_created OF ...
ENDCLASS.
rental
add_vehicle
car1
add_vehicle
SET HANDLER add_vehicle FOR ALL INSTANCES
4.
vehicle_created
8. Events –�Registration/Deregistration: Handler Tables
153
© msg systems ag, 15.01.2013
registration
office
Handler table of car2
car2
r_car
registration
office
Handler table of car1
car1
r_car
rental
vehicle_created (Event)
handling registered
method object
add_vehicle
reg_vehicle
vehicle_created (Event)
handling registered
method object
add_vehicle
reg_vehicle
8. Events –�Event Handling: Properties
154
© msg systems ag, 15.01.2013
A handler method can have even though only the same or a more restrictive visibility than the event related to it.
Event Handler
Public Private ✖
Private Public ✔
8. Events –�Summary
155
© msg systems ag, 15.01.2013
You should now be able to
Exercise
156
© msg systems ag, 15.01.2013
Exercise
Event Triggering
and Handling
MIN
HOURS
9. Global Classes/Interfaces
157
© msg systems ag, 15.01.2013
9. Global Classes/Interfaces�Rewind: Local Classes/Interfaces
158
© msg systems ag, 15.01.2013
REPORT prog1.
CLASS lcl_airplane DEFINITION.
...
ENDCLASS.
...
REPORT prog2.
DATA: r_airplane
TYPE REF TO lcl_airplane.
...
Local Program Classes
Program-1
Program-2
lcl_airplane
lcl_airplane
9. Global Classes/Interfaces
159
© msg systems ag, 15.01.2013
9. Global Classes/Interfaces�Global Classes in SE80 – Created in the Object Navigator
160
© msg systems ag, 15.01.2013
Creation of a Class using the
Object Navigator:
9. Global Classes/Interfaces�Class Builder: Attributes
161
© msg systems ag, 15.01.2013
Defining the attributes of a class
9. Global Classes/Interfaces�Class Builder: Methods
162
© msg systems ag, 15.01.2013
Defining methods of a class
Set the
signature parameter of the
selected method,
Here: CONSTRUCTOR
Redefinition�Undo Redefinition
9. Global Classes/Interfaces�Class Builder: Definition of Method Signatures
163
© msg systems ag, 15.01.2013
Set the
signature parameter
Back to method list
9. Global Classes/Interfaces�Class Builder: Exception Interface
164
© msg systems ag, 15.01.2013
Set the
possible exceptions
Back to method list
9. Global Classes/Interfaces�Class Builder: Defining Interfaces
165
© msg systems ag, 15.01.2013
1) Declaring the global interfaces in a global class
2) Implementation of methods from a global class
9. Global Classes/Interfaces�Class Builder: Implementation of Methods
166
© msg systems ag, 15.01.2013
Signature displayed to help with the implementation of the method
9. Global Classes/Interfaces�Class Builder: Inheritance
167
© msg systems ag, 15.01.2013
Make superclass known
9. Global Classes/Interfaces�Class Builder: Testing Environment
168
© msg systems ag, 15.01.2013
Test class
Create instance
Call methods
9. Global Classes/Interfaces
169
© msg systems ag, 15.01.2013
9. Global Classes/Interfaces�Global Classes in the Object Navigator
170
© msg systems ag, 15.01.2013
Left: Navigation Tree
Right: Editing an ABAP Program in the Editor
9. Global Classes/Interfaces�Class Builder: CREATE OBJECT
171
© msg systems ag, 15.01.2013
Representation of a class in the Navigation Tree enables the access to the class components
Drag&Drop of the constructor or the class name, generates CREATE OBJECT.
9. Global Classes/Interfaces�Class Builder: CALL METHOD
172
© msg systems ag, 15.01.2013
Drag&Drop of a method generates a method call.
9. Global Classes/Interfaces
173
© msg systems ag, 15.01.2013
9. Global Classes/Interfaces�The ALV Grid Control
174
© msg systems ag, 15.01.2013
Details
Sort
Search
Filter
Sum
CL_GUI_ALV_GRID
Views�(Table, Grid, Excel)
Export
Chart
9. Global Classes/Interfaces�Integrating a Grid-Control instance in a dialog program
175
© msg systems ag, 15.01.2013
Dynpro
Area
Custom
Container
Control
ALV
Grid
Control
For using the ALV Grid Control, two classes are needed.
(1) cl_gui_custom_container
Private
Public
(3) cl_gui_alv_grid
Private
Public
9. Global Classes/Interfaces�Displaying data in an ALV-Grid
176
© msg systems ag, 15.01.2013
...
DATA: go_container TYPE REF TO cl_gui_custom_container,
go_grid TYPE REF TO cl_gui_alv_grid .
...
CREATE OBJECT go_container
EXPORTING container_name = 'CONTAINER_1'
...
CREATE OBJECT go_grid
EXPORTING i_parent = go_container
...
go_grid->set_table_for_first_display(
i_structure_name = 'SPFLI'
it_outtab = gt_flights).
...
(1) cl_gui_alv_grid
Private
Public
(1) cl_gui_custom...
Private
Public
cl_gui_custom_container
cl_gui_alv_grid
set_table_for_first_display
9. Global Classes/Interfaces�Summary
177
© msg systems ag, 15.01.2013
You should now be able to:
Exercise
178
© msg systems ag, 15.01.2013
Exercise
Global Classes
Creating a Class
MIN
HOURS
10. Programming Techniques
179
© msg systems ag, 15.01.2013
10. Programming Techniques�Abstract Classes
180
© msg systems ag, 15.01.2013
CLASS lcl_vehicle DEFINITION ABSTRACT.
PUBLIC SECTION.
METHODS:
estimate_fuel_consumption ABSTRACT� IMPORTING ...
ENDCLASS.
References to such abstract classes can therefore be used for polymorphic
access to subclass instances.
They have to be redefined in the subclasses
Class cannot be instantiated
Method is not implemented in this class
ABSTRACT
ABSTRACT
10. Programming Techniques�Final Classes – Final Methods
181
© msg systems ag, 15.01.2013
CLASS lcl_truck DEFINITION FINAL
INHERITING FROM lcl_vehicle.
...
ENDCLASS.
CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle.
PUBLIC SECTION.
METHODS:
estimate_number_of_free_seats FINAL.
ENDCLASS.
FINAL
FINAL
lcl_bus
lcl_vehicle
lcl_truck
...
...
...
10. Programming Techniques
182
© msg systems ag, 15.01.2013
10. Programming Techniques�Issue with multiple instantiation
183
© msg systems ag, 15.01.2013
(1) lcl_daten
Private
Public
Function 1
Function 2
Function 3
Function 4
Change
(2) lcl_daten
Private
Public
Change
STOP
10. Programming Techniques�Who can instantiate classes?
184
© msg systems ag, 15.01.2013
Client
(1) lcl_singleton
Private
Public
get_instance
mo_singl
10. Programming Techniques�Singleton
185
© msg systems ag, 15.01.2013
Two possibilities to develop a Singleton:�
�
METHOD get_instance.
IF mo_single IS INITIAL.
CREATE OBJECT mo_single.
ENDIF.
ro_single = mo_single.
ENDMETHOD.
lcl_singleton
- mo_single:lcl_singleton
+ get_instance():lcl_singleton
METHOD class_constructor.
CREATE OBJECT mo_single.
ENDMETHOD.
METHOD get_instance.
ro_single = mo_single.
ENDMETHOD.
lcl_singleton
- mo_single:lcl_singleton
+ get_instance():lcl_singleton
+ class_constructor()
Exercise
186
© msg systems ag, 15.01.2013
Exercise
Programming Techniques
Singleton
MIN
HOURS
10. Programming Techniques
187
© msg systems ag, 15.01.2013
10. Programming Techniques�ABAP-Strings
188
© msg systems ag, 15.01.2013
DATA: lv_str TYPE c LENGTH 20.
lv_str = 'Hello World!'.
" Truncated (not wide enough!)
CONCATENATE lv_str lv_str
INTO lv_str.
" Syntax error (not wide enough!)
lv_str = lv_str+10(15).
" Ugly: * no localization,
" * space before '.',
" * lengthy, error-prone.
lv_str = sy-datum.
CONCATENATE
'Today is ' lv_str '.'
INTO lv_str
SEPARATED BY space.
CALL METHOD lo->meth( lv_str ).
DATA: lv_str TYPE string.
lv_str = `Hello World!`.
" No truncation
lv_str = lv_str && lv_str.
" No syntax- but runtime error
lv_str = lv_str+10(15).
" Pretty: * localization,
" * space before '.',
" * short,
" * directly usable
" in method call
CALL METHOD lo_meth(
|Today is { sy-datum
DATE = USER }.| ).
!'.
!`.
10. Programming Techniques
189
© msg systems ag, 15.01.2013
10. Programming Techniques�Friendship
190
© msg systems ag, 15.01.2013
Package
Friend
Grants friendship
(4) lcl_flight_planer
Public
plan_flight()
schedule()
(3) lcl_flight_factory
Public
create_flight()�get_flight()
delete_flight()
Friend
(5) lcl_flight_data
Private
flight_list
10. Programming Techniques
191
© msg systems ag, 15.01.2013
10. Programming Techniques�Persistence Services
192
© msg systems ag, 15.01.2013
Database
ABAP Program
Persistence Service
Transient Objects
Persistent data in transparent tables
Read / write objects
10. Programming Techniques�Characteristics of Persistence Services
193
© msg systems ag, 15.01.2013
10. Programming Techniques�The Class Agent
194
© msg systems ag, 15.01.2013
...
DATA: r_carrier TYPE REF TO cl_carrier,
r_agent TYPE REF TO ca_carrier,
carrname TYPE s_carrname.
TRY.
r_agent = ca_carrier=>agent.
r_carrier = r_agent->get_persistent( i_carrid = 'LH' ).
carrname = r_carrier->get_carrname( ).
WRITE: 'LH: ', carrname.
CATCH cx_os_object_not_found.
ENDTRY.
The agent (actor), a singleton of the class CA_CARRIER and friend of the persistent classCL_CARRIER
agent
10. Programming Techniques�Summary
195
© msg systems ag, 15.01.2013
You should now be able to
Exercise
196
© msg systems ag, 15.01.2013
Exercise
Programming Techniques
Friendship
MIN
HOURS
11. Exception Handling
197
© msg systems ag, 15.01.2013
11. Exception Handling�Class-Based Exceptions – Sequence Diagram
198
© msg systems ag, 15.01.2013
get_fuel_level( )
get_fuel_level( )
re_level
re_level
:lcl_car
:lcl_tank
«exception»
sensor_failed
alert( )
break
[Fill level sensor failed ]
:lcl_driver
11. Exception Handling�Class-Based Exceptions – Sequence Diagram (Propagation)
199
© msg systems ag, 15.01.2013
get_fuel_level( )
get_fuel_level( )
re_level
re_level
:lcl_car
:lcl_tank
«exception»
sensor_failed
pit_stop( )
break
[Fill level sensor failed ]
:lcl_driver
11. Exception Handling�Class-Based Exceptions – Overview
200
© msg systems ag, 15.01.2013
Exception class (predefined or your own)
...
RAISE EXCEPTION TYPE cx_exception
[EXPORTING attr1 = ...
attr2 = ...].
...
* Exception handling
...
ABAP Runtime System
Exception raised using the ABAP statement or by the runtime environment
zcx_exception
…
…
ABAP Program
11. Exception Handling�Handling Exceptions
201
© msg systems ag, 15.01.2013
TRY.
" Perform normal operation
...
CATCH cx_... cx_... ... [INTO lx_exc1].
...
CATCH cx_... ... [INTO lx_exc2].
...
CATCH cx_root [INTO lx_root].
...
CLEANUP.
...
ENDTRY.
Statements for which exceptions are to be handled
Behandler für die angegebenen Ausnahmeklassen und deren Unterklassen
Clean up, if there is no exception handler available
Handlers for the specified exception classes and their subclasses
Handlers for all exception objects of other classes
11. Exception Handling�Exception Classes: The Inheritance Hierarchy
202
© msg systems ag, 15.01.2013
cx_static_check
cx_dynamic_check
cx_no_check
cx_sy_move_cast_error
cx_sy_arithmetic_error
cx_sy_arithmetic_overflow
cx_root
- textid
- kernel_errid
...
+ get_text()
+ get_source_position()
11. Exception Handling�Example: Handling a Predefined Exception
203
© msg systems ag, 15.01.2013
PARAMETERS: int1 TYPE i,
int2 TYPE i.
DATA: result TYPE i,
lx_exc TYPE REF TO cx_root.
...
TRY.
result = int1 * int2.
WRITE result.
CATCH cx_sy_arithmetic_overflow INTO lx_exc.
MESSAGE lx_exc TYPE 'I' DISPLAY LIKE 'E'.
ENDTRY.
...
If an overflow error occurs, the runtime system raises the cx_sy_arithmetic_overflow exception
11. Exception Handling�Example: Using your own exceptions
204
© msg systems ag, 15.01.2013
CLASS lcl_airplane IMPLEMENTATION.
...
METHOD get_technical_attributes.
SELECT SINGLE weight tankcap FROM saplane
INTO (ex_weight, ex_tankcap)
WHERE planetype = im_type.
IF sy-subrc <> 0.
ex_weight = 100000.
ex_tankcap = 10000.
ENDIF.
ENDMETHOD.
...
ENDCLASS.
CLASS lcl_airplane DEFINITION.
...
METHODS get_technical_attributes
IMPORTING im_type TYPE saplane-planetype
EXPORTING ex_weight TYPE s_plan_wei
ex_tankcap TYPE s_capacity.
...
ENDCLASS.
Program adaptation: If there are no table entries ⇒ raise and handle own exception
11. Exception Handling�Creating Exception Classes
205
© msg systems ag, 15.01.2013
11. Exception Handling�Define your own Attributes and Exception Texts
206
© msg systems ag, 15.01.2013
Exception texts describe exception in more detail
Your own attributes provide additional information
11. Exception Handling�Raising and Handling selfdefined exceptions
207
© msg systems ag, 15.01.2013
METHOD get_technical_attributes.
DATA: lx_exc TYPE REF TO cx_root,
text TYPE string.
TRY.
SELECT SINGLE weight tankcap FROM saplane
INTO (ex_weight, ex_tankcap)
WHERE planetype = im_type.
IF sy-subrc <> 0.
RAISE EXCEPTION TYPE zcx_wrong_planetype
EXPORTING planetype = im_type.
ENDIF.
" Operate on valid values
" in ex_weight and ex_tankcap
CATCH zcx_wrong_planetype INTO lx_exc.
text = lx_exc->get_text( ).
MESSAGE text TYPE 'I'.
ENDTRY.
ENDMETHOD.
Example:
im_type = 727-301
11. Exception Handling�Propagating Exceptions
208
© msg systems ag, 15.01.2013
CLASS class IMPLEMENTATION.
...
METHOD meth.� ...� RAISE EXCEPTION TYPE cx_exception.� ENDMETHOD.
ENDCLASS.
CLASS class DEFINITION.
...
METHODS meth IMPORTING <im_parameter>
EXPORTING <ex_parameter>
RAISING cx_exception.
...
ENDCLASS.
REPORT propagate_exceptions.
...
DATA r_obj TYPE REF TO class.
...
TRY.
r_obj->meth( EXPORTING ...
IMPORTING ... ).
CATCH cx_exception .
...
ENDTRY.
②
①
RAISING cx_exception
RAISE EXCEPTION TYPE cx_exception
CATCH cx_exception
11. Exception Handling�Taking up exceptions in the method signature
209
© msg systems ag, 15.01.2013
11. Exception Handling�Resumable Exceptions – Sequence Diagram
210
© msg systems ag, 15.01.2013
get_fuel_level( )
get_fuel_level( )
re_level
:lcl_car
:lcl_driver
:lcl_tank
«resumable_exception»
sensor_failed
RESUME ...
re_level
break
[ Fill level sensor failed ]
11. Exception Handling�Example: Propagating Exceptions
211
© msg systems ag, 15.01.2013
METHOD get_technical_attributes.
SELECT SINGLE weight tankcap
FROM saplane
INTO (ex_weight, ex_tankcap)
WHERE planetype = im_type.
IF sy-subrc <> 0.
RAISE EXCEPTION
TYPE zcx_wrong_planetype
EXPORTING pl_type = im_type.
ENDIF.
ENDMETHOD.
CLASS lcl_airplane DEFINITION.
METHODS display_attributes.
METHODS get_technical_attributes
IMPORTING im_type TYPE saplane-planetype
EXPORTING ex_weight TYPE s_plan_wei
ex_tankcap TYPE s_capacity
RAISING zcx_wrong_planetype .
ENDCLASS.
METHOD display_attributes.
DATA: lx_exc TYPE REF TO cx_root,
text TYPE string.
...
TRY.
get_technical_attributes(
EXPORTING im_type = planetype
IMPORTING ex_weight = weight
ex_tankcap = cap ).
WRITE: /'Gewicht:'(003), weight,
'Tankkapazität:'(004), cap.
CATCH zcx_wrong_planetype INTO lx_exc.
MESSAGE lx_exc TYPE 'I'.
ENDTRY.
ENDMETHOD.
RAISING zcx_wrong_planetype
CATCH zcx_wrong_planetype INTO lx_exc
RAISE EXCEPTION
TYPE zcx_wrong_planetype
EXPORTING pl_type = im_type
①
②
11. Exception Handling�Declarable Exceptions
212
© msg systems ag, 15.01.2013
cx_static_check
cx_dynamic_check
cx_no_check
cx_root
11. Exception Handling�Summary
213
© msg systems ag, 15.01.2013
You should now be able to
Exercise
214
© msg systems ag, 15.01.2013
Exercise
Exception Handling
Class-based Exceptions
MIN
HOURS
12. Dynamic Programming
215
© msg systems ag, 15.01.2013
12. Dynamic Programming�Field Symbols
216
© msg systems ag, 15.01.2013
Field symbols
FIELD-SYMBOLS: <fs> TYPE <Structure>,
<fs> TYPE TABLE OF <Structure>,
<fs> TYPE ANY,
<fs> TYPE ANY TABLE.
<fsob>
<fs1>
<fs2>
<fs3>
Index Name Fname Age Wage
1 Huber Lotte 18 1.200
2 Maier Klaus 24 1.800
3 Berg Lisa 35 2.400
4 Reiß Tim 24 1.800
12. Dynamic Programming�Field Symbols – ASSIGNING vs. INTO
217
© msg systems ag, 15.01.2013
DATA: tab1 TYPE TABLE OF struct,
tab2 TYPE TABLE OF struct,
tab3 TYPE TABLE OF struct.
FIELD-SYMBOLS: <fs> TYPE struct.
* make <fs> point onto
* first record in a table
READ TABLE tab1 INDEX 1
ASSIGNING <fs>.
* make <fs> point onto
* first record in a another table
READ TABLE tab2 INDEX 2
ASSIGNING <fs>.
* copy record from a third table into
* the table row pointed at by <fs>
READ TABLE tab3 INDEX 1
INTO <fs>.
<fs>
1
2
3
1
2
3
Index Name Fname
1 Huber Lotte
2 Maier Klaus
Index Name Fname
1 Berg Lisa
2 Reiß Tim
Index Name Fname
1 Kraus Karl
2 Moser Hans
Kraus Karl
ASSIGNING <fs>
ASSIGNING <fs>
INTO <fs>
12. Dynamic Programming�Field Symbols – Casting on ASSIGN
218
© msg systems ag, 15.01.2013
TYPES: BEGIN OF st_date,
year(4) TYPE n,
month(2) TYPE n,
day(2) TYPE n,
END OF st_date.
�* Option 1: Implicitly
FIELD-SYMBOLS <fs> TYPE st_date.
ASSIGN sy-datum TO <fs> CASTING.
* Option 2: Explicit
FIELD-SYMBOLS <fs> TYPE ANY.
ASSIGN sy-datum TO <fs>
CASTING TYPE st_date.
* Access after cast:
WRITE: / <fs>-year, <fs>-month, <fs>-day.
20120221
<fs>
CASTING
CASTING TYPE
TYPE ANY
12. Dynamic Programming
219
© msg systems ag, 15.01.2013
12. Dynamic Programming�Statements with Dynamic Attributes
220
© msg systems ag, 15.01.2013
Replacing a literal with a variable:
CALL TRANSACTION 'T_CODE'.
SUBMIT report.
SET PF-STATUS 'STATUS_NAME'
EXCLUDING 'FC1' 'FC2' ... .
Replacing an identifier with a variable in brackets (without blanks):
Replacing an enumeration with an internal table:
Replacing conditions with an internal table :
LOOP AT table ASSIGNING <fs>
WHERE age = 16 OR age = 17
AND salary <= 1000 ... .
lv_tcode = 'T_CODE'. �CALL TRANSACTION lv_tcode.
lv_report_name = 'REPORT'. �SUBMIT (lv_report_name).
* fill internal table lt_exclude
* with function codes�SET PF-STATUS 'STATUS_NAME'
EXCLUDING lt_exclude.
* ... fill internal table
* lt_cond with conditions.�LOOP AT table INTO wa
WHERE lt_cond.
lv_tcode
(lv_report_name)
lt_exclude
lt_cond
12. Dynamic Programming�Calling methods dynamically
221
© msg systems ag, 15.01.2013
ptab
etab
NAME KIND VALUE
TYPE-POOLS: abap.
DATA: meth TYPE abap_methname,
ptab TYPE abap_parmbind_tab,
etab TYPE abap_excpbind_tab.
...
meth = 'METHOD_NAME'.
* Fill ptab and etab
...
CALL METHOD ref->(meth)
PARAMETER-TABLE ptab
EXCEPTION-TABLE etab.
Reference to the actual parameter
TYPE REF TO
Transfer type
Formal parameter name
Exception name
sy-subrc value
NAME VALUE
PARAMETER-TABLE ptab
EXCEPTION-TABLE etab
abap_parmbind_tab
abap_excpbind_tab
abap_methname
12. Dynamic Programming
222
© msg systems ag, 15.01.2013
12. Dynamic Programming�Data References
223
© msg systems ag, 15.01.2013
lr_ref
lv_num
TYPES reftype { TYPE REF TO type_name |
LIKE REF TO do_name |
TYPE REF TO data }.
DATA ref { TYPE REF TO type_name |
LIKE REF TO do_name |
TYPE REF TO data }.
GET REFERENCE OF dataobject INTO ref.
DATA: lr_ref TYPE REF TO i,
lv_num TYPE i VALUE 15.
GET REFERENCE OF lv_num INTO lr_ref.���
lr_ref
lv_num
15
15
Get reference to a data object
Generic type
Any completely specified type
GET REFERENCE OF lv_num INTO lr_ref.
12. Dynamic Programming�Example: Dynamic Method Calls
224
© msg systems ag, 15.01.2013
TYPE-POOLS abap.
DATA: ptab TYPE abap_parmbind_tab,
wa_ptab LIKE LINE OF ptab,
meth TYPE abap_methname,
gd_make TYPE string VALUE `VOLVO`.
wa_ptab-name = 'EX_MAKE'.
GET REFERENCE OF gd_make
INTO wa_ptab-value = ref.
INSERT wa_ptab INTO TABLE ptab.
meth = 'GET_MAKE'.
CALL METHOD r_truck->(meth)
PARAMETER-TABLE ptab.
WRITE gd_make.
CLASS lcl_vehicle DEFINITION.
...
METHODS get_make
EXPORTING ex_make TYPE string.
...
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
...
METHOD get_make.
ex_make = make.
ENDMETHOD.
...
ENDCLASS.
ptab
gd_make
`VOLVO`
Situation after the dynamic method call:
NAME KIND VALUE
EX_MAKE
12. Dynamic Programming�Creating Data Objects at Runtime
225
© msg systems ag, 15.01.2013
DATA ref { TYPE REF TO type_name | LIKE REF TO var }.
CREATE DATA ref.
DATA ref TYPE REF TO data.
CREATE DATA ref TYPE { type_name | itab_type_def }.
PARAMETERS pa_tab TYPE dd021-tabname.
DATA ref_itab TYPE REF TO data.
CREATE DATA ref_itab TYPE STANDARD TABLE
OF (pa_tab)
WITH DEFAULT KEY.
ref_itab
Standard table with default key and row type corresponding to the content of the data object pa_tab
①
②
Typing can also take place dynamically
CREATE DATA
(pa_tab)
12. Dynamic Programming�Dereferencing data references
226
© msg systems ag, 15.01.2013
ASSIGN ref->* TO <fs> [CASTING ... ].
PARAMETERS pa_tab TYPE dd021-tabname.
DATA ref_itab TYPE REF TO data.
FIELD-SYMBOLS <fs_itab> TYPE ANY TABLE.
CREATE DATA ref_itab TYPE STANDARD TABLE
OF (pa_tab)
WITH DEFAULT KEY.
ASSIGN ref_itab->* TO <fs_itab>.
SELECT * FROM (pa_tab) INTO TABLE <fs_itab>.
ref_itab fs_itab
->*
You can address the contents of the internal table using the field symbol.
12. Dynamic Programming�Example: Output the contents of an arbitrary database table
227
© msg systems ag, 15.01.2013
PARAMETERS pa_dbtab TYPE dd02l-tabname
DEFAULT 'SFLIGHT'.
DATA d_ref TYPE REF TO data.
FIELD-SYMBOLS: <fs_wa> TYPE ANY,
<fs_comp> TYPE ANY.
START-OF-SELECTION.�
CREATE DATA d_ref TYPE (pa_dbtab).
ASSIGN d_ref->* TO <fs_wa>.
SELECT * FROM (pa_dbtab) INTO <fs_wa>.
DO.
ASSIGN COMPONENT sy-index
OF STRUCTURE <fs_wa> TO <fs_comp>.
IF sy-subrc NE 0. SKIP. EXIT. ENDIF.� WRITE <fs_comp>.
ENDDO.
ENDSELECT.
12. Dynamic Programming
228
© msg systems ag, 15.01.2013
12. Dynamic Programming�Determine properties of internal tables
229
© msg systems ag, 15.01.2013
DATA: no_of_lines TYPE i,
initial_lines TYPE i,
table_kind TYPE c.
DESCRIBE TABLE itab
LINES no_of_lines
OCCURS initial_lines
KIND table_kind.��* other variant:�no_of_lines = lines( itab ).
TYPE-POOL: sydes.
sydes_kind-undefined
sydes_kind-standard
sydes_kind-sorted
sydes_kind-hashed
table_kind
Number of rows in the internal table
Number of initial lines
Table kind
Constants for evaluating the return values
12. Dynamic Programming�RTTI – Run Time Type Information
230
© msg systems ag, 15.01.2013
Hierarchy of description classes:
CL_ABAP_TYPEDESCR
CL_ABAP_DATADESCR
CL_ABAP_OBJECTDESCR
CL_ABAP_COMPLEXDESCR
CL_ABAP_CLASSDESCR
CL_ABAP_ELEMDESCR
CL_ABAP_TABLEDESCR
CL_ABAP_INTFDESCR
CL_ABAP_REFDESCR
CL_ABAP_STRUCTDESCR
Rules
Determining the type attributes of a data object at runtime: :
12. Dynamic Programming�Example for dynamic type description
231
© msg systems ag, 15.01.2013
...
DATA:
descr_ref TYPE REF TO cl_abap_structdescr,
wa_comp TYPE abap_compdescr.� ...
START-OF-SELECTION.
...� "get reference to type description object by widening cast:� descr_ref ?= cl_abap_typedescr=>describe_by_data( <fs_wa> ).
...
TOP-OF-PAGE.
LOOP AT descr_ref->components INTO wa_comp.
WRITE wa_comp-name.
ENDLOOP.
12. Dynamic Programming
232
© msg systems ag, 15.01.2013
12. Dynamic Programming�Conventional Data Operations
233
© msg systems ag, 15.01.2013
DATA: itab TYPE TABLE OF structure,
wa TYPE structure.
READ TABLE itab INTO wa
WITH KEY age = 24.
IF sy-subrc = 0.
wa-wage = '1.900'.
MODIFY itab FROM wa.
ENDIF.
Index Name FName Age Wage
2 Maier Klaus 24 1.900
Index Name FName Age Wage
1 Huber Lotte 18 1.200
2 Maier Klaus 24 1.800
3 Berg Lisa 35 2.400
4 Reiß Tim 27 2.000
MODIFY itab FROM wa.
1.900
Changing a single, unique record
IF sy-subrc = 0.
ENDIF.
12. Dynamic Programming�Implementation with Field Symbols
234
© msg systems ag, 15.01.2013
DATA: itab TYPE TABLE OF structure.
FIELD-SYMBOLS: <fs> TYPE structure.
READ TABLE itab ASSIGNING <fs>
WITH KEY age = 24.
IF sy-subrc = 0.
<fs>-wage = '1.900'.
ENDIF.
Index Name FName Age Wage
1 Huber Lotte 18 1.200
2 Maier Klaus 24 1.800
3 Berg Lisa 35 2.400
4 Reiß Tim 27 2.000
1.900
Changing a single, unique record
IF sy-subrc = 0.
ENDIF.
<fs>
12. Dynamic Programming –�Conventional Data Operations
235
© msg systems ag, 15.01.2013
DATA: itab TYPE TABLE OF structure,
wa TYPE structure.
LOOP AT itab INTO wa
WHERE age = 24.
wa-wage = '1.900'.
MODIFY itab FROM wa.
ENDLOOP.
Index Name FName Age Wage
1 Huber Lotte 18 1.200
2 Maier Klaus 24 1.800
3 Berg Lisa 35 2.400
4 Reiß Tim 24 2.000
Changing multiple, similar records
MODIFY itab FROM wa.
Index Name FName Age Wage
2 Maier Klaus 24 1.900
1.900
Index Name FName Age Wage
4 Reiß Tim 24 1.900
1.900
12. Dynamic Programming –�Implementation with Field Symbols
236
© msg systems ag, 15.01.2013
DATA: itab TYPE TABLE OF structure.
FIELD-SYMBOLS: <fs> TYPE structure.
LOOP AT itab ASSIGNING <fs>
WHERE age = 24.
<fs>-wage = '1.900'.
ENDLOOP.
Index Name FName Age Wage
1 Huber Lotte 18 1.200
2 Maier Klaus 24 1.800
3 Berg Lisa 35 2.400
4 Reiß Tim 24 1.900
1.900
Changing multiple, similar records
<fs>
1.900
12. Dynamic Programming –�Conventional Data Operations
237
© msg systems ag, 15.01.2013
DATA: itab1 TYPE TABLE OF structure1,
wa1 TYPE structure1,
itab2 TYPE TABLE OF structure2,
wa2 TYPE structure2.
LOOP AT itab1 INTO wa1.
wa1-kz = 'U'.
MODIFY itab FROM wa1.
ENDLOOP.
LOOP AT itab2 INTO wa2.
wa2-kz = 'U'.
MODIFY itab FROM wa1.
ENDLOOP.
Changing a common field in different internal tables
MODIFY itab FROM wa1.
MODIFY itab FROM wa2.
12. Dynamic Programming –�Implementation with Field Symbols
238
© msg systems ag, 15.01.2013
DATA: s_tab TYPE TABLE OF string,
s_wa TYPE string,
itab1 TYPE TABLE OF structure1,
itab2 TYPE TABLE OF structure2.
FIELD-SYMBOLS: <fst> TYPE ANY TABLE,
<fsw> TYPE ANY,
<fsk> TYPE ANY.
APPEND 'itab1' TO s_tab.
APPEND 'itab2' TO s_tab.
LOOP AT s_tab INTO s_wa.
UNASSIGN <fst>.
ASSIGN (s_wa) TO <fst>.
IF <fst> IS ASSIGNED.
ENDIF.
ENDLOOP.
Changing a common field in different internal tables
LOOP AT <fst> ASSIGNING <fsw>.
ASSIGN COMPONENT 'KZ'
OF STRUCTURE <fsw>
TO <fsk>.
IF <fsk> IS ASSIGNED.
<fsk> = 'U'.
ENDIF.�
ENDLOOP.
12. Dynamic Programming�Termination after accessing a field symbol which was not assigned
239
© msg systems ag, 15.01.2013
DATA: itab TYPE TABLE OF structure.
FIELD-SYMBOLS: <fs> TYPE structure.
READ TABLE itab ASSIGNING <fs>
WITH KEY age = 20.
IF sy-subrc = 0.
<fs>-wage = '1.400'.
ENDIF.
Index Name FName Age Wage
1 Huber Lotte 18 1.200
2 Maier Klaus 24 1.800
3 Berg Lisa 35 2.400
4 Reiß Tim 27 2.000
Record not found!
IF <fs> IS ASSIGNED.
ENDIF.
<fs>
12. Dynamic Programming�Erroneous write access to pre-assigned field symbol
240
© msg systems ag, 15.01.2013
Index Name FName Age Wage
1 Huber Lotte 18 1.200
2 Maier Klaus 24 1.800
3 Berg Lisa 35 2.400
4 Reiß Tim 27 2.000
Record not found on the second query!
IF <fs> IS ASSIGNED.
ENDIF.
<fs>
DATA: itab TYPE TABLE OF structure.
FIELD-SYMBOLS: <fs> TYPE structure.
READ TABLE itab ASSIGNING <fs>
WITH KEY age = 24.
<fs>-wage = '1.900'.
READ TABLE itab ASSIGNING <fs>
WITH KEY age = 20.
"!!! <fs> still points onto Klaus
<fs>-wage = '1.400'.
1.400
1.900
12. Dynamic Programming�Summary
241
© msg systems ag, 15.01.2013
You should now be able to
Bibliography
242
© msg systems ag, 15.01.2013
243
© msg systems ag, 15.01.2013
Hubert Englmaier
Senior IT Consultant
Insurance
Telefon: +49 89 96101-4568
Hubert.Englmaier@msg-systems.com
www.msg-systems.com
Thank you for your attention!
www.msg-systems.com
Vielen Dank für Ihre Aufmerksamkeit