BC401 ABAP Object PDF
BC401 ABAP Object PDF
BC401
BC401
ABAP Objects
SAP AG 2002
2002/Q3
Copyright
SAP AG 2002
Notes on Trademarks:
Some software products marketed by SAP AG and its distributors contain proprietary software
components of other software vendors.
Microsoft , WINDOWS , NT , EXCEL , Word , PowerPoint , and SQL Server are registered
trademarks of Microsoft Corporation.
IBM , DB2 , OS/2 , DB2/6000 , Parallel Sysplex , MVS/ESA , RS/6000 , AIX , S/390 , AS/400 ,
,
TM
INFORMIX -OnLine for SAP and INFORMIX Dynamic Server are registered trademarks
of Informix Software Incorporated.
UNIX , X/Open , OSF/1 and Motif are registered trademarks of the Open Group.
HTML, DHTML, XML, and XHTML are trademarks or registered trademarks of W3C , World Wide
Web Consortium, Massachusetts Institute of Technology.
JAVASCRIPT is a registered trademark of Sun Microsystems, Inc., used under license for technology
developed and implemented by Netscape.
SAP, SAP Logo, R/2, RIVA, R/3, ABAP, SAP ArchiveLink, SAP Business Workflow, WebFlow, SAP
EarlyWatch, BAPI, SAPPHIRE, Management Cockpit, mySAP.com Logo, and mySAP.com are
trademarks or registered trademarks of SAP AG in Germany and several other countries all over the
world. All other products mentioned are trademarks or registered trademarks of their respective
companies.
Course Prerequisites
Programming experience
SAPTEC
(mySAP Technology Solution Overview)
BC400
(ABAP Workbench: Foundations and Concepts)
Programming experience in ABAP
SAP AG 2002
Target Group
SAP AG 2002
Course Overview
Contents:
Course goal
Course objectives
Course content
Course overview diagram
Main business scenario
SAP AG 2002
(C) SAP AG
BC401
1-1
Course Goal
programming
Learn the structure and application of
ABAP Objects
SAP AG 2002
(C) SAP AG
BC401
1-2
Course Objectives
SAP AG 2002
(C) SAP AG
BC401
1-3
Preface
Unit 1
Course Overview
Unit 2
Unit 3
Unit 4
Unit 5
Unit 6
Unit 7
Unit 8
Inheritance
Unit 9
Casting
Unit 10
Interfaces
SAP AG 2002
(C) SAP AG
BC401
1-4
Unit 11
Events
Unit 12
Unit 13
Special Techniques
Unit 14
Exception Handling
Unit 15
Dynamic Programming
Appendix
SAP AG 2002
(C) SAP AG
BC401
1-5
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
1-6
SAP AG 2002
(C) SAP AG
BC401
1-7
Technical Names
Package: BC401
Naming conventions for program objects:
Demonstrations:
SAPBC401_xxxD_...
Copy templates:
SAPBC401_xxxT_...
Model solutions:
SAPBC401_xxxS_...
SAP AG 2002
Unit codes:
Unit 2: DTO
Unit 3: TAB
Unit 4: CAL
Unit 7: AIR
Unit 8: INH
Unit 9: CAS
Unit 10: INT
Unit 11: EVE
Unit 12: CLS
Unit 13: SPC
Unit 14: EXC
Unit 15: DYN
(C) SAP AG
BC401
1-8
Contents:
Data objects in programs
Elementary data objects
Structures
Character string processing in Unicode
SAP AG 2002
(C) SAP AG
BC401
2-1
SAP AG 2002
(C) SAP AG
BC401
2-2
and
Data Types
in
ts
ec
O
bj
Data
Detail
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
2-3
Introduction
Introduction
Elementary
Elementary Data
Data Objects
Objects
Structures
Structures
Special
Special Features
Features in
in Unicode
Unicode
SAP AG 2002
(C) SAP AG
BC401
2-4
Local types
TYPES type_name TYPE ...
Predefined
ABAP types
d
t
i
f
string
xstring
p
n
c
x
Global
types
SAP AG 2002
Data objects are usually defined with the DATA statement as follows. After the name of the data object, a
a fully-specified type is assigned to it using the TYPE addition. The type is linked to the data object
statically and cannot be changed at runtime.
There are other syntax variants available (for historical reasons). Note however, that some of these
historical variants are no longer supported in ABAP Objects. For further information, refer to the
keyword documentation for the DATA statement.
All types are based on predefined ABAP types, which will be discussed in greater detail in the following
slide. Some of these ABAP types are fully specified and can be used to type data objects directly. Other
types need to be modified to include the length, and in some cases the number of decimal places so that
they are fully specified. These are the simplest examples of user-defined types.
You can create complex structured types of any level of complexity, based on elementary types.
You can also define types centrally in the ABAP Dictionary. You can then use these global types in all
appropriate Repository objects in the system.
(C) SAP AG
BC401
2-5
Fixed length
i
f
p
Description
Integer
Length in bytes
Attributes
Differ in:
Rules for storage
Value range
Arithmetic used
n
c
d
t
Number sequence
1 .. 65535
Character sequence 1 .. 65535
Date
8
Time
6
Hexadecimal
Variable
length
Hexadecimal code
1 .. 65535
Bit operations
string
xstring
Character sequence
Hexadecimal code
SAP AG 2002
The following ABAP types are fully specified and can be used directly to type data objects: d, t, i, f,
string, and xstring. A special feature of the string and xstring types is that their length is
adjusted dynamically at runtime. Thus, for these two types, length is not a component of the type.
The following ABAP types are not fully specified, so you must include additional information before
you use them to define data objects:
c, n, and x
Length needs to be added. Permitted values: 1 to 65535 characters.
If you do not declare a length when you define a data object, the system assigns the default length of
1.
p
You must extend the type to include the length, and number of decimal places, Permitted length: 1 to
16 bytes. If you do not declare a length when you define a data object, the system assigns the default
length of 8 bytes (that is, 15 digits) and 0 decimal places.
The type also contains information on how the data is stored, what range of values is allowed, what
operations can be performed on the data, and what sort of arithmetic is used (if the data object is suitable
for use in calculations). We will deal with this topic in greater detail later in this unit.
(C) SAP AG
BC401
2-6
Using a constant:
ABAP program
TYPE-POOLS:
TYPEzmytp
TYPE-POOLS zmytp.
[ DATA var TYPE zmytp
zmytp_type1. ]
IF var = zmytp
zmytp_const_name.
...
ENDIF.
SAP AG 2002
You must use a type group to define global constants. The name of the type group can contain up to 5
characters.
You define constants in the type group using the CONSTANTS statement, just as in an ABAP program.
You only have to adhere to the following namespace convention:
All constants (and type names) must have the name of the type group as a prefix.
You can use either a global Dictionary type or a predefined ABAP type as a valid type.
To be able to use the types of a type group in a program, you must refer to the type group using the
TYPE-POOLS statement.
After this line in the program, you can then use all the constants in the type group.
You can also define global data types in a type group. Before SAP R/3 Basis Release 4.5, this was the
only way to define complex global data types.
(C) SAP AG
BC401
2-7
Introduction
Introduction
Elementary
Elementary Data
Data Objects
Objects
Structures
Structures
Special
Special Features
Features in
in Unicode
Unicode
SAP AG 2002
(C) SAP AG
BC401
2-8
Length: 4 bytes
Integer Arithmetic
int2 =
int1
int3 =
4
3
3
/
1
int4 =
+
*
/
DIV
MOD
**
Addition
Subtraction
Multiplication
Division
Integer division
Remainder integer div.
Power
SAP AG 2002
In integer arithmetic, the system always rounds to the appropriate decimal place. So, for example:
DATA int TYPE i.
int = 4 / 10.
" result: 0
int = 5 / 10.
" result: 1
Calculations performed using integer arithmetic are faster than calculations using fixed point or floating
point arithmetic.
For further information on calculations performed on integers, refer to the keyword documentation for
the COMPUTE statement.
(C) SAP AG
BC401
2-9
Length in bytes:
n bytes correspond to
2n - 1 digits
Number of decimal
places
1234,56
78,5
1313,06
Internal representation
0 1 2 3 4 +
1 digit per
half-byte
Sign
SAP AG 2002
The length of packed numbers is given in bytes. The connection between value range and length is
derived from the internal representation: Each decimal digit is represented by a half-byte. The last byte is
reserved for the plus or minus sign.
The number of decimal places is defined using the DECIMALS addition. The maximum number of
decimal places is either 15 or the length of the number minus 1 (that is, there must be at least one digit
before the comma).
In user dialogs, decimal numbers are formatted according to the settings in the user master record.
Decimal point-aligned fixed point arithmetic is used as default for calculations. Packed numbers are thus
well-suited to business calculations, where the correct rounding for the specified number of decimal
places is very important. The algorithm for this arithmetic is similar to using "pencil and paper".
The system always uses packed numbers of maximum length for interim results.
You can switch off fixed point arithmetic in the program attributes. If you do, the DECIMALS addition
when defining a packed number only affects the output of the number. Internally, all numbers are
interpreted as integers, regardless of the position of the decimal point. The fixed point arithmetic option
is always selected by default. You should always accept this value and use packed numbers for business
calculations.
(C) SAP AG
BC401
2-10
1,5 = 120 + 12 1
1
=1 +
2
| 0 0 |
| ...
| 0 0 |
0,15 = 12 3 + 12 6 + 12 7 + 12 10 + 12 11 +
1
1
1
1
1
=
+
+
+
+
+
8
128 1024 2048
64
= 0,125 +
=
=
=
0,140625 +
Only for
approximations
0,1484375 +
0,1494140625 +
0,1499023437
SAP AG 2002
Unlike packed numbers, floating point numbers are represented using sums of binary fractions. Floating
point numbers are also normalized, and both the exponent and the mantissa are stored in binary form.
This representation complies with the IEEE norm for double precision floating point numbers. The
floating point operations of the relevant processors are used for calculations.
Since algorithms are converted to binary, inaccuracies can occur. Therefore, floating point numbers are
not suitable for business calculations.
Example:
You want to calculate 7.72% of 73050 and display the result accurate to two decimal places. The answer
should be 5310.74 (73050 * 0.0727 = 5310.7735). The program, however:
DATA: float TYPE f, pack TYPE p DECIMALS 2.
float = 73050 * '0.0727'. " result: 5.3107349999999997E+03
pack = float. WRITE pack. " result: 5310.73
You should therefore only use floating point numbers for approximations. When you compare
numbers, always use intervals, and always round at the end of your calculations.
The advantage of floating point numbers is the large value range: It comprises numbers from is, from
2,2250738585072014E-308 to 1,7976931348623157E+308 including both positive and negative
numbers as well as zero. In addition, you must use floating point numbers for special aggregation
functions of the SELECT statement.
(C) SAP AG
BC401
2-11
Required:
Integers only
Type p
Type F
SAP AG 2002
Note:
The results of the following functions have the data type f:
Trigonometric functions: cos, acos, sin, asin, tan, atan
Hyperbolic functions: tanh, sinh, cosh
Exponential functions (base e): exp
Natural logarithms (base e): log
Logarithms (base 10): log10
Square root: sqrt
(C) SAP AG
BC401
2-12
Example:
p DECIMALS 3
r
i
=
a
201
i
/
0.0000...E+000
1.004999...E+000 +
0.0000...E+000
200
+
+
Conversion after f
and calculation
Interim result:
=
1.004999...E+000
1.005
Conversion after
p DECIMALS 3
SAP AG 2002
An arithmetic expression may contain any data types that are convertible into each other and into the
type of the result field.
The system converts all the values into one of the three numeric data types (i, p, or f), depending on the
data types of the operands. The ABAP runtime system contains an arithmetic for each of the three data
types. The system then performs the calculation and converts it into the data type of the result field.
This may mean that the same arithmetic expression leads to different results when performed on
different combinations of data types.
It is also possible for an arithmetic expression to have only character string type data objects, as long
as their contents are appropriate. The values are converted to numeric type objects. Bear in mind that
conversions affect performance. Wherever possible, choose a data type that does not require runtime
conversion.
If an arithmetic expression contains numeric literals, the choice of arithmetic depends on the size of the
number: If the number is within the value range for the data type i, the numeric literal is interpreted as
an integer. If the value of the literal is greater than 2147483647, it is interpreted as a packed number.
Example:
DATA int TYPE i. int = 1000000000 / 300000000 * 3. "result: 9
int = 10000000000 / 3000000000 * 3. "result: 10
(C) SAP AG
BC401
2-13
Type t
Type d
Type n
Time
Date
6 digits
HHMMSS
8 digits
1 .. 65535
YYYYMMDD characters
Description
Length
Value range
Calculations
Formatting
options
By clock
Time
arithmetic
HH:MM:SS
Type c
Sequence FixedFixed-length
of digits
char. string
By Gregorian
calendar
Date
arithmetic
Digits
Conversion
1 .. 65535
characters
Type string
Char. string
of variable
length
Variable
Depends on codepage
Conversion
Conversion
Based on
user default
values
SAP AG 2002
The value range of each string depends on the code page, which contains all the supported characters in
form of a table. Internally, each character is represented by a code number. When the system outputs the
character, it uses the code page to convert this number. To find the code page valid in a given system,
choose Tools CCMS Spool Administration Full Administration Character Sets.
The initial value of each character string with fixed length is a space character.
Numeric strings are represented internally as character strings. Note, however, that only digits are
permissible as characters. When character strings are assigned to numeric strings, the system ignores
letters and only copies the digits (right-aligned). Missing characters are filled with zeros.
The initial value of each character in a numeric string is a zero.
Only sequences of digits are valid for values of type d. These digits form a meaningful date, which
complies with the Gregorian calendar. The first four digits represent the year, the next two the month
and the last two the date. For performance reasons however, the object is only checked if it is an input
field on a screen or selection screen.
The initial value of a date is '000000'. The formatting options are determined by the user settings.
For values of type t, a sequence of digits is only valid if it can be interpreted as a time on the 24-hour
clock. The rules for interpreting the value are analogous to those used for dates.
The initial value of a time is '000000'.
(C) SAP AG
BC401
2-14
FIND
ABAP
REPLACE
ABAP
BBAP
TRANSLATE
ABAP
a b ap
SHIFT
ABAP
AP
AB P
BAP
AP
Move
CONDENSE
OVERLAY
ABAP
A B +A P
ABAP
Concatenate several
character strings
ABCAP
AB
AAAA
CONCATENATE
SPLIT
AP
SAP AG 2002
(C) SAP AG
BC401
2-15
REPORT ...
PARAMETERS:
pa_str(40) LOWER CASE,
pa_pos TYPE i,
pa_len TYPE i.
+pa_pos(pa_len)
WRITE pa_str+pa_pos(pa_len).
19991231ttA235959
000000
SAP AG 2002
In any statement that operates on a character-type field, you can address part of the field or structure by
specifying a starting position and a number of characters. If the field lengths are different, the system
either truncates the target or fills it with initial values. The source and target fields must have the type x,
c, n, d, t, or STRING. You can also use structures.
Example
MOVE <field1>+<off1>(<len1>) TO <field2>+<off2>(<len2>).
This statements assigns <len1> characters of field <field1> starting at offset <off1> to <len2>
characters of <field2> starting at offset <off2>.
(C) SAP AG
BC401
2-16
Introduction
Introduction
Elementary
Elementary Data
Data Objects
Objects
Structures
Structures
Special
Special Features
Features in
in Unicode
Unicode
SAP AG 2002
(C) SAP AG
BC401
2-17
TYPES:
TYPES:
BEGIN OF s_name_type
s_name_type,
prename(25) TYPE c,
surname(25) TYPE c,
title(5)
TYPE c,
END OF s_name_type.
DATA:
BEGIN OF s_name
s_name,
prename(25) TYPE c,
surname(25) TYPE c,
title(5)
TYPE c,
END OF s_name
s_name.
DATA:
s_name TYPE s_name_type .
Alternatives
START-OF-SELECTION.
s_name-prename
= 'Smith'.
s_names_name-surname
= 'John'.
s_nameSAP AG 2002
As with elementary data objects, you can define structures in two ways:
First, define a structure type explicitly using the TYPES statement.
To do this, enter the name of the structure after BEGIN OF and then list the definitions of all the
components. End the definition of the structure type using END OF.
You then define the structured data object with the DATA statement, using your own user-defined
structure type.
Define the data object directly using the DATA statement. The syntax is similar to the definition of a
structure type. If you use this option, the corresponding structure type is defined implicitly at the same
time.
In both cases, the type is defined locally. Bear in mind that you can also use globally defined types
instead.
You address components of structures using:
structure_name-comp_name.
For this reason, you should avoid using hyphens in variable names.
(C) SAP AG
BC401
2-18
Structure type
s_name_type
prename
surname
title
DATA:
BEGIN OF s_address,
name
TYPE s_name_type
s_name_type,
street(15) TYPE c,
city(25)
TYPE c,
END OF s_address.
Nested structure
s_address
name
prename
surname
title
street
city
s_address-name-surname
= 'Smith'.
s_address-city
= 'London'.
-
Application:
Logical subgrouping
of data
SAP AG 2002
You can define nested structures by assigning a structure type to a component within a structure type.
You can address this substructure as a whole using the component name:
structure_name-substructure_name.
You can also address individual components in the substructure:
structure_name-substructure_name-comp_name.
Structures can be nested to any level you wish.
You can also integrate components of a dynamic type in a structure. This can either be an elementary
data object of variable length (string or xstring),an internal table, or a reference. These structures
are known as deep structures.
There are constraints on how such deep structures can be used. For instance, a deep structure cannot be
used as a whole in the INTO clause of the SELECT statement. (Instead, each component must be listed
separately). Offset operations are also not appropriate. For more information, refer to SAP Note 176336.
(C) SAP AG
BC401
2-19
Structure type
s_name_type
prename
surname
title
DATA
BEGIN OF s_address.
INCLUDE
INCLUDE STRUCTURE
STRUCTURE s_name_type
AS name.
DATA:
street(15) TYPE c,
city(25)
TYPE c,
END OF s_address.
s_address-name-surname
= 'Smith'.
* or:
s_address-surname
= 'Smith'.
name
Use:
Logical subgroup desired, but nested
structures not technically possible
SAP AG 2002
(C) SAP AG
BC401
2-20
Introduction
Introduction
Elementary
Elementary Data
Data Objects
Objects
Structures
Structures
Special
Special Features
Features in
in Unicode
Unicode
SAP AG 2002
(C) SAP AG
BC401
2-21
Unicode: Overview
Previous problems
a
Solution: Unicode
a
Unicode
SAP AG 2002
To be able to work with Unicode, you must have a Unicode-compatible SAP System installed that itself
has a corresponding operating system and database. The ABAP programs must also be Unicodecompatible.
In Unicode programs, other syntax rules apply than in non-Unicode programs. This is due to the
difference between the length in bytes and the number of characters in a character set in Unicode.
Existing programs are affected by a conversion to Unicode if an explicit or implicit assumption is made
about the internal length of a character. To execute the relevant syntax checks, you must check Unicode
Checks Active under program attributes.
In a Unicode system, you can only execute programs that have the Unicode flag set. If the Unicode flag
is set for a program, the syntax check and program are executed in accordance with the rules described
in the Unicode online help (irrespective of whether it is a Unicode or a non-Unicode system).
If the Unicode flag is not set, the program can only be executed in a non-Unicode system. For such
programs, the Unicode-specific changes of syntax and semantics do not apply. However, you can use all
language enhancements introduced in connection with the conversion to Unicode.
(C) SAP AG
BC401
2-22
d
c
t
Character-type
structure types
xstring
string
x_field
G
O
E391B9A2
_
B9A20000
SAP AG 2002
(C) SAP AG
BC401
2-23
Length in
characters
Character-type type
Functions
STRLEN
STRLEN
Byte-type type
XSTRLEN
BYTE-CO, BYTE-CA,
Comparison
operators
BYTE-CS, BYTE-CN,
BYTE-NA, BYTE-NS
Examples:
DATA: c_fld1(4) TYPE c VALUE 'HUGO',
c_fld2(1) TYPE c VALUE 'G'.
IF c_fld1 CA c_fld2.
...
ENDIF.
SAP AG 2002
The operators CO, CN, CA, NA, CS, NS, CP, NP are available for comparing the contents of character
string type data objects (for syntax and semantics, see keyword documentation). As with the statements
for string processing, these operators require single fields of type c, n, d, t, or string as arguments.
Again, character-type structures are also permitted.
The X variants of the string comparison operators are distinguished from the character string variants by
the BYTE- prefix. For this operation, only X fields and fields of the type xstring are allowed as
arguments.
The STRLEN function only works with character-type fields and returns the length in characters. With c
fields, only the so-called occupied length is relevant, that is, unlike with strings, trailing blanks are not
counted.
The XSTRLEN function is available for the length of byte sequences. For X strings, XSTRLEN returns
the current length and for X fields, the defined length in bytes, where null bytes at the end of fields are
counted.
(C) SAP AG
BC401
2-24
SAP AG 2002
If two data types are not compatible but there is a conversion rule, the system converts the source object
into the type of the target object when you assign values, perform calculations, or compare values.
For a full list of all conversion rules, refer to the ABAP syntax documentation for the MOVE statement.
If there is no conversion rule defined for a particular assignment, the way in which the system reacts
depends on the program context.
If the types of the objects involved are defined statically, a syntax error occurs.
Example:
DATA: date TYPE d VALUE '19991231', time TYPE t.
FIELD-SYMBOLS: <fs_date> TYPE d, <fs_time> TYPE t.
ASSIGN: date TO <fs_date>, time TO <fs_time>.
<fs_time> = <fs_date>.
In the case of dynamic typing a runtime error occurs, because the field symbols are not assigned types
until the assignment of the data objects at runtime.
Example:
...
FIELD-SYMBOLS: <fs_date> TYPE ANY, <fs_time> TYPE ANY.
...
(Rest as above)
(C) SAP AG
BC401
2-25
struc1
C(6)
N(4)
X(3)
N(4)
C(4)
C(4)
P(8)
struc2
C(4)
struc1
Decisive criterion:
Fragment view
struc2
C(10)
Assignment is possible
X(3)
P(8)
SAP AG 2002
For some data types there are, for technical reasons, specific alignment requirements that depend on the
individual platforms. (In the memory, fields of this type must begin and end on specific addresses - for
example, a memory address divisible by four.)
Within a structure, the runtime system, if necessary, inserts bytes before or after these components with
alignment requirements to achieve the alignment needed. These bytes are known as Alignment.
To check whether the conversion is even permitted, the system first creates the Unicode fragment view
of the structures by grouping adjacent components and alignment gaps (one group each for charactertype types [c, n, d, t], byte-type types, and types i, f, and p).
Adjacent character-type components of a structure are therefore only grouped together if there are no
alignment gaps between these components. Adjacent byte-type components are grouped in the same
way.
If the fragments of the source and initial structures match the type and length in the length of the shorter
structure, the conversion is allowed.
If the target structure is longer than the source structure, the character-type components of the
remainder are filled with space characters. All other components in the remainder are filled with the
type-specific initial value, alignment gaps are filled with null bytes.
(C) SAP AG
BC401
2-26
c_field
C(9)
struc
C(6)
N(4)
X(3)
C(4)
c_field
Decisive criterion:
Fragment view
struc
Assignment is possible
Conversion between
.
structures and single fields is possible if
the structure begins with a character-type fragment and this
fragment is at least as long as the single field.
SAP AG 2002
The following rules apply for the conversion of a structure to a single field and vice versa:
If the single field is type c, but the structure isn't completely character-type, the conversion is only
allowed if the structure begins with a character-type group and this group is at least as long as the
single field. The conversion then takes place between the first character-type group of the structure and
the single field. If the structure is the target field, the character-type parts of the remainder are filled
with space characters and all other components with the type-specific initial value.
The conversion is not allowed if the structure is not purely character-type and the single field is not type
c.
Internal tables can be converted if their row type can be converted.
(C) SAP AG
BC401
2-27
p_date
Character-type
structure
s_date
SAP AG 2002
s_date is structured in such a way that the first four characters of a variable specify the year, the next
two specify the month, and the last two the day. If a date is assigned to this structure using the MOVE
statement, the characters are then copied left-aligned. You can then determine the year, month, and day
directly using the components of the structure, without having to use offsets.
(C) SAP AG
BC401
2-28
c_field
x_field
WRITE: c_field+1(4),
E391B9A203F6
x_field+3(2).
In the case .of byte-type fields, the values for offset and length are
taken in bytes.
SAP AG 2002
Offset/length accesses are permitted on character-type single fields, single fields with the type
string, and single fields of the types x and xstring.
For character-type fields and type string fields, offset and length are interpreted character by
character. Only with types x and xtring are the values for offset and length taken in bytes.
(C) SAP AG
BC401
2-29
c,
c,
c,
i,
c,
member
C(5)
C(15)
C(15)
C(20)
+off(len)
SAP AG 2002
Offset and length accesses to structures are only permitted in Unicode programs if the structure is flat
and the offset and length specifications only contain character-type fields from the beginning of the
structure. This means, the access will cause an error if the offset and length area contains both
character-type and non-character-type components.
If an offset/length access is allowed in a Unicode program, both offset and length specifications are
interpreted as characters.
Recommendation:
Only use offset and length accesses if it is necessary or useful. Bear in mind that processing component
by component and using character string operations is generally safer and more readable.
(C) SAP AG
BC401
2-30
SAP AG 2002
(C) SAP AG
BC401
2-31
Program:
Template:
SAPBC401_DTOT_SPLIT_STRING
Model solution:
SAPBC401_DTOS_SPLIT_STRING
1-2
Familiarize yourself with the main body of the program. Pay special attention to the
content of the data object datastring after the function module call. Use the
Debugger to do this, and/or display the character string in a list. (The function module
itself is here seen as a black box. For this exercise, it is not necessary to understand its
construction.)
1-3
To be able to split the character string into its components you must first remove the ##
characters. Remove the two leading separators from the character string first. Then
(C) SAP AG
BC401
2-32
copy the initial part up to the closing separators to the auxiliary variable
set_string. For this, set_string has to be defined appropriately.
1-4
Now use the separators to split the contents of the auxiliary variable set_string
into the structure wa_flight_c. The latter is typed with the local program structure
type st_flight_c. You still have to comment out the components of this structure
type and assign them an appropriate type.
1-5
1-6
In the list displayed in exercise 1-5, you should have observed that some of the fields
were displayed without formatting for example, the PRICE field. Your next step is to
change this.
To do this, convert the data you have extracted by copying it to data objects with
suitable types. Also, not all components of wa_flight_c are to be displayed.
For this purpose, a structure wa_flight has already been defined. It is typed with the
structure type st_flight. You must comment out the components of st_flight
and find appropriate types for these components for the formatting. Then copy the
identically-named components of the character-type structure wa_flight_c to the
fields of the structure wa_flight.
Display the contents of the structure wa_flight in a list. Use the appropriate
formatting options for the WRITE statement for the fldate and price components.
(C) SAP AG
BC401
2-33
sapbc401_dtos_split_string.
TYPES:
BEGIN OF st_flight_c,
mandt(3)
TYPE c,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate(8)
TYPE n,
price(20)
TYPE c,
currency(5)
TYPE c,
planetype(10)
TYPE c,
seatsmax(10)
TYPE n,
seatsocc(10)
TYPE n,
paymentsum(22) TYPE c,
seatsmax_b(10) TYPE n,
seatsocc_b(10) TYPE n,
seatsmax_f(10) TYPE n,
seatsocc_f(10) TYPE n,
END OF st_flight_c,
BEGIN OF st_flight,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate
TYPE d,
price(9)
TYPE p DECIMALS 2,
currency(5)
TYPE c,
planetype(10) TYPE c,
seatsmax
TYPE i,
seatsocc
TYPE i,
END OF st_flight.
(C) SAP AG
BC401
2-34
DATA:
datastring
TYPE string,
set_string
TYPE string,
TYPE st_flight.
START-OF-SELECTION.
CALL FUNCTION 'BC401_GET_SEP_STRING'
* EXPORTING
*
IM_NUMBER
= '1'
IM_TABLE_NAME
= 'SFLIGHT'
IM_SEPARATOR
= '#'
IM_UNIQUE
= 'X'
IMPORTING
ex_string
= datastring
EXCEPTIONS
no_data
= 1
OTHERS
= 2.
IF sy-subrc <> 0.
MESSAGE a038(bc401).
ENDIF.
BC401
2-35
wa_flight_c-carrid
wa_flight_c-connid
wa_flight_c-fldate
wa_flight_c-price
wa_flight_c-currency
wa_flight_c-planetype
wa_flight_c-seatsmax
wa_flight_c-seatsocc
wa_flight_c-paymentsum
wa_flight_c-seatsmax_b
wa_flight_c-seatsocc_b
wa_flight_c-seatsmax_f
wa_flight_c-seatsocc_f.
(C) SAP AG
BC401
2-36
Contents:
Introduction and advantages of internal tables
Defining internal tables
Internal table operations
Notes on performance
Special internal tables
SAP AG 2002
(C) SAP AG
BC401
3-1
SAP AG 2002
(C) SAP AG
BC401
3-2
and
Data Types
ts in
Data Objec
Detail
Using
Internal
Tables
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
3-3
Introduction
Introduction and
and advantages
advantages of
of internal
internal tables
tables
Definition
Definition
Operations
Operations
Special
Special situations
situations
Notes
Notes on
on performance
performance
SAP AG 2002
(C) SAP AG
BC401
3-4
Structures
ABAP
program
Internal table
At runtime, the runtime system allocates
memory for the lines in the table as needed
(dynamic table extension)
SAP AG 2002
Internal tables are data objects that allow you to store datasets with a fixed structure in memory. The
data is stored line by line in memory. Each line has the same structure.
You can also refer to each component in a line as a column in the internal table. You refer to each line in
the internal table as a table line or table entry.
Internal tables are dynamic data objects - that is, they can hold any number of lines of a fixed type. The
number of lines in an internal table is limited only by the capacity of the specific system with which you
are working.
You can define the line type of an internal table to include elementary, structured, or even table types,
and can be as complex as you want to make it.
(C) SAP AG
BC401
3-5
Line type
AA
0017
2.572
MI
LH
0400
6.162
KM
LH
0402
5.136
KM
QF
0005
10.000
MI
SQ
0866
1.625
MI
UA
0007
2.572
MI
Index access
2
Key access
SQ 0866
Table kind
Standard table
Sorted table
Hashed table
Key definition
Key fields
Sequence
Uniqueness
SAP AG 2002
(C) SAP AG
BC401
3-6
Index tables
Table kind
STANDARD TABLE
Hashed table
SORTED TABLE
HASHED TABLE
Index access
n
Key access
Binary
search
Table scan
Hash
function
Uniqueness
NON- UNIQUE
UNIQUE | NON-UNIQUE
UNIQUE
Access by
Mostly index
Mostly key
Key only
SAP AG 2002
(C) SAP AG
BC401
3-7
Introduction
Introduction and
and advantages
advantages of
of internal
internal tables
tables
Definition
Definition
Operations
Operations
Special
Special situations
situations
Notes
Notes on
on performance
performance
SAP AG 2002
(C) SAP AG
BC401
3-8
TYPES:
local_type ...
global_type
Table
attributes
Table
attributes
Internal table
Internal table
Internal table
DATA:
t_list TYPE
DATA:
t_list TYPE ...
DATA:
t_list TYPE
global_type
global_type.
local_type
local_type.
Table
attributes
SAP AG 2002
(C) SAP AG
BC401
3-9
Attributes
DATA
or
Table kind
line_type
WITH key_def
key_def
Key
[ INITIAL SIZE n ].
global_type
Table kind
Input on screen used
to specify attributes
SAP AG 2002
To define a table type (explicitly or implicitly), you must give the type (or data object) a name, as well as
specifying a table kind, line type, and key.
If you are defining a local table type, enter the kind after TYPE and the line type after OF. You must list
the key fields after WITH.
You create and edit global types in the ABAP Dictionary. If you are defining a global table type, specify
the same information on the maintenance screens.
For table types defined in a program, you can enter the number of lines that the runtime system should
reserve when it initializes the data object, after the INITIAL SIZE addition. This makes sense if you
know exactly how many lines you will want in your table when you create it. However, if your table
needs more lines at runtime, it will not be limited in size by this addition, since the runtime system frees
the necessary memory dynamically.
(Internal tables are dynamic data objects).
(C) SAP AG
BC401
3-10
TYPES
TYPES:
BEGIN OF line_type
line_type,
...
END OF line_type.
line_type
Local structure
DATA
DATA:
structure
structure TYPE ...
Table type
... name LIKE table_kind
OF
line_type
line_type
structure
WITH key_def
WITH key_def
[ INITIAL SIZE n ].
[ INITIAL SIZE n ].
SAP AG 2002
To specify the line type of an internal table, you can use all the local and global data types or data
objects.
Internal tables are most frequently used to display contents of the database tables. Normally, non-nested
structured data types are used for this.
If you use a line type, you must use a statement in the form: TYPE table_kind OF line_type,
where table_kind is the kind of table (to be discussed later) and line_type is the name of the
structure type you are using.
If you use structure (data object), you must use a statement in the form: LIKE table_kind OF
line_type, where structure is the name of the structure object you are using.
(C) SAP AG
BC401
3-11
TYPES:
itabtype TYPE table_kind
OF
line_type
WITH key_def
key_def
[ INITIAL SIZE n ].
DATA:
t_name TYPE itabtype.
table_kind
STANDARD TABLE
SORTED
HASHED
TABLE
TABLE
key_def
[NON-UNIQUE] { KEY col1 ... coln |
DEFAULT KEY }
{UNIQUE | NON-UNIQUE} KEY col1 ...coln
UNIQUE KEY col1 ... coln
SAP AG 2002
There are three parameters that you use to specify a table kind for your internal table: STANDARD
TABLE, SORTED TABLE and HASHED TABLE
You specify the table key with the WITH key_def addition. key_def includes the names of all the
key fields in order and specifies whether the key is to be UNIQUE or NON-UNIQUE.
The combination of the table kind and the key definition is very significant, because of the special
support that certain table kinds receive with specific types of read access. You can use any of the
following combinations:
For STANDARD tables:
Either create a user-defined key by naming the key fields after NON-UNIQUE KEY, or specify the
standard key using the WITH DEFAULT KEY addition. The standard key consists of all the fields
with character-type data types (c, n, d, t, x, string, xstring).
For SORTED tables:
List the key fields after WITH UNIQUE KEY or NON-UNIQUE KEY as appropriate.
For HASHED tables:
List the key fields after WITH UNIQUE KEY.
Alternatively, use the pseudo-component table_line, if you are specifying a table without a
structured line type, or if the entire table line is being used as the key. This will be discussed in more
detail later in the unit.
(C) SAP AG
BC401
3-12
TYPES:
BEGIN OF s_distance_ty
s_distance_ty,
carrid
TYPE s_carr_id,
connid
TYPE s_conn_id,
distance TYPE s_distance,
distid
TYPE s_distid,
END OF s_distance_ty.
Table type:
TYPES:
tt_distance_ty TYPE STANDARD TABLE
OF s_distance_ty
WITH NON-UNIQUE
KEY distance distid.
Internal table
DATA:
tt_distance_ty
tt_distance
tt_distance TYPE tt_distance_ty.
Internal table
of the table kind
STANDARD TABLE
SAP AG 2002
The above example shows the definition of an internal table (tt_distance) using a local table type
(tt_distance_ty), which itself uses a local line type (s_distance_ty).
The internal table defined here is a STANDARD table with the line type s_distance_ty. It contains
the columns carrid, connid, distance and distid.
The distance and distid fields are key fields. The key is not unique.
(C) SAP AG
BC401
3-13
carrid
DATA:
distance_ranc
TYPE SORTED TABLE
s_distance_ty
OF s_distance_ty
WITH NON-UNIQUE KEY
distid distance.
connid
distance distid
2
1
2
3
4
Sequence
LH
LH
AA
QM
0402
0400
0017
0005
6.162
6.162
2.572
10.000
KM
KM
MI
MI
Sequence
Hashed table:
carrid
DATA:
distance_buffer
distance_buffer
TYPE HASHED TABLE
s_distance_ty
OF s_distance_ty
WITH UNIQUE KEY
carrid connid.
LH
AA
QM
LH
connid
distance distid
0400
0017
0005
0402
6.162
2.572
10.000
6.162
KM
MI
MI
KM
SAP AG 2002
The above example shows the definition of a SORTED table and a HASHED table. Both tables have the
same line type as the STANDARD table on the previous slide.
Note that the contents of the table are in a different order. For SORTED tables, the sequence of the
entries in the internal table is determined by the sequence of fields in the key definition.
(C) SAP AG
BC401
3-14
DATA:
t_name TYPE TABLE
OF line_type.
Interpreted by
the system as:
Definition by
standard table type
DATA:
t_name TYPE STANDARD
STANDARD TABLE
OF line_type
WITH DEFAULT KEY
Example:
DATA:
t_sflight TYPE TABLE OF sflight.
SAP AG 2002
A standard type exists for defining standard tables with bound types. (Table type STANDARD TABLE,
key WITH DEFAULT KEY). When you create such a table, you can omit the STANDARD and WITH
DEFAULT KEY additions, since the runtime system supplies them automatically.
Note however, that the standard table type exists for data objects only. If you are defining a table type
that you want to use to provide a type for data objects, you must specify all its attributes completely.
Incomplete table types are known as generic. You can only use them to assign types to table-type
interface parameters.
(C) SAP AG
BC401
3-15
TYPE dd03l-fieldname.
Fill:
SAP AG 2002
Use an unstructured line type if you need a single-column internal table. The slide shows an example of
a single-column table with the line type field_name.
To declare an explicit key, you must use the pseudo-component table_line.
You can use internal tables with an unstructured line type in the following ABAP statement (among
others):
SET PF-STATUS .. EXCLUDING itab. (deactivate function codes dynamically)
SPLIT .. INTO TABLE itab. (split a string dynamically)
You can use a key access, for example, to ascertain whether a specific entry exists.
(C) SAP AG
BC401
3-16
Introduction
Introduction and
and advantages
advantages of
of internal
internal tables
tables
Definition
Definition
Operations
Operations
Special
Special situations
situations
Notes
Notes on
on performance
performance
SAP AG 2002
(C) SAP AG
BC401
3-17
Internal table
as a data object
Operations on one or
more lines
Editing lines
in a loop
or
( MOVE )
Insert
( INSERT )
( CLEAR )
Keep memory available
Read
( READ
Copy
Initialize
( FREE )
Release memory
Initialize
( DELETE )
Insert summated
LOOP ...
* command block
ENDLOOP.
( COLLECT )
=,<>,><,<=,<=,>,<
Sort
sequentially
)
Change ( MODIFY )
Delete
Edit lines
( SORT )
(C) SAP AG
BC401
3-18
n
<condition>
[ n1 ... n2 ]
Copying process
Field symbol
Direct access by
dereferenced pointer
Insert
using table
SAP AG 2002
Almost all line operations and loop processing statements offer you several options for specifying the
target set of records to be processed. You can specify these target records by declaring a key or index, by
formulating a condition that applies to some of the columns, or by specifying an index interval. Your use
of these options is limited only by the table kind you have chosen.
Example: You cannot specify a line in a hashed table using an index.
When accessing table rows, you have two possibilities for a number of line operations and for loop
processing: You can either copy the data into a structure with the same type as the line type of the
internal table, or you can set a pointer to a table line and access the data in that line directly.
In particular, when you insert table lines, you can pass the data to be inserted using another internal
table.
Note that all statements either set a return value or trigger a runtime error. If a return code has been set, it
is stored in the sy-subrc field after the statement has been executed. Runtime errors are only triggered
if the data passed at runtime are crucial in determining whether or not the operation can be performed.
Example:
You try to insert a new line into a SORTED table using an index. If you insert the new line in exactly the
right place in a sorted table, the system performs the operation. If not, the system returns a runtime error.
(C) SAP AG
BC401
3-19
<fs>
var_a
<fs>
var_a
Assigning a value to a data object
using a field symbol:
<fs>
<fs> = 77.
var_a
77
Time
SAP AG 2002
You can create a pointer to a data object in ABAP using a field symbol.
First, declare a data object using the FIELD-SYMBOLS statement. This data object can contain a pointer
to another data object at runtime. Where possible, you should give the field symbol the same type as the
data object (TYPE i, in this example).
Note that the angle brackets (<>) are part of the name of the field symbol: In this example, the name is
<fs>.
To point a field symbol at a data object, you must assign it to the object data_object using the
ASSIGN data_object TO <fs> statement.
You can use the field symbol to access the content of the data object to which it points - either to read or
to change this content.
You can "redirect" a field symbol to a different data object at runtime using the ASSIGN statement.
(C) SAP AG
BC401
3-20
<fs>
it_sflight
WRITE <fs>-connid.
<fs>-carrid = 'LH'.
<fs>
it_sflight
SAP AG 2002
In the above example, a field symbol is assigned the line type of an internal table. This makes it possible
to assign a table line to this field symbol. The syntax required for this is discussed later in this unit.
After a field symbol has been assigned a line, it is also possible to access the individual column values of
the assigned line.
As well as being able to read the data contents, you can also change the contents of the individual
components.
(C) SAP AG
BC401
3-21
Insert
Key from "wa"
specifies the line
itab
wa
INSERT
INSERT wa INTO TABLE itab.
itab
wa
INSERT
INSERT wa INTO itab INDEX n.
INSERT
INSERT LINES
LINES OF
OF itab1
itab1
[n1]
[n2]
itab2
[ FROM n1 TO n2 ]
target.
n
Only if itab1 is
an index table
target
INTO TABLE itab2.
n
SAP AG 2002
(C) SAP AG
BC401
3-22
Index
INTO wa [ options ].
READ TABLE itab INDEX
INDEX n INTO
[ options ]
COMPARING
Beliebige
Any field
Feldliste
list
comp_list
TRANSPORTING trans_list
comp_list
f1 ... fm
ALL FIELDS
trans_list
f1 ... fk
NO FIELDS
SAP AG 2002
You can read single table lines from index tables using the READ TABLE itab INDEX n INTO
wa statement. After INDEX, enter the index of the line you want to read. If the system was able to read
the line, it sets the return code to sy-subrc = 0 and stores the data from the line in wa. The total
number of lines is then in sy-tfill, the length of the lines in sy-tleng. If the system could not
read the line, the return code sy-subrc is unequal to 0. In this case, the content of wa is not changed.
Use the option TRANSPORTING addition to specify the columns for which you want to transport data:
If you do not want to read any data, but simply want to ascertain whether or not line n exists
(evaluating the return value sy-subrc), use the TRANSPORTING NO FIELDS addition.
If you want to read some of the columns in the line only, specify them after TRANSPORTING.
Separate each column name with a space.
You can use the optional addition COMPARING f1 ... fm to ascertain whether or not the line to be
read n has specific column contents: To do this, copy the value of all columns that point to the records
you want to read, into wa and list the columns after the COMPARING addition to the READ statement. If
the system was able to read the line and if all the columns listed contain the values stored in wa, it sets
the return code sy-subrc to zero. If the system was able to read the line, but if one or more of the
columns does not contain the value stored for it in wa, it sets the return code sy-subrc to two. If it
could not read the line, it sets the return code to greater than two.
The COMPARING ALL FIELDS addition provides a shorter syntax for comparing all the columns.
(C) SAP AG
BC401
3-23
itab
wa
Explicit table key
Any content from field list
search_clause
Table key
FROM wa1
WITH TABLE KEY k1 = f1 ... kn = fn
Any field
contents
SAP AG 2002
You can read individual lines from any kind of table using READ TABLE itab key INTO wa. Use
either a table key, or a comparison for some of the columns, as the search criterion key.
If you want to use a table key, you have two options:
Copy the key field values of the entry you want to read into the work area wa1 and use READ TABLE
itab FROM wa1 INTO wa. Provided sy-subrc = 0, the system stores the result of the READ
statement in the work area wa. Note that the values in wa1 that you have not explicitly filled contain
appropriately-typed initial values. Thus, the READ TABLE itab FROM wa1 statement searches
for a line that has initial values in the key fields that were not declared explicitly.
Note:
You can also use a single work area wa for both declaring the key fields and receiving the result:
READ TABLE itab FROM wa INTO wa.
Evaluate the key fields explicitly using the call READ TABLE itab WITH TABLE KEY k1 =
f1 ... kn = fn statement. In this case, you must fill all the key fields.
You can specify a formulated search condition to be applied to any columns using READ TABLE itab
WITH KEY ....
However, you can only use dynamically formulated read accesses using the key and the READ TABLE
itab FROM wa statement.
(C) SAP AG
BC401
3-24
itab
Key
<fs>
or
Index
INDEX n
Index
ASSIGNING <<fs>.
>
key
Key
-field_1 ...
<fs>
WRITE: / <fs><FS>-field_1,
Same as when reading into a work area
SAP AG 2002
You can use either a work area or a field symbol to access the individual lines in a table you want to
read.
To use a field symbol, first define it using FIELD-SYMBOLS <fs>. Give it the same type as the line
type of the internal table that you want to read.
Example: FIELD-SYMBOLS <fs> LIKE LINE OF itab.
Set the pointer to the correct line using the ASSIGNING <fs> addition instead of INTO. You can use
any search criterion you want.
You can access the components of the structure directly using the component names in the line type:
You can directly address elementary components in the line type using <fs>-field_1.
If the line type contains structured components (a structure or internal table),
<fs>-component_name points to the entire structured component. To access the sub-components
of this structured component, you need another field symbol.
Note:
If you are searching for a specific string in an internal table, you can also use the SEARCH statement. For
more details, refer to the keyword documentation for the SEARCH statement.
(C) SAP AG
BC401
3-25
itab
wa
[ TRANSPORTING
TRANSPORTING f1 ... fn ].
itab
wa
itab
WHERE
log_expr.
wa
TRANSPORTING f1 f2 ...
WHERE log_expr.
SAP AG 2002
The MODIFY TABLE itab FROM wa statement allows you to change the content of one line of the
internal table itab. The runtime system specifies the line to be changed using the key values from the
work area wa and changes the non-key fields using the other fields. If your table has a non-unique key,
the system changes the first entry only (using a linear search algorithm in STANDARD tables, and a
binary search algorithm in SORTED tables). If you want to change only some of the fields (that is,
columns) in a line, you must specify these after TRANSPORTING.
You can change the nth line in an index table using MODIFY itab FROM wa INDEX n. Note that
all the fields of the structure wa will be copied. Since changes to key fields in SORTED and HASHED
tables can cause non-catchable runtime errors, you must use the TRANSPORTING addition in this case.
If you want to make the same changes to several lines in a table, use the MODIFY itab FROM wa
TRANSPORTING f1 f2 ... WHERE log_expr statement. Specify all the columns to be changed
after TRANSPORTING. You must place the new values for these columns in the work area wa. Specify a
condition for the line using the WHERE clause.
(C) SAP AG
BC401
3-26
Key
itab
<fs>
1
or
2
<fs>-field_1 = ...
Index
key
2
<
fs>-field_1 =
<FS>-field_1
Index
ASSIGNING <fs>.
Key
...
SAP AG 2002
Instead of changing an individual line in a table using MODIFY, you can also change it using field
symbols. First use READ TABLE ... ASSIGNING <fs> to assign a field symbol to the line to be
changed. Then change the components directly using the field symbol components <fs>-field_1 =
....
When you assign the field symbol using READ TABLE ... ASSIGNING you can specify the line to
be read using a key (WITH TABLE KEY), index (for index tables), or a condition (WITH KEY).
Note that you cannot change key fields in SORTED or HASHED tables. - trying to do so causes a runtime
error.
(C) SAP AG
BC401
3-27
Delete
* fill workarea "wa"
Table key
itab
wa
key
Explicit
FROM wa
WITH TABLE KEY
k1 = f1 ... kn = fn
itab
n
WHERE
log_expr.
SAP AG 2002
Use the READ TABLE itab INDEX n INTO wa statement to delete single table lines from index
tables. Specify the line you want to delete using the table key. There are two ways of doing this:
Copy the key field values of the entry you want to delete into the work area wa and use DELETE
TABLE itab FROM wa.
Fill the key fields directly in the DELETE statement using the WITH TABLE KEY k1 = f1 ...
kn = fn addition.
You can delete the nth line from the index table itab using DELETE itab INDEX n
If you want to delete several lines from an internal table, use the DELETE itab WHERE log_expr
statement. The condition that specifies the lines you want to delete is declared in log_expr, in the
WHERE clause (where log_expr is any logical expression applied to the columns).
(C) SAP AG
BC401
3-28
Loop Processing
result
itab
wa
result
INTO wa
ASSIGNING <fs>
<fs>
[ WHERE log_expr ] } .
...
ENDLOOP.
ENDLOOP
Index table:
sy-tabix contains line
index of current line
SAP AG 2002
Use the LOOP AT itab result ... ENDLOOP statement to perform loop processing on the lines
of the internal table itab. The system then executes the statement block between LOOP AT itab
... and ENDLOOP for each loop pass. result stands for:
INTO wa:
The system copies the table line it has processed in each loop pass into the work area wa
ASSIGNING <fs>:
The relevant line is assigned to the field symbol <fs>.
With both variants you can use the TRANSPORTING NO FIELDS addition. No data is copied. Use this
addition if, for example, you simply want to determine the number or indexes of the lines processed by
the loop.
Specify the number of lines that the loop is to process using a WHERE clause (condition for any
columns).
In an index table, limit the number of lines processed in the loop by declaring an index interval.
While the loop is being processed, the system field sy-tabix contains the index of the table row of the
current loop pass. The total number of lines is in sy-tfill, the length of the lines in sy-tleng.
Note that in index tables, you can perform all the line operations (which you previously performed on
the line specified in the INDEX n addition) without this addition in the loop. The operation is then
performed on the current line.
(C) SAP AG
BC401
3-29
Overview of Operations
Standard table
Sorted table
Hashed table
SORT
Index access
INSERT
Sort
sequence
could be
violated
READ TABLE
MODIFY
DELETE
LOOP AT
Key access
No index
accesses to
hashed
tables
Append to end of
table
INSERT
READ TABLE
MODIFY
DELETE
LOOP AT
SAP AG 2002
Index accesses (such as APPEND, INSERT ... INDEX, LOOP AT ... FROM ... TO) are
possible for standard and sorted tables. However, caution is advised when using INSERT or APPEND on
sorted tables; this would violate the sort sequence and cause a runtime error.
You can use the SORT statement to sort standard and hashed tables. Sorted tables are sorted by the
runtime system.
You can use key accesses with any table type, but their effect differs. A key access with INSERT has the
same effect on standard tables as an APPEND, that is the relevant line is appended to the end of the table.
In a sorted table however, the record is inserted in accordance with the sort sequence. In the case of a
hashed table, the line is appended, but the system also changes the hash index internally.
(C) SAP AG
BC401
3-30
Introduction
Introduction and
and advantages
advantages of
of internal
internal tables
tables
Definition
Definition
Operations
Operations
Special
Special situations
situations
Notes
Notes on
on performance
performance
SAP AG 2002
(C) SAP AG
BC401
3-31
itab
itab
As well as the internal tables we have discussed, you can define internal tables with a header. These
consist of a pair of components - the internal table itself (the body) and the work area (header), with the
same line type. The header and the body have the same name, which sometimes simplifies the syntax for
table accesses.
There are several possible syntax variants used to define internal tables with header lines, some of which
are shown in the slide.
Internal tables with header lines are the oldest form of internal table.
However, note that
Many statements have a different effect on internal tables with a header than they would on normal
internal tables. You can then address the body separately using "[]" .
Example:
The CLEAR itab statement initializes only the header line, whereas in an internal with no header, it
initializes the content of the entire table.
You can delete the body of an internal table with a header using CLEAR itab[] or REFRESH
itab.
You cannot use internal tables with a header line in an object-oriented environment - that is, within
classes or interfaces.
(C) SAP AG
BC401
3-32
DATA:
so_carr LIKE
RANGE
RANGE OF
OF carrid.
sign(1)
TYPE c
option(2)
TYPE c
low LIKE
carrid
high LIKE
carrid
SAP AG 2002
Use the SELECT-OPTION statement to create an internal table with a header, for which the runtime
system automatically creates an input dialog for value sets for a selection screen. The system
automatically inserts the appropriate entries in the internal table, from the user input. For more details,
refer to the keyword documentation for the SELECT-OPTIONS statement.
As of SAP R/3 Basis Release 4.6A onwards, you can use the RANGE OF addition to the TYPES and
DATA statements to define a corresponding (internal) table without a header line.
(C) SAP AG
BC401
3-33
Introduction
Introduction and
and advantages
advantages of
of internal
internal tables
tables
Definition
Definition
Operations
Operations
Special
Special situations
situations
Notes
Notes on
on performance
performance
SAP AG 2002
(C) SAP AG
BC401
3-34
Table kind
STANDARD
SORTED
HASHED
Table scan
Binary
search
Hash
algorithm
key
Must be completely
qualified
Table kind
STANDARD
SORTED
HASHED
key
Complete/part key
leftleft-aligned without gaps
By qualified key
Binary
search
Table scan
Table
scan
Table
scan
Any component
condition
SAP AG 2002
Whenever you want to read individual table lines by declaring a complete key, use the READ TABLE
... WITH TABLE KEY statement (fastest single record access by key). The runtime system supports
this syntax variant especially for SORTED and HASHED tables. If the table is a STANDARD table, the
runtime system performs a table scan.
The same applies if you have copied the values from all key fields of the entry to be read into the work
area wa and are then use READ TABLE itab FROM wa.
The runtime system carries out the syntax variant READ TABLE ... WITH KEY (read an entry after
applying any condition) using a table scan.
The only exception to this rule applies to SORTED tables, if you fill the first n key fields with "=" (no
gaps), where n <= number of key fields.
With standard tables however, you can also sort correspondingly using SORT and then use the BINARY
SEARCH addition.
Summary:
Whenever possible, use READ TABLE ... WITH TABLE KEY or the variant with a
correspondingly-filled work area.
If you need to use READ TABLE ... WITH KEY, make your internal table a SORTED table.
(C) SAP AG
BC401
3-35
Table kind
STANDARD
SORTED
HASHED
log_expr
First n key fields filled
with "=" without gaps
Table scan
Table scan
Table scan
SAP AG 2002
The runtime system generally processes loops with a WHERE clause by performing a table scan - that is,
determining whether the condition in the WHERE clause is true for each line in the table.
SORTED tables are the only exception to this rule. For these, the runtime system optimizes the runtime
under the following condition:
In the WHERE clause, the first n key fields are filled with a "=" (no gaps). (n is less than or equal to the
number of all key fields). As a result, the loop is only performed on the lines that match the condition in
the WHERE clause. Since the table is sorted, the first line can be specified to optimize performance at
runtime (using a binary search).
(C) SAP AG
BC401
3-36
CONNID CITYFROM
AA
LH
LH
UA
UA
64
400
2407
941
3516
SAN FRANCISCO
FRANKFURT
BERLIN
FRANKFURT
NEW YORK
...
...
...
...
...
...
CARRID
LH
LH
UA
UA
AA
CONNID CITYFROM
2407
400
941
3516
64
BERLIN
FRANKFURT
FRANKFURT
NEW YORK
SAN FRANCISCO
Index-controlled loop:
LOOP AT ... INTO ...
FROM startline to endline.
...
ENDLOOP.
...
...
...
...
...
...
SAP AG 2002
To recap:
If you program a loop through a standard table to match a specific field criterion, the runtime system
always executes a table scan.
You can use the algorithm described here to program the runtime behavior of sorted tables:
First you must sort the standard table by the desired criterion, so that you can subsequently ascertain the
starting and end points in a binary search.
(The line indexes are available in the system field sy-tabix.)
Finally, you can use these values to program an index-controlled loop.
Since the SORT and READ TABLE statements require additional runtime, this procedure is only useful
if the loop can be repeated several times according to the field criterion.
Summary:Use SORTED tables if you want to implement partial sequential loops on internal tables
(where the first n key fields are filled with "=") or use the above algorithm.
(C) SAP AG
BC401
3-37
<fs2>
Copy
wa1
<fs1>
Copy
col1
col2
col3
col4
itab
col1
col2
col3
col4
SAP AG 2002
Instead of READ TABLE ... INTO, you can use the READ TABLE ... ASSIGNING variant.
This offers better performance at runtime for pure read accesses with a line width greater than or equal to
1000 bytes. If you then change the read line using MODIFY, READ ... ASSIGNING already
improves runtime with a line width of 100 bytes.
The same applies to LOOP ... INTO in comparison with LOOP ... ASSIGNING. The LOOP
... ASSIGNING variant offers better performance at runtime for any loop of five loop passes or more.
Both field symbol variants are much faster than work area variants, in particular when you use nested
internal tables. This is because, if you use work areas instead, the whole inner internal table is copied
(unless you prevent this by using a TRANSPORTING addition).
Always assign a type to field symbols, if you know their static type (again, for performance reasons).
Note:
If you use READ TABLE ... ASSIGNING the field symbol points to the originally assigned table
line, even after the internal table has been sorted.
Note that when using field symbols, you cannot change key fields in SORTED or HASHED tables. Trying
to do so causes a runtime error.
The following restrictions apply to LOOP ... ASSIGNING <fs>:
You cannot use the SUM statement in control level processing.
You cannot reassign field symbols within the loop. The statements ASSIGN do TO <fs> and
UNASSIGN <fs> will cause runtime errors.
(C) SAP AG
BC401
3-38
SAP AG 2002
(C) SAP AG
BC401
3-39
ZBC401_##_SPLIT_ITAB
Template:
SAPBC401_DTOS_SPLIT_STRING
Model solution:
SAPBC401_TABS_SPLIT_ITAB
Copy your solution for the exercise in the chapter Data Types and Data Objects in
Detail, ZBC401_##_SPLIT_STRING, or the corresponding model solution
SAPBC401_DTOS_SPLIT_STRING and give it the new name
ZBC401_##_SPLIT_ITAB.
1-2
1-3
Define a single-column internal table of the type Standard. The column component is
to have the data type string (suggested name: it_sets).
1-4
Change the SPLIT statement so that always one partial character string that contains a
data record is placed into a row of its internal table.
(C) SAP AG
BC401
3-40
1-5
(C) SAP AG
Ensure that your internal table containing the partial character strings is used for the
subsequent splitting of the individual data record and output of the components in a
loop.
BC401
3-41
Exercise 2 - Optional
Unit: Using Internal Tables
Topic:
Table Types
Program:
Template:
SAPBC401_TABS_SPLIT_ITAB
Model solution:
SAPBC401_TABS_TABKIND
2-2
2-3
Define an internal table in such a way that it can contain flight data sorted by airline,
flight number, and flight date (suggested name it_flights).
Insert the separated data records (contents of the structure wa_flight) into this
internal table, instead of displaying them. (You can still use the output statement later.)
Make use of the return value sy-subrc for the INSERT statement to ascertain
whether or not a data record appears twice. For this, you must have defined the key of
your internal table accordingly.
Define an additional internal table for the data records that appear twice (suggested
name it_doubles).
Insert the duplicate data records into this internal table.
(C) SAP AG
BC401
3-42
2-4
(C) SAP AG
Display the contents of both internal tables with the flight data.
BC401
3-43
Exercise 3 - Optional
Unit: Using Internal Tables
Topic:
Program:
Template:
SAPBC401_TABS_TABKIND
Model solution:
SAPBC401_TABS_PROCESS_DATA
3-2
Define a selection screen parameter for entering the key date (suggested name
pa_date).
Specify the default value of the key date as 30 days in the future.
The user must still be able to choose the key date. Error message 085 of the message
class bc401 is to be displayed if the selected key date is in the past.
3-3
Make sure that the data is first displayed sorted by flight date.
3-4
Ensure that the individual flight dates of the internal table it_flights are displayed
in color according to the following criteria: Use the FORMAT COLOR col_...
statement and load the type group col. (You can reverse any color set using the
FORMAT RESET statement.)
Display flights that occurred in the past with the background color
col_negative.
(C) SAP AG
BC401
3-44
Display flights that occurred between todays data and the key date with the
background color col_total.
Display flights that occurred in the past with the background color
col_positive.
3-5
Define a selection screen check box for displaying the data with the standard tool SAP
Grid Control (suggested name pa_alv, addition AS CHECKBOX).
Ensure that the data is only displayed in the usual ABAP list if the user does not check
the SAP Grid Control box.
Otherwise, proceed as follows:
3-5-1 Call the function module BC401_ALV_LIST_OUTPUT. Terminate the
program if the function module raises an exception. (In this case, there is a
problem with the system configuration.)
Detailed information on using the SAP Grid Control is not
part of this course. For this reason, you use a function
module that encapsulates all the necessary technical details,
which you can treat as a black box.
For more information on the SAP Grid Control, see:
The online documentation
The example programs under
Environment Examples
Control Examples
(C) SAP AG
Logical condition
Color value
col_negative
col_total
BC401
3-45
col_positive
(C) SAP AG
BC401
3-46
REPORT
sapbc401_tabs_split_itab.
TYPES:
BEGIN OF st_flight_c,
mandt(3)
TYPE c,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate(8)
TYPE n,
price(20)
TYPE c,
currency(5)
TYPE c,
planetype(10)
TYPE c,
seatsmax(10)
TYPE n,
seatsocc(10)
TYPE n,
paymentsum(22) TYPE c,
seatsmax_b(10) TYPE n,
seatsocc_b(10) TYPE n,
seatsmax_f(10) TYPE n,
seatsocc_f(10) TYPE n,
END OF st_flight_c,
BEGIN OF st_flight,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate
TYPE d,
price(9)
TYPE p DECIMALS 2,
currency(5)
TYPE c,
planetype(10) TYPE c,
seatsmax
TYPE i,
seatsocc
TYPE i,
END OF st_flight.
CONSTANTS c_number TYPE i VALUE 30.
(C) SAP AG
BC401
3-47
DATA:
datastring
TYPE string,
set_string
TYPE string,
TYPE st_flight.
DATA:
it_sets TYPE STANDARD TABLE OF string
WITH NON-UNIQUE DEFAULT KEY
INITIAL SIZE c_number.
START-OF-SELECTION.
CALL FUNCTION 'BC401_GET_SEP_STRING'
EXPORTING
im_number
= c_number
IM_TABLE_NAME
= 'SFLIGHT'
IM_SEPARATOR
= '#'
IM_UNIQUE
= 'X'
IMPORTING
ex_string
= datastring
EXCEPTIONS
no_data
= 1
OTHERS
= 2.
IF sy-subrc <> 0.
MESSAGE a038(bc401).
ENDIF.
(C) SAP AG
BC401
3-48
(C) SAP AG
BC401
3-49
Solution 2 - Optional
Unit: Using Internal Tables
Topic:
REPORT
Table Types
sapbc401_tabs_tabkind.
TYPES:
BEGIN OF st_flight_c,
mandt(3)
TYPE c,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate(8)
TYPE n,
price(20)
TYPE c,
currency(5)
TYPE c,
planetype(10)
TYPE c,
seatsmax(10)
TYPE n,
seatsocc(10)
TYPE n,
paymentsum(22) TYPE c,
seatsmax_b(10) TYPE n,
seatsocc_b(10) TYPE n,
seatsmax_f(10) TYPE n,
seatsocc_f(10) TYPE n,
END OF st_flight_c,
BEGIN OF st_flight,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate
TYPE d,
price(9)
TYPE p DECIMALS 2,
currency(5)
TYPE c,
planetype(10) TYPE c,
seatsmax
TYPE i,
seatsocc
TYPE i,
END OF st_flight.
(C) SAP AG
BC401
3-50
TYPE string,
set_string
TYPE string,
TYPE st_flight.
DATA:
it_sets TYPE STANDARD TABLE OF string
WITH NON-UNIQUE DEFAULT KEY
INITIAL SIZE c_number,
it_flights TYPE SORTED TABLE OF st_flight
WITH UNIQUE KEY carrid connid fldate
INITIAL SIZE c_number,
it_doubles TYPE SORTED TABLE OF st_flight
WITH NON-UNIQUE KEY carrid connid fldate
INITIAL SIZE c_number.
START-OF-SELECTION.
CALL FUNCTION 'BC401_GET_SEP_STRING'
EXPORTING
im_number
= c_number
IM_TABLE_NAME
= 'SFLIGHT'
IM_SEPARATOR
= '#'
IM_UNIQUE
= space
IMPORTING
ex_string
= datastring
EXCEPTIONS
no_data
(C) SAP AG
= 1
BC401
3-51
OTHERS
= 2.
IF sy-subrc <> 0.
MESSAGE a038(bc401).
ENDIF.
(C) SAP AG
BC401
3-52
* output:
*********
LOOP AT it_flights INTO wa_flight.
WRITE: /
wa_flight-carrid,
wa_flight-connid,
wa_flight-fldate DD/MM/YYYY,
wa_flight-price CURRENCY wa_flight-currency,
wa_flight-currency,
wa_flight-planetype,
wa_flight-seatsmax,
wa_flight-seatsocc.
ENDLOOP.
SKIP.
WRITE: / 'duplicate data records:'(dob) COLOR COL_HEADING.
LOOP AT it_doubles INTO wa_flight.
WRITE: /
wa_flight-carrid,
wa_flight-connid,
wa_flight-fldate DD/MM/YYYY,
wa_flight-price CURRENCY wa_flight-currency,
wa_flight-currency,
wa_flight-planetype,
wa_flight-seatsmax,
wa_flight-seatsocc.
ENDLOOP.
(C) SAP AG
BC401
3-53
Solution 3 - Optional
Unit: Using Internal Tables
Topic:
REPORT sapbc401_tabs_process_data.
TYPE-POOLS col.
TYPES:
BEGIN OF st_flight_c,
mandt(3)
TYPE c,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate(8)
TYPE n,
price(20)
TYPE c,
currency(5)
TYPE c,
planetype(10)
TYPE c,
seatsmax(10)
TYPE n,
seatsocc(10)
TYPE n,
paymentsum(22) TYPE c,
seatsmax_b(10) TYPE n,
seatsocc_b(10) TYPE n,
seatsmax_f(10) TYPE n,
seatsocc_f(10) TYPE n,
END OF st_flight_c,
BEGIN OF st_flight,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate
TYPE d,
price(9)
TYPE p DECIMALS 2,
currency(5)
TYPE c,
planetype(10) TYPE c,
seatsmax
(C) SAP AG
TYPE i,
BC401
3-54
seatsocc
TYPE i,
END OF st_flight.
CONSTANTS c_number TYPE i VALUE 30.
DATA:
datastring
TYPE string,
set_string
TYPE string,
TYPE st_flight.
DATA:
it_sets TYPE STANDARD TABLE OF string
WITH NON-UNIQUE DEFAULT KEY
INITIAL SIZE c_number,
it_flights TYPE SORTED TABLE OF st_flight
WITH UNIQUE KEY fldate carrid connid
INITIAL SIZE c_number,
it_doubles TYPE SORTED TABLE OF st_flight
WITH NON-UNIQUE KEY fldate carrid connid
INITIAL SIZE c_number,
LOAD-OF-PROGRAM.
pa_date = sy-datum + 30.
(C) SAP AG
BC401
3-55
AT SELECTION-SCREEN.
IF pa_date < sy-datum.
MESSAGE e085(bc401).
ENDIF.
START-OF-SELECTION.
CALL FUNCTION 'BC401_GET_SEP_STRING'
EXPORTING
im_number
= c_number
IM_TABLE_NAME
= 'SFLIGHT'
IM_SEPARATOR
= '#'
im_unique
= space
IMPORTING
ex_string
= datastring
EXCEPTIONS
no_data
= 1
OTHERS
= 2.
IF sy-subrc <> 0.
MESSAGE a038(bc401).
ENDIF.
BC401
3-56
wa_flight_c-connid
wa_flight_c-fldate
wa_flight_c-price
wa_flight_c-currency
wa_flight_c-planetype
wa_flight_c-seatsmax
wa_flight_c-seatsocc
wa_flight_c-paymentsum.
MOVE-CORRESPONDING wa_flight_c TO wa_flight.
INSERT wa_flight INTO TABLE it_flights.
IF sy-subrc <> 0.
INSERT wa_flight INTO TABLE it_doubles.
ENDIF.
ENDLOOP.
* output:
*********
IF pa_alv = 'X'.
LOOP AT it_flights INTO wa_flight.
MOVE-CORRESPONDING wa_flight TO wa_col_flight.
IF wa_col_flight-fldate < sy-datum.
wa_col_flight-color = col_negative.
ELSEIF wa_col_flight-fldate < pa_date.
wa_col_flight-color = col_total.
ELSE.
wa_col_flight-color = col_positive.
ENDIF.
INSERT wa_col_flight INTO TABLE it_col_flights.
ENDLOOP.
LOOP AT it_doubles INTO wa_flight.
MOVE-CORRESPONDING wa_flight TO wa_col_flight.
wa_col_flight-color = col_background.
INSERT wa_col_flight INTO TABLE it_col_doubles.
(C) SAP AG
BC401
3-57
ENDLOOP.
CALL FUNCTION 'BC401_ALV_LIST_OUTPUT'
EXPORTING
it_list1
= it_col_flights
it_list2
= it_col_doubles
EXCEPTIONS
control_error = 1
OTHERS
= 2.
IF sy-subrc <> 0.
MESSAGE a702(bc401).
ENDIF.
ELSE.
LOOP AT it_flights INTO wa_flight.
IF wa_flight-fldate < sy-datum.
FORMAT COLOR = col_negative.
ELSEIF wa_flight-fldate < pa_date.
FORMAT COLOR = col_total.
ELSE.
FORMAT COLOR = col_positive.
ENDIF.
WRITE: /
wa_flight-carrid,
wa_flight-connid,
wa_flight-fldate DD/MM/YYYY,
wa_flight-price CURRENCY wa_flight-currency,
wa_flight-currency,
wa_flight-planetype,
wa_flight-seatsmax,
wa_flight-seatsocc.
ENDLOOP.
FORMAT RESET.
SKIP.
WRITE: / 'duplicate data records:'(dob) COLOR COL_HEADING.
(C) SAP AG
BC401
3-58
(C) SAP AG
BC401
3-59
Contents:
Techniques for calling programs
Memory model
Techniques for passing data
Use
SAP AG 2002
(C) SAP AG
BC401
4-1
SAP AG 2002
(C) SAP AG
BC401
4-2
and
Data Types
ts in
Data Objec
Detail
al
Using Intern
Tables
Calling
d
Programs an
at
Passing D a
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
4-3
Calling
Calling programs
programs
Memory
Memory management
management
Passing
Passing data
data
SAP AG 2002
(C) SAP AG
BC401
4-4
Calling Programs
Time
Main
memory
Main
memory
1
New program
Insert program
Insertion
2
Restart
End insert
Program 1
Program 2
SAP AG 2002
There are two ways of starting an ABAP program from another ABAP program that is already running:
The called
program is inserted, that is the current program is interrupted to run the new one. The called
program is executed, and afterwards, processing returns to the program that called it.
The current program is terminated and the called program is started.
Complete ABAP programs within a single user session can only run sequentially. We refer to this
technique as sequential calling.
If you want to run functions in parallel, you must use function modules. For further information about this
technique, refer to the course BC415 (Communication Interfaces in ABAP) or the documentation for the
CALL FUNCTION ... STARTING NEW TASK ... statement.
(C) SAP AG
BC401
4-5
...
SUBMIT prog_name_2.
...
Program 2
Restart
prog_name_2
PROGRAM ...
...
List
F3
...
SUBMIT prog_name_2
AND RETURN.
...
Insertion
prog_name_2
PROGRAM ...
...
List
F3
Insertion
...
SUBMIT prog_name_2
VIA SELECTION-SCREEN
AND RETURN.
...
Selection Screen
prog_name_2
Liste
PROGRAM ...
...
F3
F3
SAP AG 2002
(C) SAP AG
BC401
4-6
Calling a Transaction
Program 1
Program 2: Transaction
TCODE
Restart
...
LEAVE TO TRANSACTION 'T_CODE'
[AND SKIP FIRST SCREEN].
...
1. Screen
2. Screen
F15
Insertion
...
CALL TRANSACTION 'T_CODE'
[AND SKIP FIRST SCREEN].
...
1. Screen
2. Screen
F15
SAPM t_name
...
LEAVE PROGRAM.
...
SAPM t_name
...
LEAVE PROGRAM.
...
SAP AG 2002
With the LEAVE TO TRANSACTION 'T_CODE' statement you terminate the current program and start
the transaction with transaction code T_CODE. The statement is the equivalent to entering /n<T_CODE>
in the command field.
CALL TRANSACTION 'T_CODE' allows you to insert ABAP programs that have a transaction code.
To terminate an ABAP program, use the LEAVE PROGRAM statement. If the statement is used in a
program that you called using CALL TRANSACTION 'T_CODE' or SUBMIT prog_name AND
RETURN, the system resumes processing at the next statement after the call in the calling program.
Otherwise, the user returns to the application menu from which he or she started the program.
If you use the ... AND SKIP FIRST SCREEN addition, the system does not display the screen
contents of the first screen. However, it does process the flow logic.
If the transaction T_CODE you called with CALL TRANSACTION uses update techniques, you can use the
UPDATE... addition to specify the update technique (asynchronous (default), synchronous, or local) that
the program should use. For further information, refer to course BC414 (Programming Database
Updates) and the online documentation.
(C) SAP AG
BC401
4-7
Calling
Calling programs
programs
Memory
Memory management
management
Passing
Passing data
data
SAP AG 2002
(C) SAP AG
BC401
4-8
ABAP memory 2
ABAP memory 1
Program 1.2
Program 1.1
Program 2.1
SAP memory
SAP AG 2002
The way in which the main memory is organized from the program's point of view can be represented in
the above logical model. There is a distinction between internal and external sessions:
Generally,
an external session is connected to an R/3 window. You can create a new session by choosing
System New Session or by entering /o<T_CODE> in the command field. You can have up to six
external sessions open simultaneously in one terminal session.
External sessions are subdivided into internal sessions (placed on a stack). Each program that you run
occupies its own internal session. Each external session can contain up to nine internal sessions.
Data for a program is only visible within an internal session. The visibility of the data is generally
restricted to the relevant program.
The following slides illustrate how the stack inside an external session changes with various program calls.
(C) SAP AG
BC401
4-9
ABAP memory 1
ABAP memory 2
Program 1.1
Program 2.1
SAP memory
SAP AG 2002
(C) SAP AG
BC401
4-10
ABAP memory 2
ABAP memory 1
Program 1.2
Program 1.1
Program 2.1
SAP memory
SAP AG 2002
When you insert a program, the system creates a new internal session, which in turn creates a new program
context.
The new session is placed on the stack The program context of the calling program also remains intact.
(C) SAP AG
BC401
4-11
ABAP memory 1
ABAP memory 2
Program 1.1
Program 2.1
SAP memory
SAP AG 2002
When the called (inserted) program finishes, its internal session (the top one in the stack) is deleted.
Processing is resumed in the next-highest internal session in the stack.
(C) SAP AG
BC401
4-12
ABAP memory 2
ABAP memory 1
Program 1.1
SAP memory
SAP AG 2002
When you end a program and start a new one, there is a distinction between calling an executable program
and calling a transaction, with regard to memory areas.
(C) SAP AG
BC401
4-13
ABAP memory 2
ABAP memory 1
Program 1.1
SAP memory
SAP AG 2002
If you call an executable program using its program name (terminating the calling program), the system
deletes the internal session of the program that you are terminating (the top one from the stack).
The system creates a new internal session, which in turn creates the program context of the called program.
The new session is placed on the stack Existing program contexts remain intact. The topmost internal
session on the stack is replaced.
(C) SAP AG
BC401
4-14
ABAP memory 2
ABAP memory 1
Program 1.1
SAP memory
SAP AG 2002
(C) SAP AG
BC401
4-15
ABAP memory 2
Program 2.1
Program 1'.1
Restart
(complete
initialization)
SAP memory
SAP AG 2002
If you start a program using its transaction code (that is, if one was defined), all of the internal sessions on
the stack are deleted.
The system creates a new internal session, which in turn creates the program context of the called program.
After the call, the ABAP memory is initialized.
(C) SAP AG
BC401
4-16
Calling
Calling programs
programs
Memory
Memory management
management
Passing
Passing data
data
SAP AG 2002
(C) SAP AG
BC401
4-17
There are various ways of passing data to programs running in separate internal sessions:
You can use:
The interface of the called program (usually a standard selection screen)
ABAP memory
SAP memory
Database tables
Local files on your presentation server
The following slides deal with the first three of these methods.
For further information regarding the passing of data using database tables or the shared buffer, refer to the
documentation for the EXPORT and IMPORT statements.
For further information on transferring data between an ABAP program and a presentation server, refer to
the documentation for the function modules GUI_UPLOAD and GUI_DOWNLOAD.
(C) SAP AG
BC401
4-18
Program A
Data
Program B
SAP AG 2002
When you call ABAP programs that have a standard selection screen, you can pass data for the input fields
in the call.
There are two ways to do this:
By specifying a variant for the selection screen when you call the program
By specifying values for the input fields when you call the program
(C) SAP AG
BC401
4-19
Insert pattern
...
...
...
Other pattern
SUBMIT
SAP AG 2002
The WITH addition to the SUBMIT statement allows you to preassign values for parameters and selection
options on a standard selection screen of the called executable program. The abbreviations "EQ, NE, ...; I,
E" have the same meanings as with selection options.
If you want to pass several selections for a selection option, you can use the RANGE statement instead of
individual WITH additions. The RANGES statement creates a selection table, which you can fill as though
it were a selection option. You then pass the whole table to the executable program.
If you want to display the standard selection screen when you call the program, use the VIA
SELECTION-SCREEN addition.
When you use the SUBMIT statement, use the Pattern function in the ABAP Editor to insert an appropriate
statement pattern for the program you want to call. It automatically supplies the names of the parameters
and selection options that are available on the standard selection screen.
For further information about working with variants and about other syntax variants of the WITH addition,
refer to the documentation for the SUBMIT statement.
(C) SAP AG
BC401
4-20
ABAP memory 2
ABAP memory 1
Program 1.2
Program 1.1
Program 2.2
Program 2.1
You can use SAP memory and ABAP memory to pass data between programs.
SAP memory is a user-specific memory area for storing field values. It is only of limited value for
passing data between internal sessions. Values in SAP memory are retained for the duration of the user's
terminal session. The memory can be used between sessions in the same terminal session. You can use
the contents of SAP memory as default values for screen fields. All external sessions can use the SAP
memory.
ABAP memory is also user-specific. There is a local ABAP memory for each external session. You can
use it to exchange any ABAP variables (fields, structures, internal tables, complex objects) between the
internal sessions in any one external session.
When the user exits an external session (/i in the command field), the corresponding ABAP memory is
automatically initialized or released.
(C) SAP AG
BC401
4-21
Internal session 1
ABAP memory
PROGRAM p1 ... .
DATA: p1_spfli TYPE spfli,
it_spfli TYPE STANDARD TABLE
OF spfli.
...
EXPORT
EXPORT
wa_fli FROM p1_spfli
it_spfli
TO MEMORY ID 'MY_ID'.
MY_ID
wa_fli
it_spfli
Internal session 2
MY_ID1
...
PROGRAM p2 ... .
DATA: p2_spfli TYPE spfli,
it_spfli TYPE STANDARD TABLE
OF spfli.
...
IMPORT
IMPORT
wa_fli TO p2_spfli
it_spfli
FROM MEMORY ID 'MY_ID'.
SAP AG 2002
The EXPORT ... TO MEMORY statement allows you to copy any number of ABAP data objects with
their current values to the ABAP memory (data cluster).
The ID ... addition enables you to identify different clusters (maximum of 60 characters).
If you use a new EXPORT TO MEMORY statement for an existing data cluster, the new one will overwrite
the old.
The IMPORT ... FROM MEMORY ID ... statement allows you to copy the data from the ABAP
memory into corresponding data objects of your ABAP program.
It is also possible to only import parts of data clusters using IMPORT.
The data objects that are to receive the data from the ABAP memory cluster must have the same types in
both the calling and the called programs.
To release a data cluster, use the FREE MEMORY ID ... statement.
Bear in mind that when you call programs using transaction codes, you can only use the ABAP memory to
pass data when inserting (CALL TRANSACTION).
(C) SAP AG
BC401
4-22
SET PARAMETER ID
'CON' FIELD sdyn_conn-connid.
Program A
Airline
LH
or
Connection 400
SET
SAP memory
CAR
CON
LH
400
Program B
Airline
LH
GET
Connection 400
or
GET PARAMETER ID
'CON' FIELD sdyn_conn-connid.
SAP AG 2002
You can define memory areas (parameters) in the SAP memory in various ways:
By creating input/output fields with reference to the ABAP Dictionary. These take the parameter name
of the data element to which they refer.
Alternatively, you can enter a name in the attributes of the input/output fields.
Here, you can also choose whether the entries from the field should be transferred to the parameter
(SET), or whether the input field should be filled with the value from the parameter (GET).
To find out about the names of the parameters assigned to input fields, display the field help for the field
(F1), then choose Technical info.
You can also fill the memory areas directly using the SET PARAMETER ID 'PAR_ID' FIELD
var. statement and read them using GET PARAMETER ID 'PAR_ID' FIELD var.
Finally, you can define parameters in the Object Navigator and let the user fill them with values.
(C) SAP AG
BC401
4-23
Program 2: Transaction
...
DATA:
bi_itab TYPE TABLE OF bdcdata,
bi_wa
TYPE bdcdata.
T_CODE
bi_itab
* fill bi_itab
...
* call other program
CALL TRANSACTION 'T_CODE'
USING bi_itab.
IF sy-subrc = 0.
...
ELSE.
...
1st screen
2nd screen
F15
SAPM t_name
...
LEAVE PROGRAM.
...
SAP AG 2002
The CALL TRANSACTION 'T_CODE' USING bi_itab statement allows you to insert the
transaction T_CODE, and the screens are processed according to the internal table bi_itab.
This internal table must be typed according to the structure bdcdata and filled appropriately.
The MODE addition allows you to specify whether the screen contents should all be displayed ('A' - the
default setting), only when an error occurs ('E'), or not at all ('N').
The MESSAGES INTO mess_itab addition is used to specify where the system messages sent during
the execution of the called transaction are written.
The internal table must be typed according to the structure bdcmsgcoll.
You can find out if the transaction was executed successfully from the system field sy-subrc.
This technique is useful if, for example:
You are processing in the foreground, but the input fields have not been filled using GET parameters
You want to process the transaction in the background. In this case, you normally have to pass function
codes as well.
This technique is also one of the possible ways of transferring data from non-SAP systems.
To do so the internal table in the bdcdata format must be filled completely.
(C) SAP AG
BC401
4-24
Field name
Length
Description
Note when
filling
program
dynpro
dynbegin
fnam
fval
40
132
132
Screen number
First record
Field name
Program name
Only in 1st
Only in 1st
record on screen record on screen
Field value
Casesensitive
SAP AG 2002
Each screen that is to be processed and filled automatically in the transaction must be identified by a
line, in which only the fields program, dynpro and dynbegin are filled.
After the record that identifies the screen, use a separate bdcdata record for each field you want to
fill. These records use the table fields fnam and fval. The following fields can be filled:
Input/output fields, with data
The command field (bdc_okcode), with function codes
The cursor position field (bdc_cursor), with field names.
You also use the CALL TRANSACTION technique to transfer data from external systems.
Further information on this topic is available in the course BC420 (Data Transfer) and in the online
documentation.
(C) SAP AG
BC401
4-25
dynpro
dynbegin
0100
SAPBC401_CALD_CREATE_CUSTOMER
fnam
fval
SCUSTOM-NAME <current_name>
SCUSTOM-CITY <current_city>
BDC_OKCODE
DATA:
bdcdata
wa_bdcdata TYPE bdcdata,
it_bdcdata LIKE TABLE OF wa_bdcdata.
* fill the bdcdata-table ...
CALL TRANSACTION 'BC401_CALD_CRE_CUST'
USING it_bdcdata
MODE 'N'.
IF sy-subrc <> 0.
MESSAGE ... WITH sy-subrc.
ENDIF.
SAVE
Save
ID for command
field
SAP AG 2002
This example refers to the transaction BC401_CALD_CTA_U. If you request the creation of a new
customer entry here, the transaction BC401_CALD_CRE_CUST is inserted. This transaction has not
implemented an import from the ABAP memory, and its input fields are not set as GET parameters. The
customer data is therefore passed using an internal table and the transaction processed in the background.
If the operation is successful, the new customer data record can be entered in the waiting list.
The relevant internal table in bdcdata format is shown above. current_name is the customer
name adopted from the input field at runtime, current_city is the city.
You address the command field using BDC_OKCODE. Here you enter the function code that is triggered by
the user choosing a function key, pushbutton, or menu entry during the dialog flow (or by entering a code
directly in the command field).
(C) SAP AG
BC401
4-26
SAP AG 2002
(C) SAP AG
BC401
4-27
Contents:
Procedural programming
Object-oriented programming
Aims of the ABAP Objects programming language
SAP AG 2002
(C) SAP AG
BC401
5-1
SAP AG 2002
(C) SAP AG
BC401
5-2
ing
Programm
d
te
n
e
ri
O
cttion to Obje Internal
Introduc
Using
and
Data Types
ts in
Data Objec
Detail
rams
Calling Prog
Data
and Passing
Tables
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
5-3
Machine language
Assembler
C++
ABAP
Java
ABAP Objects
SAP AG 2002
(C) SAP AG
BC401
5-4
Procedural
Procedural programming
programming
Object-oriented
Object-oriented programming
programming
SAP AG 2002
(C) SAP AG
BC401
5-5
Data
Data
Characteristics:
Data
Data
Possibility of encapsulating
functions using modularization
Data
Function
Function
Function
Function
Function
Function
Function
Function
Function
Function
Function
Function
SAP AG 2002
Information systems were previously defined primarily by their functions: Data and functions were
stored separately and linked using input-output relationships.
(C) SAP AG
BC401
5-6
REPORT
REPORT ZABAP_DEMO.
ZABAP_DEMO.
*---------------------*---------------------TYPES:
TYPES: ...
...
Type definitions
DATA:
DATA: ...
...
Data declarations
Main program
...
...
PERFORM
PERFORM form1
form1 ...
...
Calling subroutines
CALL
CALL FUNCTION
FUNCTION 'FB1'
'FB1'
...
...
CALL
CALL FUNCTION
FUNCTION 'FB2'
'FB2'
...
...
*---------------------*---------------------FORM
FORM f1
f1 ...
...
...
...
ENDFORM.
ENDFORM.
Definition of subroutines
SAP AG 2002
A typical ABAP program consists of type definitions and data declarations, which describe the blueprint
of the data the program uses when it is executed.
To make your program more readable and for better program structure, it is recommended that you work
with modularization units (encapsulated units with functions), such as form routines or function
modules. These components can be reused in many different programs.
(C) SAP AG
BC401
5-7
Function groups
Function group 1
Global data
Function module 1
Function module 2
Function module ...
Function group 2
Global data
Subroutines
Interface
Function module 1
Function module 2
Interface
SAP AG 2002
This slide provides an overview of the main program components during program execution in an
internal session (main memory area on application server).
The loaded main program and the two function groups with their encapsulated modules (the function
modules) are both in separate memory areas.
From the main program, you can use function modules to access function group components, for
example their global data. Therefore, a function group is a unit consisting of data and functions that
manage this data.
A user "client" (here, the main program) can only access the function groups and their services using the
interface, that is the function modules. The function group acts as a "server", because it provides
services.
(C) SAP AG
BC401
5-8
FUNCTION-POOL
FUNCTION-POOL s_vehicle.
s_vehicle.
** speed
speed is
is aa global
global variable
variable
** used
used in
in the
the funtion-pool
funtion-pool
DATA:
DATA: speed
speed TYPE
TYPE I.
I.
...
...
FUNCTION
FUNCTION INC_SPEED.
INC_SPEED.
...
...
ADD
ADD imp_speed
imp_speed TO
TO speed.
speed.
ENDFUNCTION.
ENDFUNCTION.
S_VEHICLE
speed
FUNCTION
FUNCTION DEC_SPEED.
DEC_SPEED.
...
...
SUBTRACT
SUBTRACT IMP_SPEED
IMP_SPEED from
from speed.
speed.
ENDFUNCTION.
ENDFUNCTION.
inc_speed
dec_speed
get_speed
stop
FUNCTION
FUNCTION GET_SPEED.
GET_SPEED.
exp_speed
exp_speed == speed.
speed.
ENDFUNCTION.
ENDFUNCTION.
...
...
SAP AG 2002
The function group s_vehicle provides a user or client with the services inc_speed,
dec_speed, and get_speed.
These services make up the function group interface and access the internally encapsulated component
speed.
(C) SAP AG
BC401
5-9
REPORT
REPORT zvehicledemo.
zvehicledemo.
TYPES:
TYPES: ...
...
DATA:
DATA: wa_car
wa_car TYPE
TYPE ...
...
** no
no direct
direct access
access to
to speed
speed
S_VEHICLE
** use
use functions
functions of
of pool
pool
speed
CALL
CALL FUNCTION
FUNCTION 'INC_SPEED'
'INC_SPEED'
...
...
inc_speed
CALL
CALL FUNCTION
FUNCTION 'GET_SPEED'
'GET_SPEED'
...
...
dec_speed
get_speed
stop
CALL
CALL FUNCTION
FUNCTION 'STOP'
'STOP'
...
...
SAP AG 2002
(C) SAP AG
BC401
5-10
Displaying a number of
vehicles and their speed is
only possible with
additional administration
S_VEHICLE
speed
inc_speed
dec_speed
get_speed
stop
SAP AG 2002
If the main program is to work with several vehicles, this is not possible without extra programming and
administration effort.
(C) SAP AG
BC401
5-11
The ability to create multiple instances of a "class", such as a vehicle, is one of the central attributes of
object-oriented languages.
(C) SAP AG
BC401
5-12
Procedural
Procedural programming
programming
Object-oriented
Object-oriented programming
programming
SAP AG 2002
(C) SAP AG
BC401
5-13
The left part of the slide shows that, with procedural software systems, data and functions are often:
Created separately
Stored separately
Linked with input-output relations
Objects form capsules containing the data itself and the behavior of that data. Objects enable you to draft
a software solution that is a one-to-one reflection of the real-life problem area.
(C) SAP AG
BC401
5-14
Real world
SAP AG 2002
In object-oriented programming, data and functions are developed together. Object orientation focuses
on objects that represent either abstract or concrete things in the real world. They are first viewed in
terms of their characteristics, which are displayed using the object's internal structure and attributes
(data).
The behavior of objects is described through methods (functions) and events.
Consistency throughout the software development process:
The "language" used in the various phases of software development (analysis, specification, design, and
implementation) is uniform. Ideally, changes made to the design during the implementation phase will
flow back into the design automatically.
The aim is to use this concept to:
Implement processes realistically and, at the same time, better involve the modeler and developer in
the software design
Achieve optimized structuring and maintenance of the software and hence reduce the work required
(C) SAP AG
BC401
5-15
Encapsulation
Encapsulation means that the implementation of an object is hidden from other components in the
system, so that they cannot make assumptions about the internal status of the object and therefore
dependencies on specific implementations do not arise.
Polymorphism
Polymorphism (ability to have multiple forms) in the context of object technology signifies that objects
in different classes react differently to the same messages.
Inheritance
Inheritance defines the implementation relationship between classes, in which one class (the subclass)
shares the structure and the behavior defined in one or more other classes (superclasses).
Note: ABAP Objects only allows single inheritance.
(C) SAP AG
BC401
5-16
Objects behave like client/server systems: When an object calls a method of another object, it
automatically becomes the client of the other (server) object. This gives rise to two conditions:
- The client object must adhere to the protocol of the server object
- The protocol must be clearly described so that a potential client can follow it without problem
Objects normally adopt both roles Every object is a potential server object, and when it is called by a
method of another object, it becomes a client object too.
Establishing logical business and software/technical responsibilities between classes results in a true
client/server software system in which redundancy is avoided.
(C) SAP AG
BC401
5-17
** ABAP
ABAP Objects
Objects Programm
Programm
DATA:
DATA: counter
counter TYPE
TYPE i,
i,
wa
wa type
type KNA1.
KNA1.
...
...
CLASS
CLASS lcl_car
lcl_car DEFINITION.
DEFINITION.
...
...
ENDCLASS.
ENDCLASS.
*--*--- main
main program
program -----------------
As simple as possible
SAP AG 2002
ABAP Objects is not a new language, but has been developed as an extension of ABAP. It integrates
seamlessly into ABAP syntax and the ABAP programming model. All enhancements are strictly upward
compatible.
In ABAP objects, types have to be assigned more strictly than in ABAP. - for example, when defining
interface parameters for methods, you must type the parameters. The correct pass by value is then
checked by the system when the method is called.
In ABAP Objects, the ABAP language has been cleaned up. As part of this language clean up, the
system sometimes executes stricter syntax checks for previously permitted constructions and obsolete
statements are not allowed. The stricter syntax checks usually result in a syntax that should also be used
outside ABAP Objects, but where the old forms cannot be prohibited for compatibility reasons.
For further information, refer to the ABAP Objects documentation under Replacement of Obsolete
Statements.
(C) SAP AG
BC401
5-18
One feature and design aim of object-oriented languages is that business functions are held separately.
The client (in this case, the main program) uses the addresses of the objects (pointers or reference
variables) to access their encapsulated functions. Amongst other things, this concept is to improve the
structuring, reusability, and maintainability of the software.
(C) SAP AG
BC401
5-19
Requirement,
idea
Test
Iteration
Analysis and
design
Implementation
(ABAP Objects)
SAP AG 2002
In object-oriented programming, the analysis and design phase is even more important than it is for
procedural programming. The reason for this is that in object-oriented programming, decisions taken
during the analysis and design phase have even more pronounced effects on implementation than they do
in procedural programming.
(C) SAP AG
BC401
5-20
SAP AG 2002
(C) SAP AG
BC401
5-21
Contents:
Classification of objects
UML
Class diagrams
Sequence diagrams
SAP AG 2002
(C) SAP AG
BC401
6-1
SAP AG 2002
(C) SAP AG
BC401
6-2
nd Design
Analysis a ted Programming
and
Data Types
ts in
Data Objec
Detail
t-Orien
n to Objec
Introductio
al
Using Intern
Tables
rams
Calling Prog
Data
and Passing
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
6-3
Classification
Classification
UML
UML -- the
the modeling
modeling standard
standard
SAP AG 2002
(C) SAP AG
BC401
6-4
Classification of Objects
Real world
lcl_people
lcl_vehicle
In the real world, there are objects, such as various airplanes , cars, and people. Some of these objects are
very similar, that is, they can be described using the same attributes or characteristics and provide the
same functions.
Similar objects are grouped together in classes. Each class is described once, and each object is then
created in accordance with this blueprint.
A class is therefore a description of a quantity of objects characterized by the same structure and the
same behavior. For example, the vehicle "make x, ... serial number xxx" is an object of the class
"vehicle". This object is therefore a concrete instance of the class.
(C) SAP AG
BC401
6-5
Car enthusiast
Scrap merchant
Price
Make
price
make
lcl_vehicle
Equipping
equipping
- make
Color
- ...
color
- price
Type
model
Weight
weight
Doors
lcl_vehicle
doors
Wheels
wheels
PS
- equipping
Scrap value
scrapvalue
- make
- ...
- weight
- scrapvalue
- color
SAP AG 2002
In this context, abstractions are a simplified representations of complex relationships in the real world.
An actually existing object is abstracted to the significant dimensions that are to be mapped.
Insignificant details are left out in order to aid understanding of the overall system.
This example concerns cars. Software for a car enthusiast and software for a scrap merchant contain
different abstractions (classes) for these objects.
A class can contain very different objects depending on the abstraction.
While in one software system the class lcl_vehicle describes all transport vehicles (including
bikes), in another system it describes all motorized machines with wheels.
Both classes have the same name but describe different objects.
In our examples, the class lcl_vehicle describes all motorized vehicles with 4 wheels.
(C) SAP AG
BC401
6-6
Representation of a Class
lcl_vehicle
Class name
make
modell
Attributes
...
Optional, does
not have to be
Assoziationsme
specified
price
color
set_make
Methods
display_attributes
(functions)
increase_speed
...
SAP AG 2002
UML notation:
A class is represented with its name, attributes, and methods. With UML, you also have the option of
omitting either the attribute or the method part.
Attributes describe the data that can be stored in the objects in a class.
They define the state of an object.
Methods describe the functions that can be executed on the data of the object.
They contain the executable source code and therefore also represent an object's "behavior".
ABAP Objects events are not included in class diagrams.
(C) SAP AG
BC401
6-7
A class is a set of objects that have the same structure and the same behavior. A class is therefore like a
blueprint, in accordance with which all objects in that class are created.
Every object has an identity, a status (set of attribute values), and behavior (set of methods and events).
The structure and behavior of similar objects are defined in their shared class.
Identity is an attribute that distinguishes each object from all other objects. Identity is often confused
with having the same attribute values or with a unique name. Two different objects can have identical
attribute values and still not be identical.
Example:
Two coffee cups are the same height and diameter, have the same handle and are both white. Although
they look exactly the same, they are still two separate cups.
In German literature on the subject of object orientation, we often speak of instances. In object
orientation an instance is simply an object. Another synonym of object is instance.
(C) SAP AG
BC401
6-8
Classification
Classification
UML
UML -- the
the modeling
modeling standard
standard
SAP AG 2002
(C) SAP AG
BC401
6-9
Diagram types:
Class diagram
Behavior diagram, such as a sequence diagram
Component diagram
Distribution diagram
...
SAP AG 2002
UML (Unified Modeling Language) is a standardized modeling language. It is used for the specification,
construction, visualization, and documentation of models for software systems and enables uniform
communication between various users. UML does not describe the steps in the object-oriented
development process.
UML is an industry standard and has been standardized by the OMG (Object Management Group) since
September 1997 as UML Version 1.1. The members of the OMG are continuously developing it further.
SAP uses UML as the company-wide standard for object-oriented modeling.
You can find the UML specifications on the OMG homepage at:
http://www.omg.org
UML describes a number of different diagram types in order to represent different views of a system.
Class diagrams show the static view of a model.
Behavior diagrams demonstrate the relationships and method calls between objects. They emphasize
the timing sequence of method calls.
Component diagrams show the organization and dependencies of components.
Distribution diagrams represent the dependencies of software and hardware.
(C) SAP AG
BC401
6-10
lcl_rental
0..*
lcl_booking
0..* 1
lcl_customer
1..*
lcl_vehicle
lcl_car
lcl_truck
1..*
lcl_wheel
lcl_bus
SAP AG 2002
A class diagram describes the elements contained in the model and their various static relationships.
There are two basic forms of static relationships:
Associations (for example, a car rental customer books a car)
Generalization / specialization (for example, a car and a bus are both vehicles)
In class diagrams, classes can also be shown with their attributes and methods.
(C) SAP AG
BC401
6-11
Association
lcl_booking 0..*
A booking refers to
a customer
books
lcl_customer
Association name
Common cardinalities
* or 0..*
1
1..*
0..1
Many
Exactly one
One or more
Zero or one
SAP AG 2002
An association describes a semantic relationship between classes. The specific relationship between
objects in these classes is known as an object link. Object links are therefore the instances of an
association.
An association is usually a relationship between different classes. However, an association can also be
recursive; in this case, the class would have a relationship with itself. In most cases, recursive
associations are used to link two different objects in one class.
The points below assume that the associations are binary.
Each association has two roles, one for each direction of the association (booking
customer, customer
booking). Roles can have names (for example, the association car reservation could be called
"reservation").
Each role has a cardinality that shows how many instances participate in this relationship. The
multiplicity is the number of participating objects in one class that have a relationship to an object in the
other class.
UML notation:
An association is represented by a line between the class symbols
The cardinality of the relationship can be shown at each end of the line
Associations can be given a name for ease of identification (a verb or a short text). This name is
written in italics above the line and may have an arrow to show the read direction. Both are
optional.
(C) SAP AG
BC401
6-12
Aggregation is a special
case of association, a
whole-part relationship
Aggregation symbol
lcl_vehicle
Composition is a special
case of aggregation, an
existence-dependent
whole-part relationship
0..*
lcl_wheel
Composition symbol
lcl_rental
1..*
lcl_booking
SAP AG 2002
Aggregation is a special kind of association. Aggregation describes one object that contains another or
consists of other objects (whole-part). A vehicle consists of wheels. The relationship can be described by
the words "consists of" or "is a part of".
UML notation for aggregation:
An aggregation, like an association, is represented by a line between two classes, which then additionally
has a small rhombus at one end. The rhombus is always at the aggregate end, that is, the whole object
end. Otherwise the notation conventions are the same as for associations.
Composition is a special kind of aggregation. Composition describes the fact that the object contained
cannot exist without the aggregate (for example, a car reservation cannot exist without the car rental).
Differences to aggregation:
The cardinality on the aggregate side can only be one. Each part is only part of one composite object,
otherwise the existence dependency would be contradictory. The lifetime of the individual parts is linked
to the lifetime of the aggregate: Parts are created either with or immediately after the aggregate, and they
are destroyed either with or immediately before the aggregate.
UML notation for composition:
Like aggregation, composition is shown as a line between two classes and marked with a small rhombus
on the aggregate side. However, in contrast to aggregation, the rhombus is filled in.
(C) SAP AG
BC401
6-13
lcl_car
lcl_truck
Generalization
Inheritance arrow
Specialization
lcl_vehicle
lcl_vehicle
lcl_car
lcl_truck
Generalization
Specialization
or
SAP AG 2002
UML notation:
Generalization and specialization are denoted by triangular arrows that point from the subordinate class
to the superclass.
Several arrows can be combined into a tree.
(C) SAP AG
BC401
6-14
lcl_driver
lcl_car
1:Method (parameter)
Time
Process
description
(optional)
Life line
of object
Return value
Control focus
SAP AG 2002
Sequence diagrams, unlike class diagrams, show the dynamics between objects. They are used to
represent a particular process or a particular situation. Sequence diagrams focus on the time sequence of
the information exchange:
a) Creation and deletion of objects
b) Message exchange between objects
Sequence diagrams have no notation for representing static methods.
The object life line is represented by vertical dotted lines.
The control focus is shown as a vertical rectangle on the object life line. The control focus shows the
object's "active" period:
An object is active when actions are executed
An object is indirectly active if it is waiting for a subordinate procedure to end.
Messages are shown as horizontal arrows between the object lines. The message is written above the
arrow in the form method (parameter). There are various ways of representing the reply; in this example,
the arrow is shown as a returning arrow.
You can also include a description of the process and add comments to the object life line as required.
(C) SAP AG
BC401
6-15
lcl_driver
lcl_car
lcl_tank
1: get_fuel_level( )
2: get_fuel_level( )
re_level
re_level
re_level =
tank->get_fuel_level( ).
re_level =
fuel / fuel_max * 100.
SAP AG 2002
In delegation, two objects are involved in handling a request: The recipient of the request delegates the
execution of the request to a delegate.
Example:
The driver (lcl_driver) calls the method get_fuel_level for the class car (lcl_car). The car
cannot carry out this task itself. Therefore, the car calls the get_fuel_level method for the class
(lcl_tank), that is the car delegates the execution of the method to the tank.
The main advantage of delegation (as a re-use mechanism) lies in the option of changing the behavior of
the recipient by substituting the delegate (at runtime). For example, delegation enables the car to be
equipped with a new tank, without the call changing for the client or for the car class.
Good encapsulation often forces the use of delegation: If tank in the above example were a private
attribute of the class lcl_car, the user could not address the tank directly, but only through the car.
(C) SAP AG
BC401
6-16
SAP AG 2002
(C) SAP AG
BC401
6-17
1-1
Use a pencil and paper to create a UML class diagram that contains the following
classes:
- Airline:
lcl_carrier
Airplane (general): lcl_airplane
Passenger airplane: lcl_passenger_plane
Cargo plane:
lcl_cargo_plane
1-1-1 Include some appropriate attributes and methods for every class.
1-1-2 Draw lines to represent the relationships between the classes and indicate
possible cardinalities.
(C) SAP AG
BC401
6-18
(C) SAP AG
BC401
6-19
Contents:
Classes
Objects
Attributes
Methods
Visibility/encapsulation
Instantiation
Constructor
Garbage collector
SAP AG 2002
(C) SAP AG
BC401
7-1
SAP AG 2002
(C) SAP AG
BC401
7-2
mming
ted Progra
n
e
ri
O
tc
of Obje
ign
s and Des
Principles
Analysi
and
Data Types
ts in
Data Objec
Detail
ammin
ted Progr
ect-Orien
bj
O
to
n
Introductio
al
Using Intern
Tables
rams
Calling Prog
Data
and Passing
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
7-3
Principles (1)
Classes,
Classes, attributes,
attributes, and
and methods
methods
Objects,
Objects, instances
instances of
of classes
classes
Accessing
Accessing attributes
attributes and
and methods
methods
The
The constructor
constructor
Additional
Additional principles
principles
SAP AG 2002
(C) SAP AG
BC401
7-4
Example of a Class
lcl_vehicle
Represented in
course by
Private
components
Public
components
get_make
make
set_make
model
Methods:
Implementation
Private access
Encapsulation
Normally attributes
Public access
Interface
Normally methods, events
SAP AG 2002
In the graphic, the public component of the class is accessed using the green node or starting point
displayed on the left. A user or client can use this node to access the public components and hence also
indirectly access the private components. However, the private components of the class cannot be
addressed directly . They are not visible to the outside user.
Why are the private components of a class hidden?
This principle is called information hiding or encapsulation and is used to protect the user.
Let us assume that a class changes its private components, while its interface remains unchanged. Any
user who simply needs to access the interface of the class can carry on working with the class as usual.
The user does not notice the change.
However, if an class changes its public components, then any user who accesses these public
components must take these changes into account.
(C) SAP AG
BC401
7-5
Defining Classes
ABAP code
CLASS lcl_vehicle DEFINITION.
lcl_vehicle
Public
components
ENDCLASS.
Private
components
ENDCLASS.
SAP AG 2002
A class is a set of objects that have the same structure and the same behavior. A class is therefore like a
blueprint, in accordance with which all objects in that class are created.
The components of the class are defined in the definition part. The components are attributes, methods,
events, constants, types, and implemented interfaces. Only methods are implemented in the
implementation part.
The CLASS statement cannot be nested, that is, you cannot define a class within a class.
(C) SAP AG
BC401
7-6
Attributes
(5) lcl_car
C, N, I, P, ..., STRING
Dictionary types
Public
User-defined types
TYPE REF TO
defines a reference to an
object, in this case r_car
Private
make TYPE STRING,
...
r_motor
TYPE REF TO ...
(3) lcl_rental
r_car
SAP AG 2002
Attributes describe the data that can be stored in the objects of a class.
Class attributes can be of any type:
Data types: scalar (for example data element), structured, in tables
ABAP elementary types (C, I, ...)
Object references
Interface references
Examples of attributes for the class lcl_car are:
make
(car make)
modell
(type , model)
ser_no
(serial number)
color
(color)
car_type(estate, convertible, ...)
max_seats (number of seats)
r_motor
(reference to class lcl_motor)
...
(C) SAP AG
BC401
7-7
TYPE
TYPE
LIKE
TYPE
TYPE
TYPE
TYPE
<type>,
<ddic_type>,
variable1,
<type> VALUE <value>,
<type> READ-ONLY,
REF TO <classname>,
REF TO <interface>.
SAP AG 2002
In classes, you can only use the TYPE addition to refer to data types.
You can only use the LIKE reference for local data objects.
The READ-ONLY addition means that a public attribute declared with DATA can be read from outside,
but can only be changed by methods of the class.
You can currently only use the READ-ONLY addition in the public visibility section (PUBLIC
SECTION) of a class declaration or in an interface definition.
(C) SAP AG
BC401
7-8
Public attributes
PUBLIC SECTION.
DATA: make TYPE string.
PRIVATE SECTION.
ENDCLASS.
Direct access
CLASS lcl_vehicle DEFINITION.
Private attributes
PUBLIC SECTION.
...
PRIVATE SECTION.
DATA: make
TYPE string.
ENDCLASS.
SAP AG 2002
You can protect attributes against access from outside by characterizing them as private attributes
(defined in the PRIVATE SECTION).
Attributes and their values that may be used directly by an external user are public attributes and are
defined in the PUBLIC SECTION.
In the above example for the class lcl_car, the attribute make is defined as a public attribute.
Public attributes belong to the interface of the class, that is their implementation is publicized. If you
want to hide the internal implementation from users, you must define internal and external views of
attributes.
As a general rule, you should define as few public attributes as possible.
(C) SAP AG
BC401
7-9
Client
(5) lcl_vehicle
Public
Private
make
set_make
get_make
r_vehicle
...
SAP AG 2002
You can access an object's private attributes using public methods, which in turn output this attribute or
change it.
It is not possible to directly access private attributes from outside (for example, main program or other
object). The only exception lies in the so-called "friend" concept, which will be dealt with later in the
course.
(C) SAP AG
BC401
7-10
Instance attributes
PUBLIC SECTION.
Statement: DATA
PRIVATE SECTION.
DATA: make
...
Static attributes
Statement: CLASS-DATA
TYPE string,
...
SAP AG 2002
(C) SAP AG
BC401
7-11
Internal session
Global data objects
n_o_vehicles
Static attributes
only exist once
Static attributes
(1) lcl_vehicle
r_vehicle1
(2) lcl_vehicle
Instances /
objects
r_vehicle2
(3) lcl_vehicle
r_vehicle3
...
...
SAP AG 2002
(C) SAP AG
BC401
7-12
Methods: Syntax
SAP AG 2002
Methods are internal procedures in classes that determine the behavior of an object. They can access all
attributes in their class and can therefore change the state of an object.
Methods have a parameter interface (called signature) that enables them to receive values when they are
called and pass values back to the calling program.
In ABAP Objects, methods can have IMPORTING, EXPORTING, CHANGING, and RETURNING
parameters as well as exception parameters. All parameters can be passed by value or reference. (As of
SAP R/3 Basis Release 6.10, you should no longer use the EXCEPTIONS parameter for exceptions but
use the RAISING addition instead; this will be discussed in more detail later.)
You can define a return code for methods using RETURNING. You can only do this for a single
parameter, which additionally must be passed as a value. Also, you cannot then define EXPORTING and
CHANGING parameters. You can define functional methods using the RETURNING parameter (this will
be explained in more detail).
All input parameters (IMPORTING, CHANGING parameters) can be defined as optional parameters in
the declaration using the OPTIONAL or DEFAULT additions. These parameters then do not necessarily
have to be passed when the object is called. If you use the OPTIONAL addition, the parameter remains
initialized according to type, whereas the DEFAULT addition allows you to enter a start value.
(C) SAP AG
BC401
7-13
Client
(5) lcl_vehicle
Public
Private
make
...
r_vehicle
...
set_make
init_make
SAP AG 2002
Methods also have to be assigned to a visibility area. This determines whether the methods can be called
from outside or only from within the class.
It is not possible to directly access private methods from outside. However, a private method can be
called by a public method.
Both method types can access the public and private attributes.
(C) SAP AG
BC401
7-14
Public methods
Private methods
SAP AG 2002
In this example, init_make is a private method that is called by the public method set_make.
(C) SAP AG
BC401
7-15
Rules:
Instance methods
Static methods
SAP AG 2002
Static methods are defined at class level. They are similar to instance methods, but with the restriction
that they can only use static components (such as static attributes) in the implementation part. This
means that static methods do not need instances and can be called from anywhere. They are defined
using the CLASS-METHODS statement, and they are bound by the same syntax and parameter rules as
instance methods.
The term "class method" is common, but the official term in ABAP Objects (as in C++, Java) is "static
method".
(C) SAP AG
BC401
7-16
SAP AG 2002
In the static method get_count, you can only use the static attribute n_o_vehicles. All other
attributes of the class are instance attributes and can only appear in instance methods.
(C) SAP AG
BC401
7-17
lcl_vehicle
- make
- model
- n_o_vehicles
...
+ set_make
- init_make
+ get_count
...
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 string. ...
CLASS-DATA: n_o_vehicles TYPE i.
METHODS: init_make.
ENDCLASS.
SAP AG 2002
A UML class diagram shows firstly the class name and, underneath that, the class attributes and
methods.
The visibility of components in a class is shown in UML using the characters "+" and "-":
+ indicates public components
- indicates private components
Alternatively, public and private can be prefixed to the methods. The third option for providers of
modeling tools in UML is to introduce their own symbols for visibility.
Representation of visibility characteristics is optional and is normally only used for models that are close
to implementation.
Static components are marked with an underscore.
The method signature is represented as follows (optional):
The input and output parameters and the parameters to be changed are shown in brackets.
The return code is separated from the type name by a colon.
(C) SAP AG
BC401
7-18
Principles (2)
Classes,
Classes, attributes,
attributes, and
and methods
methods
Objects,
Objects, instances
instances of
of classes
classes
Accessing
Accessing attributes
attributes and
and methods
methods
The
The constructor
constructor
Additional
Additional principles
principles
SAP AG 2002
(C) SAP AG
BC401
7-19
Creating Objects
Rules:
lcl_vehicle
- make
- model
- ser_no
- n_o_vehicles
+ set_make
- init_make
+ get_count
...
(5) lcl_vehicle
Public
...
r_vehicle
set_make
get_count
...
Private
make
modell
ser_no
...
SAP AG 2002
A class contains the generic description of an object. It describes all the characteristics that are common
to all objects in that class. During the program runtime, the class is used to create specific objects
(instances). This process is called instantiation.
Example:
The specific object Car xy with Ser-No. 0815" is created through instantiation from the class
lcl_vehicle; it is created in the main memory at runtime.
The lcl_vehicle class itself does not exist as an independent runtime object in ABAP Objects.
Implementation:
Objects are instantiated using the statement: CREATE OBJECT.
During instantiation, the runtime environment dynamically requests main memory space and assigns it to
the object.
(C) SAP AG
BC401
7-20
Reference Variables
...
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
...
PRIVATE SECTION.
...
ENDCLASS.
What do these
reference variables
point to?
r_vehicle2
?
?
START-OF_SELECTION.
...
SAP AG 2002
DATA: r_vehicle1 TYPE REF TO lcl_vehicle declares a reference variable that acts as a
pointer to an object.
(C) SAP AG
BC401
7-21
Private
r_vehicle1
(4) lcl_vehicle
r_vehicle2
Public
Private
SAP AG 2002
The CREATE OBJECT statement creates an object in the main memory. The attribute values of this
object are either initial values or correspond to the VALUE entry.
Reference variables can also be assigned to each other.
For the above example this would mean that r_vehicle1 and r_vehicle2 point to the same object.
(C) SAP AG
BC401
7-22
Garbage Collector
r_vehicle2 = r_vehicle1
Public
Private
r_vehicle1
(4) lcl_vehicle
r_vehicle2
Public
Private
SAP AG 2002
As soon as no more references point to an object, the Garbage Collector removes it from the memory.
The Garbage Collector is a system routine that automatically deletes objects that can no longer be
addressed from the main memory and releases the memory space they occupied.
(C) SAP AG
BC401
7-23
All independent references in the global main memory are checked. The
references point to active objects, which are marked internally.
Objects that are not marked are deleted from the main memory.
(4) lcl_object
Deleted
(2) lcl_object
(5) lcl_object
SAP AG 2002
Independent references are references that have not been defined within a class.
(C) SAP AG
BC401
7-24
If you want to keep several objects from the same class in your program, you can define an internal
table, which, for example, only consist of one column containing the object references for this class.
You can process the objects using a LOOP through the internal table.
(C) SAP AG
BC401
7-25
If a class defines object references to a second class as attributes (in the above example: References to
objects of the class lcl_wheel), only these object references will be stored in an object belonging to
that class.
The objects in the second class lcl_wheel have their own identity. They are encapsulated in the first
class lcl_vehicle and can only be addressed from this class using reference variables.
(C) SAP AG
BC401
7-26
Principles (3)
Classes,
Classes, attributes,
attributes, and
and methods
methods
Objects,
Objects, instances
instances of
of classes
classes
Accessing
Accessing attributes
attributes and
and methods
methods
The
The constructor
constructor
Additional
Additional principles
principles
SAP AG 2002
(C) SAP AG
BC401
7-27
Calling Methods
Client
(5) lcl_vehicle
Public
Private
motor_on
r_vehicle->motor_on( )
Method
Reference
Component selector
SAP AG 2002
Every object behaves in a certain way. This behavior is determined by its methods. There are three types
of method:
1. Methods that trigger the behavior and do not return values (see example)
2. Methods that return a value
3. Methods that return or change several values
An object that requires the services of another object sends a message to the object providing the
services. This message names the operation to be executed. The implementation of this operation is
known as a method.
For the sake of simplicity, method will henceforth be used as a synonym for operation and message.
The example shows the new syntax for method calls, in which the CALL-METHOD prefix is omitted.
(C) SAP AG
BC401
7-28
<instance>-><instance_method>
( [additions] )
SAP AG 2002
(C) SAP AG
BC401
7-29
Static methods:
SAP AG 2002
Static methods (also referred to as class methods) are called using CALL METHOD
<classname>=><class_method>.
Static methods are addressed with their class name, since they do not need instances.
Note:
If you are calling a static method from within the class, you can omit the class name.
(C) SAP AG
BC401
7-30
Functional Methods
Example
a = b +
Functional method
When defining:
Only one RETURNING parameter
Only IMPORTING parameters and exceptions are possible
When calling:
a) RECEIVING parameters possible
b) Various forms of direct call possible:
SAP AG 2002
Methods that have a RETURNING parameter are described as functional methods. These methods cannot
have EXPORTING or CHANGING parameters, but has many (or as few) IMPORTING parameters and
exceptions as required.
Functional methods can be used directly in various expressions:
Logical expressions (IF, ELSEIF, WHILE, CHECK, WAIT)
The CASE statement (CASE, WHEN)
The LOOP statement
Arithmetic expressions (COMPUTE)
Bit expressions (COMPUTE)
The MOVE statement.
(C) SAP AG
BC401
7-31
SAP AG 2002
Depending on the number of IMPORTING parameters, the syntax for functional methods is as follows
(same for static functional methods):
No IMPORTING parameters:
ref->func_method( )
Exactly 1 IMPORTING parameter: ref->func_method( p1 ) or
ref->func_method( im_1 = p1 )
Several IMPORTING parameters: ref->func_method( im_1 = p1 im_2 = p2 )
Example of detailed syntax for functional method call:
CALL METHOD r_vehicle->get_average_fuel
EXPORTING im_distance = 500
im_fuel
= 50
RECEIVING re_fuel
= avg_fuel.
Here, re_fuel is the formal parameter of the interface and avg_fuel is the actual parameter of the
calling program.
(C) SAP AG
BC401
7-32
just a demo
just a demo
...
ENDCLASS.
...
(2) lcl_vehicle
make
...
START-OF-SELECTION.
*--------------------------------------* main program, think of a client !
CREATE OBJECT r_vehicle.
r_vehicle
make_name = r_vehicle->make.
count = lcl_vehicle=>n_o_vehicles.
SAP AG 2002
There are different ways of accessing public attributes from outside the class:
You access static attributes using <classname>=><class_attribute>
You access instance attributes using <instance>-><instance_attribute>
=> and -> are the component selectors
(C) SAP AG
BC401
7-33
Principles (4)
Classes,
Classes, attributes,
attributes, and
and methods
methods
Objects,
Objects, instances
instances of
of classes
classes
Accessing
Accessing attributes
attributes and
and methods
methods
The
The constructor
constructor
Additional
Additional principles
principles
SAP AG 2002
(C) SAP AG
BC401
7-34
Constructor
lcl_vehicle
- make
- model
- n_o_vehicles
...
+ constructor
...
CREATE OBJECT
(3) lcl_vehicle
Public
Private
SAP AG 2002
The constructor is a special instance method in a class with the name constructor. The following
rules apply:
Each class can have one constructor.
The constructor is automatically called at runtime within the CREATE OBJECT statement.
If you need to implement the constructor, then you must define and implement it in the PUBLIC
SECTION.
When exceptions are raised in the constructor, instances are not created, so no main memory space is
occupied.
(C) SAP AG
BC401
7-35
Constructor: Example
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS constructor IMPORTING im_make
TYPE string
im_model 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.
model = im_model.
ADD 1 TO n_o_vehicles.
ENDMETHOD.
ENDCLASS.
SAP AG 2002
(C) SAP AG
BC401
7-36
The static constructor is a special static method in a class with the name class_constructor. It is
executed precisely once per program. The static constructor of a class <classname> is called
automatically when the class is first accessed, but before any of the following actions are executed:
Creating an instance in the class using CREATE OBJECT <obj>, where <obj> has the data type
REF TO <classname>
Addressing a static attribute using <classname>=><attribute>
Calling a static attribute using CALL METHOD <classname>=><classmethod>
Registering a static event handler method using SET HANDLER
<classname>=><handler_method> FOR <obj>
Registering an event handler method for a static event in class <classname>.
The static constructor cannot be called explicitly.
(C) SAP AG
BC401
7-37
Principles (5)
Classes,
Classes, attributes,
attributes, and
and methods
methods
Objects,
Objects, instances
instances of
of classes
classes
Accessing
Accessing attributes
attributes and
and methods
methods
The
The constructor
constructor
Additional
Additional principles
principles
SAP AG 2002
(C) SAP AG
BC401
7-38
lcl_vehicle
Attributes
Methods
Events
Types
Constants
Public
components
Method
make
Private
components
Attribute
make
Method
implementation
ALIAS names
SAP AG 2002
Within a class, attribute names, method names, event names, constant names, type names and alias
names all share the same namespace.
There is a local namespace within methods. Definitions of local variables can cover components in one
class.
(C) SAP AG
BC401
7-39
lcl_vehicle
Public
components
Private
components
Attribute
make
Method
implementation
ME->make
METHOD DUMMY.
* calling own methods from inside class
* call method display_attributes( )
* with the short syntax variant:
display_attributes( ).
ENDMETHOD.
ENDCLASS.
SAP AG 2002
You can address the object itself within instance methods using the implicitly available reference
variable me.
Description of example:
In the constructor, the instance attribute make is covered by the locally defined variable make. In order
to still be able to address the instance attribute, you need to use me.
The dummy method demonstrates how to call a class's own method. You can omit the prefix me->.
Other important use:
An object calls another object's method and passes its own address.
(C) SAP AG
BC401
7-40
SAP AG 2002
(C) SAP AG
BC401
7-41
Exercises
Unit: Principles of Object-Oriented Programming
Topic:
Creating a Class
1-1
Create the package ZBC401_## (where ##: is your group number) and save all the
repository objects you have created during the course in this package.
1-2
1-3
(C) SAP AG
BC401
7-42
Implement the method in the implementation part; set both attributes. Each time
the method is called, the static attribute n_o_airplanes should increase by one.
(This is actually not right but will be corrected later).
1-3-4 The class is to have another public instance method display_attributes to
display the instance attributes. Declare this method and, in the implementation
part, output the attributes using the WRITE statement (you can also display the
icon icon_ws_plane, in which case you must add TYPE-POOLS icon to
the program.
1-3-5 Declare and implement a public static method display_n_o_airplanes to
display the static attribute n_o_airplanes.
(In the remaining exercises in this course, you can always start with the program you
created in the previous exercise or copy the corresponding model solution and continue
working with this program.)
(C) SAP AG
BC401
7-43
Exercises
Unit: Principles of Object-Oriented
Programming
Topic:
Instantiating Objects
(In the remaining exercises in this course, you can always start with the program you
created in the previous exercise or copy the corresponding model solution and continue
working with this program.)
(C) SAP AG
BC401
7-44
Exercises
Unit: Principles of Object-Oriented
Programming
Topic:
Method Calls
3-1 Call the static method display_n_o_airplanes (before instantiating an object in class
lcl_airplane).
3-2 Use the set_attributes method to set the attributes for all objects already created. Choose
an airplane name and airplane type and pass them as text literals. (For the plane type you
can use a type from the table SAPLANE, for example 747-400.)
3-3 Display the object attributes using the display_attributes method.
3-4 Call the static method display_n_o_airplanes a second time.
3-5 Add a functional static method get_n_o_airplanes to the class lcl_airplane. The method
must be public and have the re_count (type I) return parameter (no input parameters).
3-6 Test your functional method by calling it from the main program.
(C) SAP AG
BC401
7-45
Exercises
Unit: Principles of Object-Oriented
Programming
Topic:
Constructor
4-1 Create a constructor for the class lcl_airplane (in your include program
ZBC401_##_AIRPLANE) The simplest way of doing this is to copy the method
set_attributes, which you now no longer need.
4-1-1
The constructor must have two importing parameters that fill the instance
attributes name and planetype.
4-1-2
4-2 In the method set_attributes, comment out the line in which the static attribute
n_o_airplanes is increased by one (if you still want to use this method).
4-3 In the main program ZBC401_##_MAIN_AIRPLANE, extend the creation of the object
with the constructor interface.
Fill the constructors interface parameters with the same values you used when calling
the set_attributes method.
4-4 (Optional)
Comment out the method call set_attributes or delete the call.
(C) SAP AG
BC401
7-46
Exercises
Unit: Principles of Object-Oriented Programming
Topic: Calling a Private Method
At the conclusion of these exercises, you will be able to:
Call methods within a class
Create the private method get_technical_attributes for the class lcl_airplane (in your
include program ZBC401_##_AIRPLANE).
5-1 The airplane type is the import parameter. (Type saplane-planetype)
5-2 The export parameter is the weight WEIGHT and the tank capacity TANKCAP.
Refer to the types in the table SAPLANE.
5-3 The result, both export parameters are ascertained in a database access to the table
SAPLANE.
Therefore, both attributes are read, depending on the airplane type.
5-4 If the imported plane type does not exist in the table, set default values (weight
100000, tank capacity 10000).
5-5 Test your method get_technical_attributes:
(C) SAP AG
5-5-1
5-5-2
5-3-3
BC401
7-47
Solutions
Unit: Principles of Object-Oriented
Programming
Topic:
Creating a Class
*&---------------------------------------------------------------------*
*& Report
SAPBC401_AIRS_MAIN_a
*&---------------------------------------------------------------------*
REPORT
sapbc401_airs_main_a.
TYPE-POOLS icon.
INCLUDE SAPBC401_airs_A.
*&-----------------------------------------------------------------*
*&
Include
SAPBC401_AIRS_A
*&-----------------------------------------------------------------*
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
"-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
METHODS: set_attributes IMPORTING
im_name
TYPE string
TYPE string,
BC401
7-48
*------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
METHOD set_attributes.
name
= im_name.
planetype
= im_planetype.
n_o_airplanes = n_o_airplanes + 1.
ENDMETHOD.
METHOD display_attributes.
WRITE: / icon_ws_plane as icon,
/ 'Name of airplane:'(001), AT pos_1 name,
/ 'Airplane type'(002), AT pos_1 planetype.
ENDMETHOD.
METHOD display_n_o_airplanes.
WRITE: /, / 'Total number of planes'(ca1),
AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
ENDMETHOD.
ENDCLASS.
(C) SAP AG
BC401
7-49
Solutions
Unit: Principles of Object-Oriented
Programming
Topic:
Instantiating Objects
*&---------------------------------------------------------------------*
*& Report
SAPBC401_AIRS_MAIN_b
*&---------------------------------------------------------------------*
*& create and insert planes into internal table
*&---------------------------------------------------------------------*
REPORT
sapbc401_airs_main_b.
TYPE-POOLS icon.
INCLUDE SAPBC401_airs_A.
DATA: r_plane TYPE REF TO lcl_airplane,
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION.
*##############################
(C) SAP AG
BC401
7-50
Solutions
Unit: Principles of Object-Oriented
Programming
Topic:
Method Calls
*&---------------------------------------------------------------------*
*& Report
SAPBC401_AIRS_MAIN_C
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_airs_main_c.
TYPE-POOLS icon.
INCLUDE sapbc401_airs_c.
DATA: r_plane TYPE REF TO lcl_airplane,
plane_list TYPE TABLE OF REF TO lcl_airplane,
count type i.
START-OF-SELECTION.
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_plane.
APPEND r_plane TO plane_list.
r_plane->set_attributes( im_name = 'LH Berlin'
im_planetype = '747-400' ).
CREATE OBJECT r_plane.
APPEND r_plane TO plane_list.
r_plane->set_attributes( im_name = 'AA New York'
im_planetype = '737-100' ).
(C) SAP AG
BC401
7-51
(C) SAP AG
BC401
7-52
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_AIRS_C
*&
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
"-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
METHODS: set_attributes IMPORTING
im_name
TYPE string
TYPE string,
*------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
METHOD set_attributes.
name
= im_name.
planetype
= im_planetype.
(C) SAP AG
BC401
7-53
n_o_airplanes = n_o_airplanes + 1.
ENDMETHOD.
METHOD display_attributes.
WRITE: / icon_ws_plane as icon,
/ 'Name of airplane:'(001), AT pos_1 name,
/ 'Airplane type'(002), AT pos_1 planetype.
ENDMETHOD.
METHOD display_n_o_airplanes.
WRITE: /, / 'Total number of planes'(ca1),
AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
ENDMETHOD.
method get_n_o_airplanes.
re_count = n_o_airplanes.
endmethod.
ENDCLASS.
(C) SAP AG
BC401
7-54
Solutions
Unit: Principles of Object-Oriented
Programming
Topic:
Constructor
*&---------------------------------------------------------------------*
*& Report
SAPBC401_AIRS_MAIN_d
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_airs_main_d.
TYPE-POOLS icon.
INCLUDE sapbc401_airs_d.
DATA: r_plane TYPE REF TO lcl_airplane,
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION.
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_plane exporting im_name = 'LH Berlin'
im_planetype = '747-400'.
APPEND r_plane TO plane_list.
CREATE OBJECT r_plane exporting im_name = 'AA New York'
im_planetype = '737-100'.
LOOP AT plane_list INTO r_plane.
r_plane->display_attributes( ).
ENDLOOP.
lcl_airplane=>display_n_o_airplanes( ).
(C) SAP AG
BC401
7-55
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_AIRS_d
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
"-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
METHODS: constructor IMPORTING
im_name
TYPE string
TYPE string,
*------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
name
= im_name.
planetype
= im_planetype.
n_o_airplanes = n_o_airplanes + 1.
ENDMETHOD.
METHOD display_attributes.
(C) SAP AG
BC401
7-56
(C) SAP AG
BC401
7-57
Solutions
Unit: Principles of Object-Oriented
Programming
Topic:
*&---------------------------------------------------------------------*
*& Report
SAPBC401_AIRS_MAIN_e
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_airs_main_e.
TYPE-POOLS icon.
INCLUDE sapbc401_airs_e.
DATA: r_plane TYPE REF TO lcl_airplane,
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION.
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_plane exporting im_name = 'LH Berlin'
im_planetype = '747-400'.
APPEND r_plane TO plane_list.
r_plane->display_attributes( ).
CREATE OBJECT r_plane exporting im_name = 'AA New York'
im_planetype = '727-200'.
r_plane->display_attributes( ).
lcl_airplane=>display_n_o_airplanes( ).
(C) SAP AG
BC401
7-58
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_AIRS_e
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
"-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
METHODS: constructor IMPORTING
im_name
TYPE string
type saplane-planetype
EXPORTING ex_weight
TYPE s_plan_wei
ex_tankcap
DATA: name
TYPE s_capacity.
TYPE string,
(C) SAP AG
"lcl_airplane DEFINITION
BC401
7-59
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
name
= im_name.
planetype
= im_planetype.
n_o_airplanes = n_o_airplanes + 1.
ENDMETHOD.
"constructor
METHOD display_attributes.
data: weight type saplane-weight,
cap type saplane-tankcap.
WRITE: / icon_ws_plane AS ICON,
/ 'Name of airplane'(001), AT pos_1 name,
/ 'Airplane type: '(002), AT pos_1 planetype.
get_technical_attributes( exporting im_type = planetype
importing ex_weight = weight
ex_tankcap = cap ).
write: / 'wheight: '(003), weight,
'tankcap: '(004), 60 cap.
ENDMETHOD.
"display_attributes
METHOD display_n_o_airplanes.
WRITE: /, / 'Number of airplanes: '(ca1),
AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
ENDMETHOD.
"display_n_o_airplanes
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.
(C) SAP AG
"get_technical_attributes
BC401
7-60
ENDCLASS.
(C) SAP AG
"lcl_airplane IMPLEMENTATION
BC401
7-61
Inheritance
Contents:
Generalization / specialization of classes
SAP AG 2002
(C) SAP AG
BC401
8-1
SAP AG 2002
(C) SAP AG
BC401
8-2
e
Inheritanc gramming
and
Data Types
ts in
Data Objec
Detail
Pro
Oriented
of ObjectPrinciples
n
ig
and Des
Analysis
amming
P
ted rogr
ect-Orien
bj
O
to
n
Introductio
al
Using Intern
Tables
rams
Calling Prog
Data
and Passing
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
8-3
"is a"
relationship
lcl_car
- make
- modell
- ser_no
- color
- n_o_vehicles
+constructor
+display_attributes
+get_count
lcl_truck
lcl_bus
- car_type
- max_seats
- accelertion
- max_cargo
- n_o_tanks
- n_o_wheels
- max_passengers
- lavatory
- television
+...
+get_type
+...
+get_cargo
+...
+get_passengers
SAP AG 2002
Inheritance is a relationship, in which one class (the subclass) inherits all the main characteristics of
another class (the superclass). The subclass can also add new components (attributes, methods, and so
on) and replace inherited methods with its own implementations.
Inheritance is an implementation relationship that emphasizes similarities between classes. In the
example above, the similarities between the car, bus, and truck classes are extracted to the vehicle
superclass. This means that common components are only defined/implemented in the superclass and are
automatically present in the subclasses.
The inheritance relationship is often described as an "is a" relationship: A truck is a vehicle.
(C) SAP AG
BC401
8-4
lcl_super2
No
multiple inheritance
lcl_sub1
lcl_sub2
lcl_sub3
Specialization
lcl_super1
Generalization
Multiple Inheritance?
SAP AG 2002
(C) SAP AG
BC401
8-5
lcl_super
lcl_sub
New
components
Inherited
components
SAP AG 2002
If inheritance is used properly, it provides a significantly better structure, as common components only
need to be stored once centrally (in the superclass) and are then automatically available to subclasses.
Subclasses also benefit from modifications (however, they can also be invalidated as a result).
Inheritance provides very strong links between the superclass and the subclass. The subclass must
possess detailed knowledge of the implementation of the superclass, particularly for redefinition, but
also in order to use inherited components. Even if the superclass does not technically know its
subclasses, the subclass often makes additional requirements of the superclass, for example, because a
subclass needs certain protected components or because implementation details in the superclass need to
be changed in the subclass in order to redefine methods. The basic reason is that the developer of a
(super)class cannot normally predict all the requirements that subclasses will later need to make of the
superclass.
(C) SAP AG
BC401
8-6
Inheritance: Syntax
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.
SAP AG 2002
Normally the only other entry required for subclasses is what has changed in relation to the direct
superclass. Only additions are permitted in ABAP Objects, that is, in a subclass you can "never take
something away from a superclass". All components from the superclass are automatically present in the
subclass.
The attributes of the superclass lcl_vehicle exist in the subclass lcl_truck; the method
estimate_fuel is also available in the subclass.
The subclass defines a method get_cargo. It is not visible in the superclass.
(C) SAP AG
BC401
8-7
Redefining Methods
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.
CLASS lcl_truck IMPLEMENTATION.
METHOD estimate_fuel.
...
super->estimate_fuel(...)
ENDMETHOD.
ENDCLASS.
Cannot change
the interface
New
implementation of
method
SAP AG 2002
The REDEFINITION statement for the inherited method must be in the same SECTION as the
definition of the original method. (It can therefore not be in the PRIVATE SECTION, since a class's
private methods are not visible and therefore cannot be redefined in subclasses).
If you redefine a method, you do not need to enter its interface again in the subclass, but only the name
of the method. The reason for this is that ABAP Objects does not support overloading.
In the case of redefined methods, changing the interface (overloading) is not permitted; exception:
Overloading is possible with the constructor.
Within the redefined method, you can access components of the direct superclass using the SUPER
reference.
To implement a redefined method in a subclass, you often need to call the method of the same name in
the immediate superclass. In ABAP Objects you can call the method from the superclass using the
pseudo-reference super:
The pseudo-reference super can only be used in redefined methods.
(C) SAP AG
BC401
8-8
The constructor of the superclass must be called within the constructor of the subclass. The reason for
this is the special function of the constructor: To ensure that objects are initialized correctly. Only the
class itself, however, can initialize its own (private) components correctly; this task cannot be carried out
by the subclass. Therefore it is essential that all (instance) constructors are called in an inheritance
hierarchy (in the correct sequence).
For static constructors, unlike instance constructors, the static constructor in the superclass is called
automatically, that is the runtime system automatically ensures that the static constructors of all its
superclasses have already been executed before the static constructor in a particular class is executed.
(C) SAP AG
BC401
8-9
lcl_1
a1
constructor
(im_a1:i)
Case 1:
Class of instance to be created has constructor
Fill its parameters
Case 2:
Class of instance to be created has no constructor
Search for the next superclass with a constructor
in the inheritance tree
Fill its parameters
lcl_2
lcl_3
a2
constructor
(im_a1, im_a2)
SAP AG 2002
The model described for instance constructors must also be taken into account for CREATE OBJECT.
There are two main methods of creating an instance of a class using CREATE OBJECT:
1. The class has a defined (and implemented) instance constructor
In this case, when you are using CREATE OBJECT, the parameters have to be filled according to the
constructor interface, that is, optional parameters may, and non-optional parameters must be filled
with actual parameters. If the constructor does not have any (formal) parameters, no parameters may
or can be filled.
2. The instance constructor for that class has not been defined
In this case, you must search the inheritance hierarchy for the next highest superclass in which the
instance constructor has been defined and implemented. Then, when you are using CREATE
OBJECT, the parameters of that class must be filled (similarly to the first method above).
If there is no superclass with a defined instance constructor, then no parameters may or can be filled.
If no instance constructor has been defined for a class, then a default constructor, which is implicitly
always present is used. This default constructor calls the constructor from the immediate superclass.
(C) SAP AG
BC401
8-10
Public components
Visible to all
Direct access
...
PROTECTED SECTION.
DATA tank TYPE REF TO lcl_tank.
Protected components
PUBLIC SECTION.
PRIVATE SECTION.
DATA make TYPE string.
ENDCLASS.
Private components
lcl_vehicle
- make
- modell
# tank
...
+constructor
+display_attributes
+get_count
+ public
# protected
- private
SAP AG 2002
Inheritance provides an extension of the visibility concept: There are protected components. The
visibility of these components lies between that of the public components (visible to all users, all
subclasses, and the class itself), and private (visible only to the class itself). Protected components are
visible to and can be used by all subclasses and the class itself.
Subclasses cannot access the private components (particularly attributes) of the superclass. Private
components are genuinely private. This is particularly important if a (super)class needs to make local
enhancements to handle errors: It can use private components to do this without knowing or invalidating
subclasses.
In ABAP Objects, you must keep to the section sequence PUBLIC, PROTECTED, PRIVATE.
(C) SAP AG
BC401
8-11
Can be addressed
"from outside" for
all clients
(5) lcl_bus
Public
Private
Inherited
get_make
set_make
get_count
display_attributes
estimate_fuel
Protected
Inherited
tank
Can only be
addressed within
the class
SAP AG 2002
In this example, lcl_bus, a subclass of lcl_vehicle, can directly access the protected attribute
tank. If the attribute was private, the subclasses would only be able to access tank using non-private
methods.
(C) SAP AG
BC401
8-12
lcl_vehicles
estimate_fuel
lcl_car
lcl_truck
estimate_fuel
estimate_fuel
lcl_bus
estimate_fuel
In ABAP Objects, you can not only add new components, but also provide inherited methods with new
implementations. This is known as redefinition. You can only redefine (public and protected) instance
methods, other components (static methods, attributes and so on) cannot be redefined. Changes to
method parameters (signature changes) are not possible.
In UML, the redefinition of a method is represented by listing the method again in the subclass. Methods
(and all other components) that are inherited but not redefined are not listed in the subclass, as their
existence there is clear from the specialization relationship.
You should not confuse redefinition with "overloading". The latter describes the ability of a class to have
methods with the same name but a different signature. This is not available in ABAP Objects.
There is only one static event per roll area. In this way, a class that defines a public or protected static
attribute shares this attribute with all its subclasses. The significant point here is that subclasses do not
each receive their own copy of the static attribute.
(C) SAP AG
BC401
8-13
lcl_bus
lcl_truck
- max_passengers
...
- max_cargo
...
+ constructor
+ estimate_fuel
+ constructor
+ estimate_fuel
METHOD estimate_fuel.
DATA: total_weight ...
* just an example!
total_weight = max_passengers *
average_weight + weight.
re_fuel = total_weight *
im_distance * factor.
ENDMETHOD.
METHOD estimate_fuel.
DATA: total_weight ...
* just an example!
total_weight = max_cargo +
weight.
re_fuel = total_weight *
im_distance * factor.
ENDMETHOD.
SAP AG 2002
In the above example, both redefined methods calculate the return code in different ways. The important
point is that the semantics stay the same.
(C) SAP AG
BC401
8-14
SAP AG 2002
(C) SAP AG
BC401
8-15
Inheritance Exercises
Unit: Inheritance
Topic: Creating Class Hierarchies
At the conclusion of these exercises, you will be able to:
Define subclasses
Redefine superclass methods in subclasses
Model solution: SAPBC401_INHS_MAIN_A
SAPBC401_INHS_A include program
Your program: ZBC401_##_MAIN_AIRPLANE
ZBC401_##_AIRPLANE include program
1-1
Make both instance attributes of the class lcl_airplane visible to their subclasses
(PRIVATE SECTION -> PROTECTED SECTION).
1-2
Create the subclass lcl_passenger_plane for the class lcl_airplane. Also, create this
subclass in your include program.
1-2-1 The class is to have a private instance attribute max_seats with the same
type as table field sflight-seatsmax.
1-2-2 A public constructor is to be defined and implemented in the class. This
constructor provides all instance attributes in the class with values.
1-2-3 Redefine the method display_attributes of the class lcl_airplane, so that,
using the redefined method, the WRITE statement displays all instance
attributes.
1-3
Create the subclass lcl_cargo_plane for the class lcl_airplane. Also, create this
subclass in your include program.
1-3-1 The class is to have a private instance attribute max_cargo with the same
type as the table field scplane-cargomax.
1-3-2 A public constructor is to be defined and implemented in the class. This
constructor provides all instance attributes in the class with values.
1-3-3 Redefine the method display_attributes of the class lcl_airplane, so that,
using the redefined method, the WRITE statement displays all instance
attributes.
(C) SAP AG
BC401
8-16
1-4
1-5
Follow the program flow in the Debugger, paying special attention to the call of
display_attributes.
1-6
1-7
Is it necessary for the subclasses to directly access the attributes name and
planetype of the superclass to initialize them?
Or, to formulate it differently:
If these attributes remained in the private visibility area of the superclass, how
would the subclasses have to access the attributes?
(C) SAP AG
BC401
8-17
Inheritance Solutions
Unit: Inheritance
Topic:
*&---------------------------------------------------------------------*
*& Report
SAPBC401_INHS_MAIN_a
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_inhs_main_a.
INCLUDE <icon>.
INCLUDE sapbc401_inhs_a.
DATA: r_plane TYPE REF TO lcl_airplane,
r_cargo type ref to lcl_cargo_plane,
r_passenger type ref to lcl_passenger_plane,
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION.
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_passenger EXPORTING
im_name = 'LH BERLIN'
im_planetype = '747-400'
im_seats = 345.
CREATE OBJECT r_cargo EXPORTING
im_name = 'US HErcules'
im_planetype = '747-500'
im_cargo = 533.
(C) SAP AG
BC401
8-18
r_cargo->display_attributes( ).
r_passenger->display_attributes( ).
lcl_airplane=>display_n_o_airplanes( ).
(C) SAP AG
BC401
8-19
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_INHS_a
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
*...
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
"---------------------METHODS: constructor IMPORTING im_name TYPE string
im_planetype TYPE saplane-planetype
im_cargo TYPE scplane-cargomax.
METHODS: display_attributes REDEFINITION.
PRIVATE SECTION.
"---------------------DATA: max_cargo TYPE scplane-cargomax.
ENDCLASS.
"lcl_cargo_plane DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_cargo_plane IMPLEMENTATION.
METHOD constructor.
CALL METHOD super->constructor( im_name
= im_name
im_planetype = im_planetype ).
(C) SAP AG
BC401
8-20
max_cargo = im_cargo.
ENDMETHOD.
"constructor
METHOD display_attributes.
super->display_attributes( ).
WRITE: / 'Max Cargo = ', max_cargo.
ULINE.
ENDMETHOD.
ENDCLASS.
(C) SAP AG
"display_attributes
"lcl_cargo_plane IMPLEMENTATION
BC401
8-21
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..
PUBLIC SECTION.
METHODS: constructor IMPORTING im_name TYPE string
im_planetype TYPE saplane-planetype
im_seats TYPE sflight-seatsmax.
METHODS: display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: max_seats TYPE sflight-seatsmax.
ENDCLASS.
"lcl_passenger_plane DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_passenger_plane IMPLEMENTATION.
METHOD constructor.
CALL METHOD super->constructor( im_name
= im_name
im_planetype = im_planetype ).
max_seats = im_seats.
ENDMETHOD.
"constructor
METHOD display_attributes.
super->display_attributes( ).
WRITE: / 'Max Seats = ', max_seats.
ULINE.
ENDMETHOD.
ENDCLASS.
(C) SAP AG
"display_attributes
"lcl_passenger_plane IMPLEMENTATION
BC401
8-22
(C) SAP AG
BC401
8-23
Casting
Contents:
Cast
Polymorphism
SAP AG 2002
(C) SAP AG
BC401
9-1
SAP AG 2002
(C) SAP AG
BC401
9-2
Casting
and
Data Types
ts in
Data Objec
Detail
e
Inheritanc
ming
ed Program
nt
Object-Orie
of
es
pl
ci
Prin
n
and Desig
Analysis
ing
Programm
d
te
en
Object-Ori
to
n
tio
Introduc
al
Using Intern
Tables
rams
Calling Prog
Data
and Passing
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
9-3
Casting (1)
Narrowing
Narrowing cast
cast
Widening
Widening cast
cast
Inheritance
Inheritance and
and polymorphism
polymorphism
SAP AG 2002
(C) SAP AG
BC401
9-4
(5) lcl_truck
Public
Geerbt
r_truck
get_make
get_count
r_vehicle
Redefiniert
display_attributes
set_attributes
estimate_fuel
* Narrowing Cast
r_vehicle = r_truck
get_cargo
...
r_vehicle
SAP AG 2002
After the narrowing cast, you can use the r_vehicle reference to access the components of the
truck instance that were inherited from lcl_vehicle - obviously, in some cases with the
limitations entailed by their visibility. You can no longer access the truck-specific part of the instance
(get_cargo in the above example) using the r_vehicle reference.
(C) SAP AG
BC401
9-5
DATA: r_vehicle
r_truck
level
SAP AG 2002
One of the significant principles of inheritance is that an instance from a subclass can be used in any
context, in which an instance from the superclass appears. This is possible because the subclass has
inherited all components from the superclass and therefore has the same interface as the superclass. The
user can therefore address the subclass instance in the same way as the superclass instance.
Variables that point to a superclass instance can also refer to subclass instances at runtime.
The assignment of a subclass instance to a reference variable of the type "reference to superclass" is
described as a narrowing cast, because you are switching from a more detailed view to a one with less
detail.
The description "up-cast" is also used.
What is a narrowing cast used for? A user who is not interested in the finer points of cars, trucks, and
busses (but only, for example, in the fuel consumption and tank gauge) does not need to know about
them. This user only wants and needs to work with (references to) the lcl_vehicle class. However,
in order to allow the user to work with cars, busses, or trucks, you generally need a narrowing cast.
(C) SAP AG
BC401
9-6
A possible client (car rental company for example) wants to access the list of vehicles with identicallynamed services. The client wishes to, for example, calculate the required amount of fuel. The client is
not concerned with the details of how the car, bus, or truck do this.
(C) SAP AG
BC401
9-7
Objects from different classes (lcl_bus, lcl_truck, and lcl_car in the above example ) can be
stored in an internal table consisting of references to the superclass (lcl_vehicle in the above
example),and then processed in a uniform manner using the same access technique.
A client, the car rental company in this example, can then generically access the identically-named
service of the different classes. (This will be discussed in more detail.)
(C) SAP AG
BC401
9-8
When objects from different classes react differently to the same method call, this is known as
polymorphism. To do this, the classes implement the same method in different ways. This can be done
using inheritance, by redefining a method from the superclass in subclasses and implementing it
differently. (Interfaces will be discussed later; they too can enable polymorphic behavior.)
When an instance receives a message to execute a particular method, then that method is executed if it
has been implemented by the class the instance belongs to. If the class has not implemented that method,
but only inherited and not redefined it, then a search up through the inheritance hierarchy is carried out
until an implementation of that method is found.
The dynamic type, not the static type of the reference variable is used to search for the implementation
of a method (will be discussed later). r_vehicle->estimate_fuel above therefore uses the class
of the instance that r_vehicle actually refers to to search for the implementation of
estimate_fuel. The static type for r_vehicle, which is always REF TO lcl_vehicle is not
used.
Polymorphism is one of the main strengths of inheritance: The user can work in the same way with
different classes, regardless of their implementation. The search for the right implementation of a
method is carried out by the runtime system, not the user.
(C) SAP AG
BC401
9-9
Which coding is actually executed when estimate_fuel is called depends on the dynamic type of
the reference variable r_vehicle, that is it depends on which object from which (sub)class
r_vehicle refers to.
You can use polymorphism to write programs that are generic to a high degree and that do not even need
to be changed if use cases are added. In the simple example above, this means that, should a further
subclass be added, for example for motorbikes, the above coding would not need to be changed.
A redefined method will be created in the server class lcl_motorbike.
(C) SAP AG
BC401
9-10
DATA: r_vehicle
TYPE REF TO lcl_vehicle.
(5) lcl_truck
Inherited /
redefined
Estimate_
fuel
Estimate_fuel
(2) lcl_bus
Inherited /
redefined
r_vehicle
Estimate_
fuel
Estimate_fuel
SAP AG 2002
(C) SAP AG
BC401
9-11
(C) SAP AG
BC401
9-12
Casting (2)
Narrowing
Narrowing cast
cast
Widening
Widening cast
cast
Inheritance
Inheritance and
and polymorphism
polymorphism
SAP AG 2002
(C) SAP AG
BC401
9-13
The client, the car rental company in the above example, wants to execute a function for specific
vehicles form the list (vehicle_list). For example, the client wants to ascertain the truck with the
largest cargo capacity.
However, not all vehicles are in the trucks list, it also includes references to cars and busses.
(C) SAP AG
BC401
9-14
The type of case described above is known as a widening cast (or "down cast") because it changes from
a less detailed view to one with more detail. The target reference (r_truck in the above example) must
correspond to the object reference (r_vehicle in the above example), that is the instance must have
the details implied by the reference.
The widening cast logically represents the opposite of the narrowing cast. The widening cast cannot be
checked statically, only at runtime. The Cast Operator ?= (or the equivalent MOVE ... ?TO )
must be used to make this visible.
With this kind of cast, a check is carried out at runtime to ensure that the current content of the source
variable corresponds to the type requirements of the target variables. In this example, it checks that the
dynamic type of the source reference r_vehicle is compatible with the static type of the target
reference r_truck. If it is, the assignment is carried out. Otherwise, an exception that can be handled is
raised, and the original value of the target variable remains the same. This exception of the error class
CX_SY_MOVE_CAST_ERROR can be caught using TRY-ENDTRY and the CATCH statement. (This
will be discussed in more detail later.)
Another way of preventing the runtime error would be to use RTTI (Runtime Type Identification). This
is a class library for ascertaining type attributes at runtime.
(C) SAP AG
BC401
9-15
Casting (3)
Narrowing
Narrowing cast
cast
Widening
Widening cast
cast
Inheritance
Inheritance and
and polymorphism
polymorphism
SAP AG 2002
(C) SAP AG
BC401
9-16
Rules:
Using inheritance:
Allows you to enhance classes using
generalization/specialization and hence achieve
better software structure
Provides possibility of polymorphic behavior,
"generic programming"; CASE constructions no
longer needed
SAP AG 2002
A subclass instance can be used in any context in which a superclass instance also appears. Moreover:
The user does not and is not intended to know whether they are dealing with a subclass or a superclass
instance. The user works only with references to the superclass and must rely on the inherited
components behaving in the subclass instances exactly as they do in the superclass instances, otherwise
the program will not work.
On the other hand, this ensures useful restrictions on the implementation of the subclasses: Inherited
components must keep their inherited semantics. You cannot use inherited attributes or events in any
way other than intended in the superclass, and you cannot change method semantics by redefinition.
You must avoid "code inheritance": It is not correct for one class to inherit from another simply because
part of the functionality required is already implemented there.
(C) SAP AG
BC401
9-17
Rules:
car
car_red
si
gn
car_blue
change_width
Superclass
Rectangular
si
gn
Subclass
square
change_height
SAP AG 2002
(C) SAP AG
BC401
9-18
SAP AG 2002
(C) SAP AG
BC401
9-19
Casting Exercises
Unit: Casting
Topic: Polymorphism
At the conclusion of these exercises, you will be able to:
Describe polymorphism and inheritance
Use generic programming for inheritance relationships and implement
polymorphic method calls
Model solution: SAPBC401_CASS_MAIN_A
SAPBC401_INHS_A include program
1-1
1-2
In your main program, define an internal table for buffering airplane objects. The type
of the internal table should be REF TO lcl_airplane.
1-3
Try to insert the planes (passenger and cargo) into this internal table and execute the
display_attributes method for every plane in a LOOP.
Read the internal table in the LOOP using the auxiliary reference variable r_airplane
(type REF TO lcl_airplane).
1-3-1 Was this successful?
1-3-2 Check the internal table and the execution of the display_attributes method in
the Debugger
1-3-3 Which source code is executed when the display_attributes method is called,
the original method from the superclass or the relevant redefined methods from
the subclasses? What would happen if one of these methods had not been
redefined in the subclass?
(C) SAP AG
BC401
9-20
2-1
Copy the definition of the class lcl_carrier from the template SAPBC401_CAST_B to
your own include program ZBC401_##_AIRPLANE (hence adding this class to your
include program).
2-2
2-3
(C) SAP AG
BC401
9-21
Casting Solutions
Unit: Casting
Topic:
Polymorphism
*&---------------------------------------------------------------------*
*& Report
SAPBC401_CASS_MAIN_a
*&
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_cass_main_a.
INCLUDE <icon>.
INCLUDE sapbc401_inhs_a.
START-OF-SELECTION.
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_passenger EXPORTING
im_name = 'LH BERLIN'
im_planetype = '747-400'
im_seats = 345.
APPEND r_passenger TO plane_list.
CREATE OBJECT r_cargo EXPORTING
(C) SAP AG
BC401
9-22
lcl_airplane=>display_n_o_airplanes( ).
(C) SAP AG
BC401
9-23
*&---------------------------------------------------------------------*
*& Report
SAPBC401_CASS_MAIN_b
*&
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_cass_main_b.
INCLUDE <icon>.
INCLUDE sapbc401_cass_b.
START-OF-SELECTION.
*##############################
***** Create Carrier ********************************************
create object r_carrier exporting im_name = 'Smile&Fly-Travel'.
***** Passenger Plane ********************************************
CREATE OBJECT r_passenger EXPORTING
im_name = 'LH BERLIN'
im_planetype = '747-400'
im_seats = 345.
***** cargo Plane ************************************************
CREATE OBJECT r_cargo EXPORTING
im_name = 'US HErcules'
im_planetype = '747-500'
im_cargo = 533.
***** insert planes into itab if client ***************************
r_carrier->add_airplane( r_passenger ).
(C) SAP AG
BC401
9-24
r_carrier->add_airplane( r_cargo ).
(C) SAP AG
BC401
9-25
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
* Class definitions of ... lcl_airplane, cargo- and passenger_plane
* ...
* ...
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_carrier DEFINITION.
PUBLIC SECTION.
"---------------------------------------METHODS: constructor IMPORTING im_name TYPE string,
get_name RETURNING value(ex_name) TYPE string,
add_airplane IMPORTING
im_plane TYPE REF TO lcl_airplane,
display_airplanes,
display_attributes.
PRIVATE SECTION.
"----------------------------------DATA: name
TYPE string,
*---------------------------------------------------------------------*
CLASS lcl_carrier IMPLEMENTATION.
METHOD add_airplane.
APPEND im_plane TO airplane_list.
ENDMETHOD.
METHOD display_attributes.
WRITE: icon_flight AS ICON, name . uline. uline.
display_airplanes( ).
ENDMETHOD.
(C) SAP AG
BC401
9-26
METHOD display_airplanes.
data: r_plane type ref to lcl_airplane.
loop at airplane_list into r_plane.
r_plane->display_attributes( ).
endloop.
ENDMETHOD.
METHOD constructor.
name = im_name.
ENDMETHOD.
METHOD get_name.
ex_name = name.
ENDMETHOD.
ENDCLASS.
(C) SAP AG
BC401
9-27
Interfaces
Contents:
Interfaces
Compound interfaces
Polymorphism
SAP AG 2002
(C) SAP AG
BC401
10-1
SAP AG 2002
(C) SAP AG
BC401
10-2
Interfaces
Casting
and
Data Types
ts in
Data Objec
Detail
e
Inheritanc
ing
Programm
nt
Orie ed
of Objectes
pl
ci
rin
P
n
and Desig
Analysis
ing
Programm
d
te
Orien
to Objectn
tio
uc
Introd
al
Using Intern
Tables
rams
Calling Prog
Data
and Passing
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
10-3
Interfaces (1)
Interfaces:
Interfaces: Principles
Principles
Working
Working with
with interfaces
interfaces
Preview:
Preview: Compound
Compound interfaces
interfaces
SAP AG 2002
(C) SAP AG
BC401
10-4
Interfaces: Use
Interfaces
Service 1
Service 2
Service 3
...
Shared services
lcl_carrier
lcl_rental
lcl_hotel
lcl_vehicles
lcl_airplane
...
...
...
...
SAP AG 2002
In ABAP Objects, interfaces are implemented in addition to and independently of classes. Interfaces
only describe the external point of contact of a class (protocols), they do not contain any implementation.
Interfaces are usually defined by a user. The user describes in the interface which services (technical and
semantic) it needs in order to carry out a task. The user never actually knows the providers of these
services, but communicates with them through the interface. In this way the user is protected from actual
implementations and can work in the same way with different classes/objects, as long as they provide the
services required. This is known as polymorphism with interfaces.
(C) SAP AG
BC401
10-5
Interfaces: Services
display_partner
check_availability
...
Client uses
Interface
Shared services
lcl_carrier
lcl_rental
lcl_hotel
lcl_vehicles
lcl_airplane
...
...
...
...
SAP AG 2002
In the above example, a client wants to use the same services of different server classes
(lcl_carrier, lcl_hotel, and lcl_rental) in the same way. There are different
implementations of the services in the server classes (polymorphism).
The following are examples of shared services of the server classes in the above case:
display_partner, check_availability, booking, or cancel_booking.
(C) SAP AG
BC401
10-6
lcl_travel_agency
uses
Client
It is possible to
Implementation
implement
several
mehrerer
Interfaces
interfaces
mglich
!
<<Interface>>
<<Interface>>
lif_partners
lif_license
implements
lcl_carrier
...
lcl_rental
lcl_hotel
lcl_vehicles
lcl_airplane
...
...
...
...
SAP AG 2002
In UML, interfaces can represented in the same way as classes. However, they always have the
stereotype interface above their name and can therefore be distinguished from classes.
The use of an interface is represented by a dotted line with a two-sided arrow from the user to the
interface, the stereotype uses is optional. The fact that a class implements an interface is represented
by a dotted line with a three-sided arrow from the class to the interface. The similarity to the
representation of inheritance is intentional, because the interface can be seen as a generalization of the
class implemented or the class can be seen as a specialization of the interface.
In ABAP Objects, the same components can be defined in interfaces and in classes. This allows you to
shift part of the public point of contact of a class into an interface, even though the class is already in
use; users will not notice the difference as long as you use alias names (see appendix) for the
components that are now in the interface.
A class can implement any number of interfaces and an interface can be implemented by any number of
classes. By implementing several interfaces, a class can simulate multiple inheritance. In the example,
lcl_rental implements the interfaces lif_partners and lif_license.
(C) SAP AG
BC401
10-7
Declaring the
interface
Interfaces are
implemented in classes
INTERFACE lif_partners.
METHODS: display_partner.
ENDINTERFACE.
ENDMETHOD.
ENDCLASS.
Interface
resolution
operator
SAP AG 2002
In ABAP Objects, the same components (attributes, methods, constants, types, alias names) can be
defined in an interface in largely the same way as in classes. However, interfaces do not have component
visibility levels.
Interfaces are implemented in classes.
The interface name is listed in the definition part of the class. Interfaces can only be implemented
publicly and are therefore always in the PUBLIC SECTION. If you do not do this, you risk
multiple implementations if a superclass and a subclass both implement the same interface
privately.
The operations defined in the interface are implemented as methods of a class. A check is carried
out to ensure that all the methods defined in the interfaces are actually present in the
implementation part of the class (for global interfaces, a missing or superfluous implementation of
an interface method results in a warning).
The attributes, events, constants, and types defined in the interface are automatically available to
the class carrying out the implementation.
Interface components are addressed in the class carrying out the implementation by prefixing
the interface name, followed by a tilde (the Interface Resolution Operator):
<interfacename>~<componentname>.
(C) SAP AG
BC401
10-8
Interfaces: Features
Polymorphism
Code 2
Code 1
Code 4
Abstraction
Interface as a generalization of
the implementing class
super1
display_partner
Code 3
Interf.
sub2
SAP AG 2002
Interfaces are the means of choice for describing external points of contact or protocols, without linking
them to a type of implementation. An extra layer is introduced between the client and the server to
protect the client explicitly from the server, thereby making the client independent.
Interfaces enable you to work uniformly with different classes (providers/servers). In particular, they
always ensure polymorphic behavior as they do not have their own implementation, but instead allow the
providers to carry it out.
The definition of an interface is always an abstraction: The user wants to handle various providers in the
same way and must therefore abstract concrete implementations to a description of the services required
to fulfill the task.
You can also use interfaces to achieve multiple inheritance by defining the functionality to be inherited
by a second class as an interface that the inheriting class then has to implement.
(C) SAP AG
BC401
10-9
Interfaces (2)
Interfaces:
Interfaces: Principles
Principles
Working
Working with
with interfaces
interfaces
Preview:
Preview: Compound
Compound interfaces
interfaces
SAP AG 2002
(C) SAP AG
BC401
10-10
lif_partners
display_partner
check_availability
...
implements
lcl_rental
- name
- vehicle_list
+ add_vehicle
+ display_attributes
...
You can access interface components using an object reference, whose class implements the interface.
Syntactically this is done with the interface resolution operator, just as with the method definitions in the
implementation part of the class.
This allows you to differentiate between components defined in the interface and components of the
same name that are defined in the class itself. The reason for this is the shared namespace.
To simplify accessing interface methods you can work with alias names.
Alias names can only appear in the in the declaration part of a class or in the interface definition.
Example for an alias in the interface: ALIASES a1 FOR lif_interface~method1
An alias defined in this way can be directly addressed using r_ref->a1.
(C) SAP AG
BC401
10-11
(1) lcl_rental
Public
Private
r_rental
r_lif
Interface
components
* Narrowing Cast
r_lif = r_rental
display_partner
check_availability
...
r_lif
SAP AG 2002
Interfaces are addressed using interface references. Interface references always refer to instances in the
classes carrying out the implementation. Interface references always have both static and dynamic types.
The assignment of an object reference to an interface reference is known as a narrowing cast since, as
with inheritance, only a part of the object interface is visible once you have assigned the reference.
With an interface reference, you can no longer address all components in the class carrying out the
implementation, but only the components defined in the interface. These components are now addressed
using the interface reference exclusively with their own short name.
When an object reference is assigned to an interface reference, you must be able to convert the dynamic
type of the interface reference to the static type of the object reference - that is, the class that was used to
define the object reference must have implemented the interface of the interface-reference.
(C) SAP AG
BC401
10-12
The travel agent is a user (client) of the created interface. The travel agency keeps references to its
business partners in an internal table. Th type of this internal table is REF TO lif_partners, that is
the reference to the interface lif_partners.
When it is called, the client's public method add_partner is transferred the business partner
references. In the method, the references are inserted into the table partner_list. Therefore, the
interface parameter of the add_partner method has the type REF TO lif_partners.
The aim here is polymorphism: It needs to be possible to generically access the services of the interface
later.
(C) SAP AG
BC401
10-13
Polymorphism can also be used for interfaces: you can use interface references to call methods that can
have a different implementation depending on the object behind the reference.
The dynamic type, not the static type of the reference variable is used to search for the implementation
of a method. In the above example, r_partner->display_partner( ) therefore uses the class
of the instance that r_partner actually refers to to search for the implementation of display. The
static type for r_partner, which is always REF TO lif_partners, is not used.
(C) SAP AG
BC401
10-14
The widening cast is, as with inheritance, the opposite of the narrowing cast: Here it is used to retrieve a
class reference from an interface reference. Obviously it cannot be statically checked, since an interface
can be implemented by more than one class.
An object reference cannot be assigned to an interface reference if it has itself not implemented the
corresponding interface. It cannot be assigned even if a subclass has implemented the interface and the
interface reference points to an object in this class.
Assignments between interface references whose interfaces are not related to each other cannot be
checked statically and must therefore be formulated using the cast operator ?=.
For this type of assignment, a check must be carried out at runtime to see whether the class of the
instance that the source reference points to also supports the interface that the target reference refers to.
If this is the case, the cast is carried out, otherwise the exception that can be handled of the class
CX_SY_MOVE_CAST_ERROR is raised.
(C) SAP AG
BC401
10-15
Interfaces (3)
Interfaces:
Interfaces: Principles
Principles
Working
Working with
with interfaces
interfaces
Preview:
Preview: Compound
Compound interfaces
interfaces
SAP AG 2002
(C) SAP AG
BC401
10-16
Compound Interfaces
Interface
lcl_hotel
lif_partners
lcl_rental
lcl_carrier
Solution:
Compound
interfaces
Interface
lif_room_booking
book_room
Problem:
Extending
interfaces
lif_partners
Interface
lcl_hotel
lcl_carrier
lcl_rental
SAP AG 2002
ABAP Objects contains a composition model for interfaces. A compound interface contains other
interfaces as components (component interfaces) and summarizes the extension of these component
interfaces. An elementary interface does not itself contain other interfaces.
One interface can be used as a component interface in several compound interfaces.
UML only deals with the specialization and generalization of interfaces. This relationship is represented
by a dotted line with a three-sided arrow from the specialized to the generalized interface.
Compound interfaces in ABAP Objects can always be seen as specializations of their component
interfaces and represented as such in UML.
(C) SAP AG
BC401
10-17
DATA: i_partner
i_room_book
...
i_partner = i_room_book.
Narrowing Cast
i_room_book->lif_partners~display_partner( ).
* i_partner->display_partner( ) also possible
i_room_book ?= i_partner.
Widening Cast
SAP AG 2002
In a compound interface, the components of the component interface keep their original names, that is
<component-interfacename>~<componentname>; no more prefixes are added. In other
words, all components in a compound interface are on the same level, and components inherited from
component interfaces are marked with the usual interface prefix.
This equality principle for compound interfaces also affects how they are implemented. The procedure is
as follows: First, implement the elementary interfaces, then the additional methods from the compound
interfaces. For multiple compound interfaces, the process is simply repeated. In the class carrying out the
implementation, all components of all interfaces implemented are again on the same level.
This means that interface components only ever exist once and are known by their original names
<interfacename>~<componentname>. This is true both for compound interfaces and for the
classes that implement them.
(C) SAP AG
BC401
10-18
SAP AG 2002
(C) SAP AG
BC401
10-19
Interfaces Exercises
Unit: Interfaces
Topic: Defining Interfaces
At the conclusion of these exercises, you will be able to:
Define and implement interfaces
The classes lcl_rental, lcl_vehicle, and their subclasses are to be added to the existing UML
diagram.
The classes lcl_rental, lcl_carrier, and later lcl_hotel will all store separate services and
provide a possible client (to be defined later) using an interface lif_partners.
1-1
Add the interface lif_partners to your UML diagram. display_partner is to be the only
interface method. What are the roles of the classes lcl_rental, lcl_carrier, and
lcl_hotel? Depict this in the UML diagram by adding text and arrows.
Fill in the UML diagram on the next page.
1-2
1-3
(C) SAP AG
BC401
10-20
1-4
1-5
In the main program, create some instances for lcl_rental, lcl_vehicle, and so on by
copying the relevant code from the template SAPBC401_VEHT_MAIN_A. Call the
method display_attributes of the class lcl_rental.
Start your program. You should see an airline with your planes and a car rental
company with various vehicles.
(You will use the interface in the next exercise.)
(C) SAP AG
BC401
10-21
(C) SAP AG
BC401
10-22
Exercises
Unit: Interfaces
Topic: Using Interfaces
At the conclusion of these exercises, you will be able to:
Define and implement interfaces
Use polymorphism with interfaces
Model solution: SAPBC401_INTS_MAIN_B
SAPBC401_VEHD_G include program
SAPBC401_INTS_A include program
Now the class lcl_travel_agency (travel agency) is to be added to the existing UML diagram. It
will use the interface to access the classes lcl_rental, lcl_carrier, lcl_hotel (not yet
implemented).
2-1
Add the class lcl_travel_agency to your UML diagram. What is the role of this class?
Depict this in the UML diagram by adding text and arrows.
Fill in the UML diagram on the next page.
2-2
(C) SAP AG
BC401
10-23
2-3
2-4
(C) SAP AG
BC401
10-24
Interfaces Solutions
Unit: Interfaces
Topic:
Defining Interfaces
*&---------------------------------------------------------------------*
*& Report
SAPBC401_INTS_MAIN_A
*&
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_ints_main_a.
START-OF-SELECTION.
*##############################
***** Create Carrier ********************************************
create object r_carrier exporting im_name = 'Smile&Fly-Travel'.
(C) SAP AG
BC401
10-25
(C) SAP AG
BC401
10-26
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_INTS_a
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
...
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
*---------------------------------------------------------------------*
CLASS lcl_carrier DEFINITION.
PUBLIC SECTION.
"---------------------------------------INTERFACES lif_partners.
METHODS: constructor IMPORTING im_name TYPE string,
get_name RETURNING value(ex_name) TYPE string,
add_airplane IMPORTING
im_plane TYPE REF TO lcl_airplane,
display_airplanes,
display_attributes.
PRIVATE SECTION.
"----------------------------------DATA: name
TYPE string,
"lcl_carrier DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_carrier IMPLEMENTATION.
METHOD lif_partners~display_partner.
display_airplanes( ).
ENDMETHOD.
"lif_partners~display_partner
METHOD add_airplane.
APPEND im_plane TO airplane_list.
ENDMETHOD.
(C) SAP AG
"add_airplane
BC401
10-27
METHOD display_attributes.
WRITE: icon_flight AS ICON, name . ULINE. ULINE.
display_airplanes( ).
ENDMETHOD.
"display_attributes
METHOD display_airplanes.
DATA: r_plane TYPE REF TO lcl_airplane.
LOOP AT airplane_list INTO r_plane.
r_plane->display_attributes( ).
ENDLOOP.
ENDMETHOD.
"display_airplanes
METHOD constructor.
name = im_name.
ENDMETHOD.
"constructor
METHOD get_name.
ex_name = name.
ENDMETHOD.
ENDCLASS.
(C) SAP AG
"get_name
"lcl_carrier IMPLEMENTATION
BC401
10-28
Solutions
Unit: Interfaces
Topic:
Using Interfaces
*&---------------------------------------------------------------------*
*& Report
SAPBC401_INTS_MAIN_B
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_ints_main_b.
(C) SAP AG
BC401
10-29
BC401
10-30
(C) SAP AG
BC401
10-31
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_VEHD_g
*&---------------------------------------------------------------------*
*---------------------------------------------------------------------*
* define client lcl_travel_agency
* it will use the interface lif_partners
*---------------------------------------------------------------------*
INTERFACE lif_partners.
METHODS display_partner.
ENDINTERFACE.
"lif_partners
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
"------------------METHODS: get_average_fuel IMPORTING im_distance TYPE s_distance
im_fuel TYPE ty_fuel
RETURNING value(re_avgfuel) TYPE ty_fuel.
METHODS
METHODS
display_attributes.
METHODS
METHODS
TYPE string.
METHODS
init_make.
CLASS-DATA:
n_o_vehicles TYPE i.
ENDCLASS.
"lcl_vehicle DEFINITION
*---------------------------------------------------------------------*
*
(C) SAP AG
BC401
10-32
*---------------------------------------------------------------------*
CLASS lcl_vehicle IMPLEMENTATION.
METHOD get_average_fuel.
re_avgfuel = im_distance / im_fuel.
ENDMETHOD.
"get_average_fuel
METHOD constructor.
make = im_make.
ADD 1 TO n_o_vehicles.
ENDMETHOD.
"constructor
METHOD set_make.
IF im_make IS INITIAL.
init_make( ).
ELSE.
make = im_make.
ENDIF.
ENDMETHOD.
"set_make
METHOD init_make.
make = 'default make'.
ENDMETHOD.
"init_make
METHOD get_make.
ex_make = make.
ENDMETHOD.
"get_make
METHOD display_attributes.
WRITE: make.
ENDMETHOD.
"display_attributes
METHOD get_count.
re_count = n_o_vehicles.
ENDMETHOD.
ENDCLASS.
"get_count
"lcl_vehicle IMPLEMENTATION
*---------------------------------------------------------------------*
(C) SAP AG
BC401
10-33
*---------------------------------------------------------------------*
CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.
PUBLIC SECTION.
"------------------METHODS:
METHODS
display_attributes REDEFINITION.
METHODS
PRIVATE SECTION.
"------------------DATA: max_cargo TYPE ty_cargo.
ENDCLASS.
"lcl_vehicle DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_truck IMPLEMENTATION.
METHOD constructor.
super->constructor( im_make ).
max_cargo = im_cargo.
ENDMETHOD.
"constructor
METHOD display_attributes.
WRITE: / icon_ws_truck AS ICON.
super->display_attributes( ).
WRITE: 20 ' Cargo = ', max_cargo.
ULINE.
ENDMETHOD.
"display_attributes
METHOD get_cargo.
re_cargo = max_cargo.
ENDMETHOD.
(C) SAP AG
"get_cargo
BC401
10-34
ENDCLASS.
"lcl_vehicle DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle.
PUBLIC SECTION.
"------------------METHODS:
METHODS
display_attributes REDEFINITION.
PRIVATE SECTION.
"------------------DATA: max_passengers TYPE i.
ENDCLASS.
"lcl_vehicle DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_bus IMPLEMENTATION.
METHOD constructor.
super->constructor( im_make ).
max_passengers = im_passengers.
ENDMETHOD.
"constructor
METHOD display_attributes.
WRITE: / icon_transportation_mode AS ICON.
super->display_attributes( ).
WRITE:
ULINE.
ENDMETHOD.
(C) SAP AG
"display_attributes
BC401
10-35
ENDCLASS.
"lcl_vehicle DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_rental DEFINITION.
PUBLIC SECTION.
"------------------METHODS:
METHODS
METHODS
display_attributes.
INTERFACES: lif_partners.
PRIVATE SECTION.
"------------------DATA: name TYPE string,
vehicle_list TYPE TABLE OF REF TO lcl_vehicle.
ENDCLASS.
"lcl_rental DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_rental IMPLEMENTATION.
METHOD lif_partners~display_partner.
display_attributes( ).
ENDMETHOD.
METHOD
"lif_partners~display_partner
constructor.
name = im_name.
ENDMETHOD.
METHOD
"constructor
add_vehicle.
"add_vehicle
display_attributes.
10-36
WRITE:
"display_attributes
ENDCLASS.
"lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_travel_agency DEFINITION.
PUBLIC SECTION.
"------------------METHODS:
METHODS
METHODS
display_agency_partners.
PRIVATE SECTION.
"------------------DATA: name TYPE string,
partner_list TYPE TABLE OF REF TO lif_partners.
ENDCLASS.
"lcl_travel_agency DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_travel_agency IMPLEMENTATION.
METHOD display_agency_partners.
DATA: r_partner TYPE REF TO lif_partners.
WRITE: icon_dependents AS ICON, name.
WRITE:
"display_agency_partners
constructor.
name = im_name.
(C) SAP AG
BC401
10-37
ENDMETHOD.
METHOD
"constructor
add_partner.
(C) SAP AG
"add_partner
"lcl_travel_agency IMPLEMENTATION
BC401
10-38
Events
Contents:
SAP AG 2002
(C) SAP AG
BC401
11-1
SAP AG 2002
(C) SAP AG
BC401
11-2
Events
Interfaces
and
Data Types
ts in
Data Objec
Detail
Casting
e
Inheritanc
ing
Programm
nt
Orie ed
of Objectes
pl
ci
rin
P
n
and Desig
Analysis
ing
rogramm
P
d
te
en
Object-Ori
to
n
tio
Introduc
al
Using Intern
Tables
rams
Calling Prog
Data
and Passing
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
11-3
By triggering an event, an object or class announces a change of state, or that a certain state has been
achieved.
In the example, the class car triggers the event created. Other classes subscribe to this event (triggered
when a car is instantiated) and process it. The car rental company wants to be informed of completion;
the car is registered at the vehicle registration office.
Note:
The events discussed here are not the events of the ABAP runtime system (such as INITIALIZATION,
START-OF-SELECTION, and so on) and not the events of background processing or workflow.
(C) SAP AG
BC401
11-4
Features
Areas of use
GUI implementations
SAP AG 2002
Events link objects or classes more loosely than direct method calls do. Method calls establish precisely
when and in which statement sequence the method is called. However, with events, the reaction of the
object to the event is triggered by the event itself.
Events are most often used in GUI implementations.
Other external object models, such as COM, ActiveX controls, and so on, also provide events.
(C) SAP AG
BC401
11-5
Rules:
Triggering events
1
Handling events
3
SAP AG 2002
(C) SAP AG
BC401
11-6
(C) SAP AG
BC401
11-7
Events are registered using the SET HANDLER statement. Registration is only active at program
runtime. Events cannot be persistent.
You want to register an object to an event belonging to another object. The SET HANDLER statement
enters the registration in that object's list. All handlers for one event are entered in this list.
When the event is triggered, the list shows which event handler methods need to be called.
(C) SAP AG
BC401
11-8
Event handler methods are triggered by events (RAISE EVENT), although they can also be called like
normal methods (CALL METHOD).
The interface of the event handler method consists solely of IMPORTING parameters. You can only use
parameters from the definition of the corresponding events (event interface). An event interface, which
only has EXPORTING parameters, is defined using the EVENTS statement in the declaration of the
event. The parameters are typed in the event definition and the typing is passed to the event handler
method, that is, the interface parameters of the event handler method cannot be typed in the definition of
the event handler method.
In addition to the explicitly defined event interface parameters, the implicit parameter sender can also
be listed as an IMPORTING parameter for instance events. This passes on a reference to the object that
triggered the event.
(C) SAP AG
BC401
11-9
When an event is triggered, only those event handler methods are executed that have, by this point,
registered themselves using SET HANDLER.
You can register an event using ACTIVATION 'X', and deregister it using ACTIVATION space. If
you do not specify ACTIVATION, then the event registers (default behavior).
You can register several methods in one SET HANDLER statement:
SET HANDLER <ref_handle1>-><handler_method1>
...
<ref_handleN>-><handler_methodN>
FOR <ref_sender> | FOR ALL INSTANCES.
(C) SAP AG
BC401
11-10
Every object that has defined events has an internal table, the handler table. All objects that have
registered for events are entered in this table together with their event handler methods.
Objects that have registered themselves for an event that is still "active" also remain "active". The
methods of these objects are called when the event is triggered, even if they can no longer be reached
using main memory references.
(C) SAP AG
BC401
11-11
With regard to the Garbage Collector, registration has the same effect
as a reference to the registered object
Event handler methods, however, can only have the same visibility or more
restricted visibility than the events they refer to
SAP AG 2002
If several objects have registered for an event, then the sequence in which the event handler methods are
called is not defined, that is, there is no guaranteed sequence in which the event handler methods are
called.
If a new event handler is registered in an event handler method for an event that has just been triggered,
then this event handler is added to the end of the sequence and is then also executed when its turn comes.
If an existing event handler is deregistered in an event handler method, then this handler is deleted from
the event handler method sequence.
Events are also subject to the visibility concept and can therefore be either public, protected, or private.
Visibility specifies who can handle an event:
PUBLIC: All users
PROTECTED: Only users within that class or its subclasses
PRIVATE: Only users within that class
Event handler methods also have visibility attributes. Event handler methods, however, can only have
the same visibility or more restricted visibility than the events they refer to. The visibility of event
handler methods establishes authorization for SET HANDLER statements; SET HANDLER statements
can be used: Everywhere, in the class and its subclasses, or only within the class.
(C) SAP AG
BC401
11-12
SAP AG 2002
(C) SAP AG
BC401
11-13
Events Exercises
Unit: Events
Topic: Triggering and Handling Events
At the conclusion of these exercises, you will be able to:
Define and trigger events
Handle events
Register event handler methods
As soon as a new airplane is created, this event must be made known to
the airline. .
In the UML diagram decide what steps are needed where for the triggering and
handling of the event airplane_created.
See next page for UML diagram.
1-2
1-3
Handle the event within the class lcl_carrier using the handler method
add_airplane. This method requires a new interface, its implementation must also
be changed slightly.
1-4
1-5
In the debugger, check whether the event is triggered and handled by the event
handler method when the planes are created.
If this does not happen, check whether one of the four important steps for
implementing events was perhaps left out.
(C) SAP AG
BC401
11-14
1-6 Optional:
Implement the event vehicle_created for the car rental company and its corresponding
vehicles.
2 Optional (advanced):
In the UML, there is the possibility of using events when creating the business partners of
the travel agency.
If airlines, car rental companies, or hotels are created, these business partners should
automatically be made known to the travel agency.
2-1
You could solve this using the events carrier_created, rental_created, and
hotel_created. Would this be problematic?
What would be the best solution?
2-2
(C) SAP AG
BC401
11-15
Solutions
Unit:
Events
Topic:
*&---------------------------------------------------------------------*
*& Report
SAPBC401_EVES_MAIN_A
*&
*&---------------------------------------------------------------------*
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_eves_main_a.
(C) SAP AG
BC401
11-16
r_carrier->add_airplane( r_passenger ).
r_carrier->add_airplane( r_cargo ).
r_rental->add_vehicle( r_truck ).
r_rental->add_vehicle( r_bus ).
r_rental->add_vehicle( r_truck ).
BC401
11-17
r_agency->add_partner( r_rental ).
******* show attributes of all partners of travel_agency ******
r_agency->display_agency_partners( ).
(C) SAP AG
BC401
11-18
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_EVES_A
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
"--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
METHODS: constructor IMPORTING
im_name
TYPE string
TYPE saplane-planetype
EXPORTING ex_weight
TYPE s_plan_wei
ex_tankcap
DATA: name
TYPE s_capacity.
TYPE string,
"lcl_airplane DEFINITION
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
(C) SAP AG
BC401
11-19
METHOD constructor.
name
= im_name.
planetype
= im_planetype.
n_o_airplanes = n_o_airplanes + 1.
raise event airplane_created.
ENDMETHOD.
"constructor
METHOD display_attributes.
DATA: weight TYPE saplane-weight,
cap TYPE saplane-tankcap.
WRITE: / icon_ws_plane AS ICON,
/ 'Name of airplane'(001), AT pos_1 name,
/ 'Type of airplane: '(002), AT pos_1 planetype.
get_technical_attributes( EXPORTING im_type = planetype
IMPORTING ex_weight = weight
ex_tankcap = cap ).
WRITE: / 'Weight:'(003), weight,
'Tankkap:'(004), cap.
ENDMETHOD.
"display_attributes
METHOD display_n_o_airplanes.
WRITE: /, / 'Number of airplanes: '(ca1),
AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
ENDMETHOD.
"display_n_o_airplanes
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.
(C) SAP AG
"get_technical_attributes
"lcl_airplane IMPLEMENTATION
BC401
11-20
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
"---------------------METHODS: constructor IMPORTING im_name TYPE string
im_planetype TYPE saplane-planetype
im_cargo TYPE scplane-cargomax.
METHODS: display_attributes REDEFINITION.
PRIVATE SECTION.
"---------------------DATA: max_cargo TYPE scplane-cargomax.
ENDCLASS.
"lcl_cargo_plane DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_cargo_plane IMPLEMENTATION.
METHOD constructor.
CALL METHOD super->constructor
EXPORTING
im_name
= im_name
im_planetype = im_planetype.
max_cargo = im_cargo.
ENDMETHOD.
"constructor
METHOD display_attributes.
super->display_attributes( ).
WRITE: / 'Max Cargo = ', max_cargo.
ULINE.
ENDMETHOD.
(C) SAP AG
"display_attributes
BC401
11-21
ENDCLASS.
"lcl_cargo_plane IMPLEMENTATION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..
PUBLIC SECTION.
METHODS: constructor IMPORTING im_name TYPE string
im_planetype TYPE saplane-planetype
im_seats TYPE sflight-seatsmax.
METHODS: display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: max_seats TYPE sflight-seatsmax.
ENDCLASS.
"lcl_passenger_plane DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_passenger_plane IMPLEMENTATION.
METHOD constructor.
CALL METHOD super->constructor
EXPORTING
im_name
= im_name
im_planetype = im_planetype.
max_seats = im_seats.
ENDMETHOD.
"constructor
METHOD display_attributes.
super->display_attributes( ).
WRITE: / 'Max Seats = ', max_seats.
ULINE.
ENDMETHOD.
(C) SAP AG
"display_attributes
BC401
11-22
ENDCLASS.
"lcl_passenger_plane IMPLEMENTATION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_carrier DEFINITION.
PUBLIC SECTION.
"---------------------------------------INTERFACES lif_partners.
METHODS: constructor IMPORTING im_name TYPE string,
get_name RETURNING value(ex_name) TYPE string,
add_airplane for event airplane_created of lcl_airplane
IMPORTING sender,
display_airplanes,
display_attributes.
PRIVATE SECTION.
"----------------------------------DATA: name
TYPE string,
"lcl_carrier DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_carrier IMPLEMENTATION.
METHOD lif_partners~display_partner.
display_airplanes( ).
ENDMETHOD.
"lif_partners~display_partner
METHOD add_airplane.
APPEND sender TO airplane_list.
ENDMETHOD.
"add_airplane
METHOD display_attributes.
WRITE: icon_flight AS ICON, name . ULINE. ULINE.
display_airplanes( ).
ENDMETHOD.
(C) SAP AG
"display_attributes
BC401
11-23
METHOD display_airplanes.
DATA: r_plane TYPE REF TO lcl_airplane.
LOOP AT airplane_list INTO r_plane.
r_plane->display_attributes( ).
ENDLOOP.
ENDMETHOD.
"display_airplanes
METHOD constructor.
name = im_name.
set handler add_airplane for all instances.
ENDMETHOD.
"constructor
METHOD get_name.
ex_name = name.
ENDMETHOD.
ENDCLASS.
(C) SAP AG
"get_name
"lcl_carrier IMPLEMENTATION
BC401
11-24
Solutions (optional)
Unit:
Events
Topic:
*&---------------------------------------------------------------------*
*& Report
SAPBC401_EVES_MAIN_B
*&
*&---------------------------------------------------------------------*
*&
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_eves_main_b.
(C) SAP AG
BC401
11-25
(C) SAP AG
BC401
11-26
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_EVES_B
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
* events in: lcl_airplane and lcl_carrier !
*
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
"--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
METHODS: constructor IMPORTING
im_name
TYPE string
TYPE saplane-planetype
EXPORTING ex_weight
TYPE s_plan_wei
ex_tankcap
DATA: name
TYPE s_capacity.
TYPE string,
"lcl_airplane DEFINITION
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
(C) SAP AG
BC401
11-27
= im_name.
planetype
= im_planetype.
n_o_airplanes = n_o_airplanes + 1.
RAISE EVENT airplane_created.
ENDMETHOD.
"constructor
METHOD display_attributes.
DATA: weight TYPE saplane-weight,
cap TYPE saplane-tankcap.
WRITE: / icon_ws_plane AS ICON,
/ 'Name of airplane'(001), AT pos_1 name,
/ 'Type of airplane: '(002), AT pos_1 planetype.
get_technical_attributes( EXPORTING im_type = planetype
IMPORTING ex_weight = weight
ex_tankcap = cap ).
WRITE: / 'Weight:'(003), weight,
'Tankkap:'(004), cap.
ENDMETHOD.
"display_attributes
METHOD display_n_o_airplanes.
WRITE: /, / 'Number of airplanes: '(ca1),
AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
ENDMETHOD.
"display_n_o_airplanes
METHOD get_technical_attributes.
SELECT SINGLE weight tankcap FROM saplane
INTO (ex_weight, ex_tankcap)
WHERE planetype = im_type.
IF sy-subrc <> 0.
ENDMETHOD.
ENDCLASS.
"get_technical_attributes
"lcl_airplane IMPLEMENTATION
...
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_carrier DEFINITION.
PUBLIC SECTION.
(C) SAP AG
BC401
11-28
"---------------------------------------INTERFACES lif_partners.
METHODS: constructor IMPORTING im_name TYPE string,
get_name RETURNING value(ex_name) TYPE string,
add_airplane FOR EVENT airplane_created OF lcl_airplane
IMPORTING sender,
PRIVATE SECTION.
"----------------------------------DATA: name
TYPE string,
"lcl_carrier DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_carrier IMPLEMENTATION.
METHOD lif_partners~display_partner.
display_attributes( ).
ENDMETHOD.
"lif_partners~display_partner
METHOD add_airplane.
APPEND sender TO airplane_list.
ENDMETHOD.
"add_airplane
METHOD display_attributes.
skip 2.
WRITE: icon_flight AS ICON, name . ULINE. ULINE.
display_airplanes( ).
ENDMETHOD.
"display_attributes
METHOD display_airplanes.
DATA: r_plane TYPE REF TO lcl_airplane.
LOOP AT airplane_list INTO r_plane.
r_plane->display_attributes( ).
ENDLOOP.
ENDMETHOD.
"display_airplanes
METHOD constructor.
name = im_name.
(C) SAP AG
BC401
11-29
(C) SAP AG
"constructor
"lcl_carrier IMPLEMENTATION
BC401
11-30
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_VEHD_i
*&---------------------------------------------------------------------*
*---------------------------------------------------------------------*
* define client lcl_travel_agency
* it will use the interface lif_partners
*
* implement EVENT in LCL_VEHICLE and LCL_RENTAL
*---------------------------------------------------------------------*
INTERFACE lif_partners.
METHODS display_partner.
*** event defined inside the interface !! ****
EVENTS: partner_created.
ENDINTERFACE.
"lif_partners
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
"------------------METHODS: get_average_fuel IMPORTING im_distance TYPE s_distance
im_fuel TYPE ty_fuel
RETURNING value(re_avgfuel) TYPE ty_fuel.
METHODS
METHODS
display_attributes.
METHODS
METHODS
TYPE string.
METHODS
init_make.
CLASS-DATA:
n_o_vehicles TYPE i.
(C) SAP AG
BC401
11-31
ENDCLASS.
"lcl_vehicle DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_vehicle IMPLEMENTATION.
METHOD get_average_fuel.
re_avgfuel = im_distance / im_fuel.
ENDMETHOD.
"get_average_fuel
METHOD constructor.
make = im_make.
ADD 1 TO n_o_vehicles.
raise event vehicle_created.
ENDMETHOD.
"constructor
METHOD set_make.
IF im_make IS INITIAL.
init_make( ).
ELSE.
make = im_make.
ENDIF.
ENDMETHOD.
"set_make
METHOD init_make.
make = 'default make'.
ENDMETHOD.
"init_make
METHOD get_make.
ex_make = make.
ENDMETHOD.
"get_make
METHOD display_attributes.
WRITE: make.
ENDMETHOD.
"display_attributes
METHOD get_count.
re_count = n_o_vehicles.
ENDMETHOD.
(C) SAP AG
"get_count
BC401
11-32
ENDCLASS.
"lcl_vehicle IMPLEMENTATION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_rental DEFINITION.
PUBLIC SECTION.
"------------------METHODS:
METHODS
METHODS
display_attributes.
INTERFACES: lif_partners.
PRIVATE SECTION.
"------------------DATA: name TYPE string,
vehicle_list TYPE TABLE OF REF TO lcl_vehicle.
ENDCLASS.
"lcl_rental DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_rental IMPLEMENTATION.
METHOD lif_partners~display_partner.
display_attributes( ).
ENDMETHOD.
METHOD
"lif_partners~display_partner
constructor.
name = im_name.
set handler add_vehicle for all instances.
raise event lif_partners~partner_created.
ENDMETHOD.
METHOD
"constructor
add_vehicle.
(C) SAP AG
"add_vehicle
BC401
11-33
METHOD
display_attributes.
"display_attributes
ENDCLASS.
"lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_travel_agency DEFINITION.
PUBLIC SECTION.
"------------------METHODS:
METHODS
METHODS
display_agency_partners.
PRIVATE SECTION.
"------------------DATA: name TYPE string,
partner_list TYPE TABLE OF REF TO lif_partners.
ENDCLASS.
"lcl_travel_agency DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_travel_agency IMPLEMENTATION.
METHOD display_agency_partners.
DATA: r_partner TYPE REF TO lif_partners.
WRITE: icon_dependents AS ICON, name.
WRITE:
BC401
11-34
ENDLOOP.
ENDMETHOD.
METHOD
"display_agency_partners
constructor.
name = im_name.
set handler add_partner for all instances.
ENDMETHOD.
METHOD
"constructor
add_partner.
(C) SAP AG
"add_partner
"lcl_travel_agency IMPLEMENTATION
BC401
11-35
Contents:
Local versus global classes and interfaces
Class Builder
SAP AG 2002
(C) SAP AG
BC401
12-1
SAP AG 2002
(C) SAP AG
BC401
12-2
terfaces
sses and In
la
C
l
a
b
Glo
Events
Interfaces
Casting
and
Data Types
ts in
Data Objec
Detail
e
Inheritanc
ming
ed Program
nt
rie
O
of ObjectPrinciples
n
and Desig
Analysis
ing
Programm
d
te
en
Ori
to Objectn
tio
uc
Introd
al
Using Intern
Tables
rams
Calling Prog
Data
and Passing
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
12-3
Class
Class Builder
Builder
Working
Working with
with global
global classes
classes and
and interfaces
interfaces
Applied
Applied example
example
SAP AG 2002
(C) SAP AG
BC401
12-4
Programm-1
Programm-2
REPORT prog1.
REPORT prog2.
CLASS lcl_airplane DEFINITION.
ENDCLASS.
DATA: r_airplane
TYPE REF TO lcl_airplane.
...
...
...
Local classes are only visible in the program they were defined in
SAP AG 2002
Local classes and interfaces are only known within the program in which they are defined and
implemented.
Local classes and interfaces are not stored in the Repository (no TADIR entry). There is no "global"
access to these classes or interfaces (for example, from other programs).
(C) SAP AG
BC401
12-5
Stored in Repository
SAP AG 2002
Unlike local program classes and interfaces, global classes and interfaces can be created and
implemented using the ABAP Workbench tool Class Builder. These classes and interfaces are then
available active throughout the whole system.
Global class and interface names share the same namespace.
Individual methods of global classes and interfaces can be transported separately.
(C) SAP AG
BC401
12-6
Workbench
Edit
Goto
Utilities
Environment
MIME Repository
Diese Knpre hier
Repository Browser
Repository Information
Systemich auch
brauche
Tag Library
Transport Organizer
System
Help
Create Report
a class in the Object
Navigator
Package
Instance creation
ZBC401_00
Object Name
ZBC401_00
Class Library
Classes
Description
private
protected
public
abstract
SAP AG 2002
You can also display the Class Builder's global classes in the Object Navigator.
Being able to view classes through the navigation window on the left is especially useful when
developing code.
Here, you can also create a new class. Proceed as you would when creating a program: Use the context
menu for a package node or directly for a class node within a package.
Alternatively, you can also create a new class by entering a class name and then choosing Display. In
this case, you must specify a package.
I dialog box asks you to make further specifications for the new class:
Instance creation: Where are instances of this new class to be created?
For example, if you specify private the class could only be instantiated within the class itself.
The default setting is public.
Exception class (this will be discussed in more detail later, in the context of exception handling)
Persistent class (this will be discussed in more detail later, in the context of special techniques)
Final class (represents the end of an inheritance tree)
Only modeled (class definition only for modeling)
(C) SAP AG
BC401
12-7
Edit
Goto
Utilities
Environment
System
Help
Define class
attributes
ZCL_AIRPLANE_00
Interfaces
Friends
Implemented/Active
Attributes Methods
Events
Internal Types
Aliases
Filter
Attribute
Level
Name
Instan
PLANE _TYPE
Instan
N_O_AIRPLANES
Static
Assoc. Type
Description
Priv
Type
STRING
Name of airplane
Priv
Type
SAPLANE
Airplane type
Priv
Type
Number of airplanes
SAP AG 2002
In the Class Builder, choosing the Attributes tab displays the class attributes and their properties
(instance attribute/static attribute and the visibility area)
(C) SAP AG
BC401
12-8
Edit
Goto
Utilities
Environment
System
Help
Define class
methods
Class Interface
Properties
Interfaces
Parameters
Friends
Implemented/Active
Attribute Methods
Events
Exceptions
Methods
Level
CONSTRUCTOR
CONSTRUCTOR
DISPLAY ATTRIBUTES
Airplane attributes
DISPLAY_N_O_AIRPLANES
Static Method
Number of planes
Visibility
Mod. Met.
Public
Description
SAP AG 2002
(C) SAP AG
BC401
12-9
Edit
Goto
Utilities
Environment
System
Help
ZCL_AIRPLANE_00
Class Interface
Properties
Implemented/Active
Parameters
Events
Exceptions
Visibility
Methods
Level
CONSTRUCTOR
CONSTRUCTOR
DISPLAY ATTRIBUTES
Airplane attributes
DISPLAY_N_O_AIRPLANES
Static Method
Number of planes
ZIF_FLY~START
Public
2) Method implementation of
a global interface
Mod. Met.
Description
1) Announce a global
interface in a global class
SAP AG 2002
A global interface that was created in the Class Builder can be announced in a server class by choosing
the Interfaces tab.
All interface methods are then automatically listed under the Methods tab.
All interface methods must then be implemented in this server class. In the example, the interface
zif_fly consists of a single method start.
(C) SAP AG
BC401
12-10
Class
Edit
Goto
Utilities
Environment
System
Help
Method Parameters
Methods
Parameter
ZCL_AIRPLANE_00
Interfaces
Friends
Implemented/Active
Attributes
Methods
Events
Internal Types
Aliases
CONSTRUCTOR
Exceptions
P
Typing
Assoc. Type
IM_ NAME
Type
STRING
IM_PLANETYPE
Type
SAPLANE-...
Type
Type
Signature parameters of
method,
here: CONSTRUCTOR
SAP AG 2002
Selecting a method and choosing Parameters displays a list of all the method's signature parameters.
(C) SAP AG
BC401
12-11
Method
Edit
Goto
Utilities
Environment
System
Help
Type spec.
Description
IM_NAME
TYPE STRING
IM_PLANETYPE
Method
CONSTRUCTOR
active
METHOD constructor.
make = im_name.
plane_type = im_planetype.
ADD 1 TO n_o _airplanes.
ENDMETHOD.
SAP AG 2002
When implementing methods, you can also display the signature of the method to aid your work.
In this example (constructor), the signature consists of the import parameters im_make and
im_planetype.
(C) SAP AG
BC401
12-12
Edit
Goto
Utilities
Environment
System
Help
ZCL_CARGO_PLANE_00
Interfaces
Friends
Implemented/Active
Attributes Methods
Events
Internal Types
Aliases
Superclass
Superclass
Superclass
ZCL_AIRPLANE_00
Description
...
Instantiation
...
Final
...
SAP AG 2002
In the Class Builder, inheritance relationships are defined by choosing the Properties tab.
Here, for example, is the Superclass function, which you can use to specify the superclass for the current
class.
In this example, the superclass ZCL_AIRPLANE_00 is specified for the subclass
ZCL_CARGO_PLANE_00.
(C) SAP AG
BC401
12-13
Class
Edit
Goto
Utilities
Handler
ZCL_AIRPLANE_00
Attributes
Methods
Handler
TestObject->
Upper/Lower Case Active
DISPLAY_N_O_AIRPLANES
ZCL_AIRPLANE_00
45<CL_AIRPLANE_00
Interfaces
Attributes
Methods
DISPLAY_ATTRIBUTES
DISPLAY_N_O_AIRPLANES
If the class is completed and activated, you can use the test tool to create an instance of the class and test
method calls of the class.
(C) SAP AG
BC401
12-14
Class
Class Builder
Builder
Working
Working with
with global
global classes
classes and
and interfaces
interfaces
Applied
Applied example
example
SAP AG 2002
(C) SAP AG
BC401
12-15
Workbench
Edit
Goto
Utilities
Environment
System
Help
MIME Repository
Diese Knpre hier
Repository Browser
Repository Information
Systemich auch
brauche
Tag Library
Transport Organizer
Class/Interface
Report
zdemo
Active
ZCL_AIRPLANE_00
Object Name
ZCL_AIRPLANE_00
Description
Class Airplane
START-OF-SELECTION.
******************************
CREATE OBJECT r_airplane
EXPORING
IMPORTING ...
Attributes
NAME
N_O_AIRPLANES
PLANE _TYPE
Methods
Name of airplane
Number of planes
Airplane type
CONSTRUCTOR
CONSTRUCTOR
DISPLAY_ ATTRIBUTES
Displays airplane attributes
DISPLAY_N_O_ AIRPLANES Displays number of airplanes
SAP AG 2002
You can also display the Class Builder's global classes in the Object Navigator.
Being able to view classes through the navigation window on the left is especially useful when editing
source code. You can drag & drop specific components into the right Editor window and automatically
create and insert source code (as a template).
(C) SAP AG
BC401
12-16
Edit
Goto
Utilities
Environment
System
Help
Report
MIME Repository
Knpre
Repository Browser Diese
Selecting
andhier
dragging
CREATE OBJECT
Class/Interface
ZCL_AIRPLANE_00
Object Name
ZCL_AIRPLANE_00
*********************************************************************
* XY_00_airplane
*********************************************************************
* XY_00_airplane
CLASS lcl_airplane DEFINITION.
START-OF-SELECTION.
####################
Description
Class Airplane
Attributes
NAME
N_O_AIRPLANES
PLANE _TYPE
Methods
Active
into
Repository Information
System
brauche
ichcreates
auch
the
Editor
Tag Library
Transport Organizer
zdemo
Name of airplane
Number of planes
Airplane type
CONSTRUCTOR
CONSTRUCTOR
DISPLAY_ ATTRIBUTES
Displays airplane attributes
DISPLAY_N_O_ AIRPLANES Displays number of airplanes
SAP AG 2002
(C) SAP AG
BC401
12-17
Workbench
Edit
Goto
Utilities
Environment
System
Help
MIME Repository
Report
Knpre hier
Repository Information
System ich auch
brauche
Tag Library
Selecting and dragging into
Transport Organizer
the Editor creates CALL
zdemo
Active
Class/Interface
METHOD
ZCL_AIRPLANE_00
Object Name
ZCL_AIRPLANE_00
Attributes
NAME
N_O_AIRPLANES
PLANE _TYPE
*********************************************
* XY_00_airplane
*********************************************
* XY_00_airplane
class lcl airplane definition
START-OF-SELECTION.
#################################
Description
Class Airplane
Name of airplane
Number of planes
Airplane type
CALL METHOD
xxx->display_attributes
Methods
CONSTRUCTOR
CONSTRUCTOR
DISPLAY_ ATTRIBUTES
Displays airplane attributes
DISPLAY_N_O_ AIRPLANES Displays number of airplanes
SAP AG 2002
(C) SAP AG
BC401
12-18
Class
Class Builder
Builder
Working
Working with
with global
global classes
classes and
and interfaces
interfaces
Applied
Applied example
example
SAP AG 2002
(C) SAP AG
BC401
12-19
An applied example for the use of ABAP Objects is the standard output tool SAP Grid Control. It is
implemented in ABAP Objects and provides the user with a wide range of functions (for example sorting
data, reorganizing/hiding columns, totalling).
Principle of SAP Control Framework:
To use such a control the developer no longer has to re-implement functions in the control, but simply
specify the instances of the classes that contain these functions.
The exact procedure for using the SAP Grid Control will be discussed in the following.
(C) SAP AG
BC401
12-20
Screen
Area
1 CL_GUI_CUSTOM_CONTAINER
Public
Private
Custom
Container
Control
3 CL_GUI_ALV_GRID
Public
Private
ALV
Grid
Control
SAP AG 2002
An SAP container is capable of housing other controls (such as the SAP Grid Control, tree control,
picture control, splitter control, and so on). It manages these controls in a logical collection and provides
a physical area for visualization. Each control "lives" in a container. Because containers are themselves
controls, containers can be nested within one another. The container becomes the parent of its control.
Global classes are available for accessing the custom control and the SAP Grid Control. At runtime, an
object each of the class CL_GUI_CUSTOM_CONTAINER and the class CL_GUI_ALV_GRID is
created. These objects contain all necessary information for accessing the controls. For information on
the object types (classes) and the corresponding methods, refer to the online documentation.
(C) SAP AG
BC401
12-21
The control is displayed on a screen, the call of which is not shown in this example.
To create the object that communicates with the container control, it is sufficient to include the name of
the container area 'CONTAINER_1' on the screen, on which the container area is defined.
To create the object that communicates with the SAP Grid Control, you must include the reference
variable that refers to the object for the custom container. This is because the object for the SAP Grid
Control contains a reference variable that points to the container object as a private attribute. This
relationship tells the object, which container it should be included in.
To display data in a SAP Grid Control, it must be provided in an internal table. Then a method is called
that receives the content of the internal table and its structure. The name of this method id
set_table_for_first_display. If, while the program runs, only the content of the internal
table to be displayed changes, it is sufficient to call the method refresh_table_display with the
container area before the the screen is re-sent.
(C) SAP AG
BC401
12-22
SAP AG 2002
(C) SAP AG
BC401
12-23
Exercises
Unit: Global Classes and Interfaces
Topic: Creating Global Classes
At the conclusion of these exercises, you will be able to:
Use the Class Builder to process global classes and interfaces
1-1
1-2
1-3
1-4
1-5
Activate and test your class using the Class Builder test tool.
(C) SAP AG
BC401
12-24
Define the global interface ZIF_##_PARTNERS with the interface method display_partner.
Implement the interface in the class ZCL_##_HOTEL.
Optional:
Include the new class in the program with the airlines and car rental companies. Adjust the
sections that refer to the local interface lif_partners to suit the new global interface.
lcl_travel_agency
uses
zif_partners
implements
lcl_carrier
lcl_hotel
lcl_vehicles
lcl_airplane
...
4
lcl_car_rental
...
...
...
(optional)
Define an inheritance relationship in the Class Builder. Your hotel is to inherit from the
superclass ZCL_##_HOUSE. Tip: Construct the class ZCL_##_HOUSE copying the class
ZCL_##_HOTEL to ZCL_##_HOUSE and then making changes to this copy. The house
should only have an attribute name (protected) and the method display_attributes; delete all
superfluous components.
Finally, define the inheritance relationship between the house and the hotel.
(C) SAP AG
BC401
12-25
Solutions
Unit:
Topic:
*&---------------------------------------------------------------------*
*& Report
SAPBC401_CLSS_MAIN_A
*&---------------------------------------------------------------------*
*&
*&
travel agency
*&---------------------------------------------------------------------*
REPORT
sapbc401_clss_main_a.
(C) SAP AG
BC401
12-26
(C) SAP AG
BC401
12-27
Special Techniques
Contents:
Abstract and final classes
Visibility of constructors
Friends
Object Services
SAP AG 2002
(C) SAP AG
BC401
13-1
SAP AG 2002
(C) SAP AG
BC401
13-2
chniques
Special Te d Interfaces
an
sses
Global Cla
Events
Interfaces
Casting
and
Data Types
ts in
Data Objec
Detail
e
Inheritanc
ing
Programm
nt
Orie ed
of Objectes
pl
ci
rin
P
n
and Desig
Analysis
ing
Programm
d
te
Orien
to Objectn
tio
uc
Introd
al
Using Intern
Tables
rams
Calling Prog
Data
and Passing
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
13-3
Abstract
Abstract and
and final
final classes
classes
Visibility
Visibility of
of constructors
constructors
The
The friend
friend concept
concept
Persistent
Persistent objects
objects
SAP AG 2002
(C) SAP AG
BC401
13-4
Abstract Classes
Class cannot
be instantiated
Method not
implemented in this
class
SAP AG 2002
It is not possible to instantiate objects of an abstract class However, this does not mean that references to
such a class are not useful. On the contrary, they are very useful, since they can (and must) refer to
instances in subclasses of the abstract class at runtime. The CREATE OBJECT statement is extended in
this context. You can specify the class of the instance to be created explicitly:
CREATE OBJECT <RefToAbstractClass> TYPE <NonAbstractSubclassName>.
Abstract classes are normally used as an incomplete blueprint for concrete (that is, non-abstract)
subclasses, for example to define a uniform interface.
Abstract instance methods are used to specify particular interfaces for subclasses, without having to
immediately provide implementation for them. Abstract methods need to be redefined and thereby
implemented in the subclass (here you also need to include the corresponding redefinition statement in
the DEFINITION part of the subclass).
Classes with at least one abstract method are themselves abstract.
Static methods and constructors cannot be abstract (they cannot be redefined).
(C) SAP AG
BC401
13-5
Final Classes
vehicle
truck
...
bus
...
...
SAP AG 2002
A final class cannot have subclasses, and can protect itself in this way against (uncontrolled)
specialization.
A final method in a class cannot be redefined in a subclass, and can protect itself in this way against
(uncontrolled) redefinition.
Some features:
A final class implicitly only contains final methods. In this case, you cannot enter FINAL explicitly
for these methods.
Methods cannot be both final and abstract.
Classes, on the other hand, that are both abstract and final can be useful: Only static components
can be used.
(C) SAP AG
BC401
13-6
Abstract
Abstract and
and final
final classes
classes
Visibility
Visibility of
of constructors
constructors
The
The friend
friend concept
concept
Persistent
Persistent objects
objects
SAP AG 2002
(C) SAP AG
BC401
13-7
CREATE PUBLIC
Every user (client) can create instances of a class
(default setting)
CREATE PROTECTED
Only the class itself and all its subclasses can create instances of this
class
CREATE PRIVATE
Only the class can create instances of itself
(1) lcl_singleton
Public
Private
r_singl
Client
get_
singleton
SAP AG 2002
If you want to ensure that not every user (client) can instantiate a class, you can use the following
additions to restrict the visibility area of the constructor and hence limit the use of the class. (The
following additions must be preceded by CLASS ... DEFINITION.)
The CREATE PUBLIC addition is implicitly available for every class definition, provided neither
of the other two CREATE additions is used. It defines the default that every user can create
instances of a known class.
The optional additions CREATE PROTECTED and CREATE PRIVATE, on the other hand, have
the effect that not every user can create instances of a class. In the case of CREATE PROTECTED,
only subclasses of the class or the class itself and, in the case of CREATE PRIVATE, only the class
itself can create instances of the class.
Therefore, the additions CREATE PROTECTED and CREATE PRIVATE allow you to control
instance creation and, for example, are a prerequisite for the instance management of persistent
objects, for which the uniqueness of objects must be ensured. (Persistent objects will be discussed
in more detail later.)
If it is to be impossible to instantiate a class more than once (for example, because it serves as a data
administrator or data container), you can use the singleton concept. The class is defined with the addition
CREATE PRIVATE and FINAL and instantiated using its static constructor.
A public static component could then make the reference to the class available to an external user.
(C) SAP AG
BC401
13-8
Abstract
Abstract and
and final
final classes
classes
Visibility
Visibility of
of constructors
constructors
The
The friend
friend concept
concept
Persistent
Persistent objects
objects
SAP AG 2002
(C) SAP AG
BC401
13-9
In rare cases, classes have to work together so closely that they need access to their protected and private
components. To avoid making these components available to all users, there is the concept of friendship
between classes.
A class can provide friendship to other classes and interfaces (and hence all classes that implement the
interface). To do this you use the FRIENDS additions to the CLASS statement, in which all classes and
interfaces that are to be provided friendship are listed. Friends are allowed to access the protected and
private components of the class providing the friendship and can always create instances of this class,
regardless of the CREATE addition to the CLASS statement.
In principle, providing friendship is one-sided: A class providing friendship is not automatically a friend
of its friends. If a class providing friendship wants to access the non-public components of a friend, this
friend has to explicitly provide friendship to it.
Classes that inherit from friends and interfaces that contain a friend as a component interface also
become friends. Therefore, extreme caution is advised when providing friendship. The higher up a friend
is in the inheritance tree, the more subclasses can access all components of a class providing friendship.
However, providing friendship, unlike the attribute of being a friend, is not inherited. A friend of a
superclass is therefore not automatically a friend of its subclasses.
(C) SAP AG
BC401
13-10
Abstract
Abstract and
and final
final classes
classes
Visibility
Visibility of
of constructors
constructors
The
The friend
friend concept
concept
Persistent
Persistent objects
objects
SAP AG 2002
(C) SAP AG
BC401
13-11
The persistence service helps the programmer to work object-oriented with data in relational databases.
In principle, ABAP programs work with data and objects that exist(s) in the internal session at runtime.
They are transient when the program is stopped. If this data is to be stored program-independently, that
is persistently, it must be stored in the database. (You could also use files on operating system level.)
(C) SAP AG
BC401
13-12
...
SAP AG 2002
To use the persistence service for objects, their classes must be created as so-called persistent classes in
the Class Builder.
The term persistent class indicates that the objects of the class and their state are managed by the
persistence service. In ABAP programs, objects of these classes are, for example, not created using the
normal statement CREATE OBJECT, but instead using a method of the persistence service that ensures
the correct initialization.
When creating a persistent class, the Class Builder automatically creates a corresponding class, the so
called class actor or agent, the methods of which are used to manage the objects of the persistent class.
As well as their unique identity, persistent classes can also contain so-called key attributes, which the
persistence service uses to ensure the uniqueness of the persistent objects' contents.
(C) SAP AG
BC401
13-13
Class Agent
Within the persistence service, the class actor or class agent manages
the persistent objects
...
The agent,
a singleton of the class
CA_CARRIER and
friend of the persistent
class CL_CARRIER
TRY.
r_carrier = r_agent->get_persistent( i_carrid = 'LH' ).
carrname
= r_carrier->get_carrname( ).
WRITE: 'LH: ', carrname.
CATCH cx_os_object_not_found.
ENDTRY.
SAP AG 2002
For every persistent class cl_persistent, the Class Builder generates two further classes
ca_persistent and cb_persistent. These classes make up the class-specific part of the
persistence service.
ca_persistent is the so-called class actor (or agent), which is used to manage the managed object
of the class cl_persistent, and in which all actual database accesses take place. The class actor
inherits the relevant methods from the abstract superclass cb_persistent. The programmer can
extend the class actor and redefine the methods (especially the database accesses). The superclass
cb_persistent cannot be changed. The class actor is a friend of the managed class. It has the
attribute CREATE PRIVATE and exactly one instance of the class actor is created when it is first
accessed.
The static attribute AGENT is a reference variable with the type of the class ca_persistent. When
the attribute is first accessed in an ABAP program, the static constructor of the class ca_persistent
creates exactly one instance of this class, which points to the attribute AGENT. This object is part of the
persistence service and its methods are used to manage the object of the persistent class. For each
program there is only one object of the class ca_persistent, because you cannot create objects from
outside using CREATE OBJECT.
The class actor manages one or more objects of the relevant persistent class. These objects must have
different keys.
(C) SAP AG
BC401
13-14
SAP AG 2002
(C) SAP AG
BC401
13-15
Exercises - optional
Unit: Special Techniques
Topic: Singleton Classes
At the conclusion of these exercises, you will be able to:
Create a singleton; requirement for next exercise
(Advanced)
Create the global class ZCL_##_SINGLETON in the Class Builder.
The following must be specified for the class:
1-1
You must be able to be instantiate the class only once. (Tip: Instantiation should take
place automatically when the class is first accessed.)
1-2
1-3
The class has a static reference variable r_singleton that refers to the instantiated
object.
1-4
The class has a static reference variable r_singleton that refers to the instantiated
object.
2-2
Verify your blueprint by calling get_singleton several times. (Debug.) When does
instantiation take place and how often?
(C) SAP AG
BC401
13-16
Exercises - optional
Unit: Special Techniques
Topic: Concluding Project Exercise
At the conclusion of these exercises, you will be able to:
Create a friends relationship and access the data of a class providing
the friendship (a singleton) from the befriended class
(Note that the friends concept is mainly used in bigger projects with
more complex classes)
Model solution: CL_AGENCY
SAPBC401_SPCS_MAIN_B
(Advanced)
Use your singleton and the main program from the last exercise.
3-1
3-2
When instantiating the singleton, this internal table is to be automatically filled with
the flight connections from the table SPFLI.
4-2
(C) SAP AG
BC401
13-17
4-2-3 In the method, the internal table of the class providing the friendship is to be
accessed in a single record access. (READ TABLE...)
If the requested record does not exist, it is sufficient in this example to display
an appropriate message using the WRITE statement.
5
friend
(3) lcl_agency
(1) cl_singleton
get_
connection
connection_
list
(C) SAP AG
BC401
13-18
Solutions - optional
Unit:
Special Techniques
Topic:
Singleton Classes
*&---------------------------------------------------------------------*
*& Report
SAPBC401_spcS_MAIN_A
*&---------------------------------------------------------------------*
*&
*&
*&
*&
*&
*&
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_spcs_main_a.
(C) SAP AG
BC401
13-19
Solutions - optional
Unit:
Special Techniques
Topic:
*&---------------------------------------------------------------------*
*& Report
SAPBC401_spcS_MAIN_B
*&---------------------------------------------------------------------*
*&
*&
*&
*&
*&
*&
*&
*&
*&---------------------------------------------------------------------*
REPORT
sapbc401_spcs_main_b.
START-OF-SELECTION.
*########################
r_single = cl_singleton=>get_singleton( ).
create object r_agency exporting im_name = 'Agency'.
r_agency->get_connection( exporting im_carrid = 'LH'
im_connid = '0400'
importing ex_connection = rec ).
write: / rec-carrid, rec-connid.
(C) SAP AG
BC401
13-20
(C) SAP AG
BC401
13-21
Exception Handling
Contents:
Predefined exceptions and exceptions you define
yourself
Raising, handling, and passing along exceptions
SAP AG 2002
(C) SAP AG
BC401
14-1
SAP AG 2002
(C) SAP AG
BC401
14-2
Handling
Exception
chniques
Special Te
aces
and Interf
es
ss
Global Cla
Events
Interfaces
Casting
and
Data Types
ts in
Data Objec
Detail
e
Inheritanc
ming
ed Program
nt
Object-Orie
of
es
pl
ci
Prin
n
and Desig
Analysis
ing
rogramm
P
d
te
en
Object-Ori
to
n
tio
Introduc
al
Using Intern
Tables
rams
Calling Prog
Data
and Passing
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
14-3
We use the term exception to refer to a situation that arises while an ABAP program is being executed,
where there is no point in continuing to run the program in the normal way. Since SAP R/3 Basis
Release 6.10, exceptions and exception handling is based on the exception classes concept. This concept
includes the functions of the concepts that preceded it but also enhances (and thus replaces) them.
Class-based exceptions are raised either using the ABAP statement RAISE EXCEPTION or by the
ABAP runtime environment. For example, if the program tries to divide by zero the runtime
environment raises the exception. You can, however, ascertain that this situation has arisen using a query
in the ABAP program. From there, you can then raise an exception yourself.
You can define exception classes yourself, but there is already a range of predefined exception classes in
the system. In an exception situation, an exception is represented by an exception object - that is, an
instance of an exception class. The attributes of each exception object can contain information about the
error situation.
The use of class-based exceptions is not limited to object-oriented contexts. Class-based exceptions can
be raised and handled in all ABAP processing blocks. In particular, the catchable runtime errors used
until now can be handled as class-based exceptions.
If a class-based exception occurs, the system interrupts the normal program flow and tries to navigate to
a suitable handler. If it cannot find a handler, a runtime error occurs.
(C) SAP AG
BC401
14-4
cx_no_check
cx_dynamic_check
cx_sy_arithmetic_error
cx_static_check
cx_sy_move_cast_error
cx_sy_arithmetic_overflow
SAP AG 2002
All exception classes are derived from the one of the classes CX_NO_CHECK,
CX_DYNAMIC_CHECK, or CX_STATIC_CHECK, themselves derived from the common superclass
CX_ROOT. The way in which exception classes are assigned to one of these three paths in the hierarchy
defines how the associated exceptions are passed along. (This will be discussed in more detail later in
this unit.)
All exception classes begin with the prefix CX_. In general, they are defined globally in the ABAP
Workbench Class Builder. However you can also define local exception classes.
The root class CX_ROOT contains two predefined methods that are inherited by the other classes. The
GET_SOURCE_POSITION method returns the program name, include name (if relevant), and line
number in the source code where the exception occurred. The GET_TEXT method returns an exception
text of a class in the form of a string. You can assign several texts to each class. You can then specify
which text is to used when an exception is raised by passing an identifier to the IMPORTING parameter
TEXTID of the instance constructor.
All exception classes inherit the KERNEL_ERRID attribute from CX_ROOT. This attribute contains the
name of the appropriate runtime error if the exception was raised by the runtime environment - such as
COMPUTE_INT_ZERODIVIDE if the program tries to divide by zero. If the exception is not listed, a
runtime error occurs.
(C) SAP AG
BC401
14-5
Handling Exceptions
TRY.
...
CATCH cx_...
cx_...
...
[INTO r_exc1].
Code whose
exceptions (if
any) are to be
handled
...
CATCH cx_...
...
CLEANUP.
Handlers
Handlers for
for the
the
specified
specified exception
exception
classes
classes and
their
and
their
subclasses
subclasses
...
ENDTRY.
SAP AG 2002
Like all ABAP control structures, TRY-ENDTRY structures can be nested. Thus the TRY block, CATCHblocks, and the CLEANUP block in particular can contain complete TRY-ENDTRY structures
themselves.
The TRY block contains the application code that is to handle the exceptions. If an exception occurs in
the TRY block the system searches first for a CATCH statement (which will handle the exception) in the
same TRY-ENDTRY structure and then step by step outwards in all the enclosing TRY-ENDTRY
structures. If it finds one, it navigates to this handler. If it cannot find a handler but the TRY-ENDTRY
structure is in a procedure, it then tries to pass the exception along to the calling program. (This will be
discussed in more detail later.)
A CATCH block contains the exception handler that is executed if a specified exception has occurred in
the TRY block in the same TRY-ENDTRY structure. After the CATCH statement, you can specify as
many exception classes as you wish. In this way, you define an exception handler for all these
exception classes and their subclasses. After an exception occurs, the system searches through the listed
exception handlers in the order specified. It then executes the first exception handler whose CATCH
statement contains the relevant exception class or one of its superclasses.
In some cases, the system cannot find a handler for an exception within a specific TRY-ENDTRY
structure but the exception is handled in a surrounding TRY-ENDTRY structure or passed along to a
calling program. If this occurs, a CLEANUP block is executed before leaving the TRY-ENDTRY
structure.
(C) SAP AG
BC401
14-6
In the above calculation, if the value range for data type i is exceeded, the runtime system raises the
exception CX_SY_ARITHMETIC_OVERFLOW. This exception is handled in the implemented
CATCH block.
The object reference to the exception object is stored in the reference variable r_exc. Using r_exc
and the functional method get_text, the handler accesses the exception text for this exception object
and stores in the string variable text.
To display exception texts as messages, the MESSAGE statement has been extended so that you can use
any string:
MESSAGE <string> TYPE <type>.
As well as the message <string> that will be displayed, you must display the message type <type>,
either as a literal or in a field.
If the value range for data type i is not exceeded, no exception is raised and the TRY block is processed
completely. The program then continues executing after the keyword ENDTRY.
The class CX_SY_ARITHMETIC_OVERFLOW is a subclass of the classes
CX_SY_ARITHMETIC_ERROR, CX_DYNAMIC_CHECK, and CX_ROOT. Thus the exception
raised above can also be handled if you enter one of these classes after the CATCH statement.
The keyword documentation for each keyword lists the exception classes whose exceptions may occur
when the appropriate ABAP statement is executed.
(C) SAP AG
BC401
14-7
SAP AG 2002
The above program source code shows the method get_technical_attributes of the class
lcl_airplane, which was implemented in an earlier exercise in this training course. It receives an
airplane type as an import parameter and returns its weight and tank capacity as export parameters.
The relevant information is read from the database table saplane. If the airplane type passed is not
available in this table (that is, if sy-subrc <> 0), the values 100.000 and 10.000 respectively are
assigned to the export parameters ex_weight and ex_tankcap. We will now change this behavior:
If an airplane type is not entered in the table, an exception that we have defined should be raised and
handled appropriately.
(C) SAP AG
BC401
14-8
Workbench
Edit
Goto
Utilities
Environment
System
Pattern
privat
ZCX_WRONG_PLANETYPE
protected
CX_STATICS_CHECK
Inherits From
public
abstract
Class Type:
Usual ABAP Class
Exception Class
Persistent Class
Class
Package
ZBC401_00
ZBC401_00
Class Library
Classes
Pretty Printer
Report
MIME Repository
Object Navigator Diese Knpre hier
Repository Infosystem
brauche ich auch
Tag Library
Transport Organizer
Object Name
Help
Description
Final Class
Only modeled
SAP AG 2002
Exceptions are represented by objects that are instances of exception classes. Defining an exception is
thus synonymous with creating an exception class.
Exception classes are generally defined globally. For special exceptions that will only occur within a
single ABAP program however, you can also define local exception classes.
Global exception classes are defined and managed in the Class Builder. When you create a new class, if
you use the correct naming convention (prefix ZCX_) and choose the class type Exception Class, the
system automatically displays the Exception Builder instead of the Class Builder.
The Exception Builder offers all the functions you need to create exception classes and generates
specified components that cannot be changed. When you create an exception class, you must also
specify which category of exception it will be - that is, whether it is derived from
CX_STATIC_CHECK, CX_DYNAMIC_CHECK or CX_NO_CHECK.
(C) SAP AG
BC401
14-9
Edit
Goto
Utilities
Environment
System
Help
Class Interface
Implemented/Active
Attributes Texts
Const..
TEXTID
Instan..
Filter
Nu
Re
Typing
Pub..
Type
SOTR_CONC
Pub..
Type
SOTR_CONC
Type Re
CX_ROOT
Type
S380ERRID
Type
SAPLANE-PLANETYPE
PREVIOUS
Instan..
Pub..
KERNEL_ERRID
Instan..
Pub..
PL_TYPE
Instan..
Pub..
Associated Type
Exception text
used to describe
exception situation
in more detail
Exception ID
Text
CX_ROOT
An exception occurred
The methods are all inherited from CX_ROOT. You can also add your own methods. The instance
constructor is generated automatically.
You can also define your own attributes, whose contents specify the exception in more detail. The
Exception Builder ensures that the instance constructor has identically-named IMPORTING parameters
for these attributes.
The exception texts of global classes are defined on the Texts tab of the Exception Builder. They can
contain parameters. To do this, use the elementary attributes of the exception class by enclosing their
name in ampersands ('&') in the exception text.
The exception texts of global exception classes are stored in their different translations in the Open Text
Repository (OTR). Note that several texts can be assigned to a single class. You assign a text to an
exception using the TEXTID attribute, which contains the globally unique ID of the text object within an
exception object at runtime. The method GET_TEXT then exports this text, replaces any text parameters
with the contents of the relevant attributes as necessary, and returns the text as a character string.
For each global class, the Exception Builder generates a default text whose name matches the class
name. (The name of this default text cannot be changed.) You need to create names for other texts. For
each text, the Exception Builder generates a static constant that contains the associated ID in the OTR.
You can then specify which text is to used when an exception is raised by passing an identifier to the
IMPORTING parameter TEXTID of the instance constructor. If you do not specify a text, the default
text is used.
(C) SAP AG
BC401
14-10
If the airplane type passed to the method has not been stored in the table saplane, the exception we
defined previously, zcx_wrong_planetype, is raised. In addition, a TRY-ENTRY control structure is
implemented that is only processed if sy-subrc <> 0.
The TRY block contains the application code that is to handle the exceptions. When the exception is
raised, the IMPORTING parameter pl_type of the instance constructor is filled. (This parameter is
automatically generated by the Exception Builder.) Using this parameter, the program then assigns the
value of the airplane type to the identically-named attribute.
The exception that has been raised is handled in the CATCH block. The reference to the exception object
is stored in the reference variable r_exc, which was created as a local data object in the method (TYPE
REF TO cx_root).
Since the IMPORTING parameter TEXTID of the instance constructor was not filled when the
exception was raised, the default text generated when the exception class was created is addressed using
the functional method get_text. The method GET_TEXT then exports this text, replaces the text
parameter with the contents of the attribute pl_type, and returns the text as a character string.
The returned text is stored in the local data object text, which has the type string. The text is then
displayed as an information (type I) message.
(C) SAP AG
BC401
14-11
REPORT propagate_exceptions.
...
DATA r_obj TYPE REF TO class.
...
TRY.
r_obj->meth( EXPORTING ...
IMPORTING ... ).
CATCH cx_exception.
...
ENDTRY.
SAP AG 2002
Exceptions that occur in procedures (methods, function modules, or subroutines) do not necessarily need
to be handled there; they can be passed along to the calling program. The calling program can then
handle the exception itself or also pass it along to its own caller, and so on.
The highest levels to which an exception can be passed are processing blocks without local data areas that is, event blocks or dialog modules. The exceptions passed along by the called procedures must be
dealt with there, as must any exceptions raised within this processing block itself. Otherwise a runtime
error occurs.
To pass along an exception from a procedure, you generally use the RAISING addition when defining
the procedure interface.
In methods of local classes and subroutines, specify the RAISING addition directly when defining the
procedure (METHODS meth ... RAISING cx_... cx_..., FORM form ... RAISING cx_... cx_...). After
RAISING, list the exception classes whose objects are to passed along.
In methods of global classes, the exception classes whose objects are to be propagated are entered in the
exception table of the method in the Class Builder. Check the Exception Class field in this exception
table. Similarly, exceptions raised by function modules are passed along by being entered in the
Function Builder.
(C) SAP AG
BC401
14-12
METHOD get_technical_attributes.
RAISE EXCEPTION
TYPE zcx_wrong_planetype
EXPORTING pl_type = im_type.
ENDIF.
ENDMETHOD.
SAP AG 2002
As in the previous example, the exception we have defined (zcx_wrong_planetype) is raised if the
airplane type passed to the method get_technical_attributes is not stored in the table saplane. Here,
however, the exception is only raised in the method get_technical_attributes, not handled there.
To pass the exception along to the caller of the method, we enter it after the RAISING keyword.
Now, the caller - that is, the method display_attributes - handles the exception. For this purpose, we
have implemented a TRY-ENDTRY control structure in this method. The method
get_technical_attributes is now called in the TRY block of this control structure.
If the exception is raised in the method get_technical_attributes, the program continues by handling this
exception. That is, the method get_technical_attributes is terminated and the appropriate CATCH block
is processed within the caller. Note in particular that the program no longer executes the WRITE
statements entered in the TRY block after get_technical_attributes is called.
(C) SAP AG
BC401
14-13
cx_no_check
cx_dynamic_check
cx_static_check
SAP AG 2002
Subclasses of CX_STATIC_CHECK: The relevant exception must either be handled, or passed along
explicitly using the RAISING addition. The syntax check ensures that this is the case. At present, only
exceptions you define yourself for error situations in the application code are subclasses of
CX_STATIC_CHECK.
Subclasses of CX_DYNAMIC_CHECK: The relevant exception does not have to be declared. If such an
exception occurs at runtime, just as with subclasses of CX_STATIC_CHECK, it must either be handled
or passed along explicitly using a RAISING addition. However, this is not checked in the syntax check.
If such an exception occurs at runtime and is not either handled or passed along, a runtime error occurs.
Most predefined exceptions with the prefix CX_SY_... for error situations in the runtime environment
are subclasses of CX_DYNAMIC_CHECK.
Subclasses of CX_NO_CHECK: These exceptions cannot be declared. These exceptions can be handled.
Otherwise they are automatically passed along. The syntax check never finds an error here. All
exceptions of the category CX_NO_CHECK that are not handled in the call hierarchy are automatically
passed to the top level, If they are not caught there, they cause a runtime error. Some predefined
exceptions with the prefix CX_SY_... for error situations in the runtime environment are subclasses of
CX_NO_CHECK.
(C) SAP AG
BC401
14-14
SAP AG 2002
(C) SAP AG
BC401
14-15
Copy your solution to the last exercise from the unit Events, or the corresponding
model solution SAPBC401_EVES_MAIN_B, with all their includes. Give them the
new names ZBC401_##_RAISE_TRY, ZBC401_##_RAISE_TRY_CL1, and
ZBC401_##_RAISE_TRY_CL2.
1-2
1-3
(C) SAP AG
14-16
1-4
(C) SAP AG
BC401
14-17
Include
BC401_EXCS_RAISE_TRY_CL2
*&---------------------------------------------------------------------*
...
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
"--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
METHODS: constructor IMPORTING
im_name
TYPE string
TYPE saplane-planetype
EXPORTING ex_weight
TYPE s_plan_wei
ex_tankcap
RAISING
DATA: name
(C) SAP AG
TYPE s_capacity
cx_bc401_invalid_planetype.
TYPE string,
BC401
14-18
"lcl_airplane DEFINITION
*------------------------------------------------------------------*
*
*------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
...
ENDMETHOD.
"constructor
METHOD display_attributes.
DATA: weight TYPE saplane-weight,
cap TYPE saplane-tankcap,
r_exception TYPE REF TO cx_root,
exc_text TYPE string.
WRITE: / icon_ws_plane AS ICON,
/ 'Name des Flugzeugs'(001), AT pos_1 name,
/ 'Type of airplane: '(002), AT pos_1 planetype.
* handle exception in case of invalid planetype:
TRY.
get_technical_attributes( EXPORTING im_type = planetype
IMPORTING ex_weight = weight
ex_tankcap = cap ).
WRITE: / 'Gewicht:'(003), weight,
'Tankkap:'(004), cap.
CATCH cx_bc401_invalid_planetype INTO r_exception.
exc_text = r_exception->get_text( ).
WRITE: / exc_text COLOR COL_NEGATIVE.
ENDTRY.
ENDMETHOD.
"display_attributes
METHOD display_n_o_airplanes.
...
(C) SAP AG
BC401
14-19
ENDMETHOD.
"display_n_o_airplanes
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 cx_bc401_invalid_planetype
EXPORTING planetype = im_type.
ENDIF.
ENDMETHOD.
ENDCLASS.
(C) SAP AG
"get_technical_attributes
"lcl_airplane IMPLEMENTATION
BC401
14-20
Dynamic Programming
Contents:
Dynamic attributes
Data reference variables
Field symbols
Runtime Type Identification (RTTI)
SAP AG 2002
(C) SAP AG
BC401
15-1
SAP AG 2002
(C) SAP AG
BC401
15-2
Dynamic Programming:
Integration in Course Content
Dynamic
ing
Programm
Exception
handling
chniques
Special Te
Interfaces
sses and
Global Cla
Events
Interfaces
Casting
and
Data Types
ts in
Data Objec
Detail
e
Inheritanc
ing
Programm
nt
Orie ed
of Objectes
pl
ci
rin
P
n
and Desig
Analysis
ing
Programm
d
te
Orien
to Objectn
tio
uc
Introd
al
Using Intern
Tables
rams
Calling Prog
Data
and Passing
rview
Course Ove
SAP AG 2002
(C) SAP AG
BC401
15-3
Field
Field Symbols
Symbols in
in Detail
Detail
Dynamic
Dynamic Calls
Calls
Data
Data References
References
Ascertaining
Ascertaining Data
Data Attributes
Attributes Dynamically
Dynamically
SAP AG 2002
(C) SAP AG
BC401
15-4
Field Symbols
FIELD-SYMBOLS <fs> TYPE|LIKE ... |TYPE ANY}.
ASSIGN ... dataobject TO <fs>.
UNASSIGN <fs>.
... <fs> IS ASSIGNED ...
Generic or
complete type
specification
fs_int
15
int
fs_int
15
int
<fs_int> = 17.
WRITE: / int, <fs_int>.
fs_int
17
int
fs_int
17
int
UNASSIGN <fs_int>.
IF <fs_int> IS ASSIGNED.
WRITE: / int, <fs_int>.
ELSE.
WRITE: / 'fieldsymbol not assigned'(fna).
ENDIF.
SAP AG 2002
You declare field symbols using the FIELD-SYMBOLS <fs> statement. Note that the parentheses
(<>) are part of the syntax.
Field symbols allow you to access an assigned data object - that is, all the accesses that you make to the
field symbol are made to the data object assigned to it. Field symbols are similar to dereferenced
pointers. Thus, you can only access the content of the data object to which the field symbol points. (That
is, field symbols use value semantics).
You use the ASSIGN statement to assign a data object to the field symbol <fs>. If the field symbol is
generically typed (TYPE ANY), it adopts the type of the data object.
By specifying a type for the field symbol, you can ensure that only compatible objects are assigned to it.
Example:
DATA: date TYPE d VALUE '19991231', time TYPE t.
FIELD-SYMBOLS: <fs_date> TYPE d, <fs_time> TYPE t.
ASSIGN: date TO <fs_date>, time TO <fs_time>.
<fs_time> = <fs_date>. returns a syntax error.
Conversely, using the following construction would deliver a runtime error:FIELD-SYMBOLS:
<fs_date> TYPE ANY, <fs_time> TYPE ANY.
Use the expression <fs> IS ASSIGNED to find out whether the field symbol <fs> is assigned to a
field.
The statement UNASSIGN <fs>. sets the field symbol <fs> so that it points to nothing. The logical
expression <fs> IS ASSIGNED is then false.
(C) SAP AG
BC401
15-5
sy
...
...
date
20011221
...
...
fs
SAP AG 2002
If you use the CASTING addition when you assign a data object to a field symbol that has a different
type, you can remove the restrictions of having to use the data object's original type. The access is then
interpreted as though the data object had the data type of the field symbol.
If you use the CASTING TYPE <type> addition when you assign a data object to a field symbol that
has a different type, you can access the data object using the field symbol as if the object had the type
<type>.
In the above example, note that the system field sy-datum is an elementary character-type component
of length 8.
You can also use type casting dynamically when you assign a data object to a field symbol.
For example:
PARAMETERS tabname TYPE dd02l-tabname.
DATA:
dummy TYPE i,
line(65535) TYPE c.
FIELD-SYMBOLS <fs_wa> TYPE ANY.
BC401
15-6
Field
Field Symbols
Symbols in
in Detail
Detail
Dynamic
Dynamic Calls
Calls
Data
Data References
References
Ascertaining
Ascertaining Data
Data Attributes
Attributes Dynamically
Dynamically
SAP AG 2002
(C) SAP AG
BC401
15-7
SUBMIT report_name.
* dynamic:
data_object = 'REPORT_NAME'.
SUBMIT (data_object).
SAP AG 2002
In many ABAP statements, you can pass attributes dynamically. The syntax for doing this differs,
depending on the statement you use:
If you pass the attribute as a literal in the static form of the statement, you can replace the literal with a
variable. If you pass the attribute as an identifier in the static form of the statement, you can replace the
identifier with a variable in parentheses. Make sure there are no spaces between either parenthesis and
the variable. If the attribute is a list, you can replace it with an internal table.
Note: you must use upper case when filling data objects with literals.
For more information on which of these three options you can use with a specific ABAP statement - if
any - refer to the ABAP documentation for that statement.
In Open SQL statements, you can also specify the logical conditions of the WHERE clause dynamically at
runtime, by entering the ABAP source code in a variable. In the FROM clause of the SELECT statement,
you can specify either individual table names or a dynamic JOIN expression using a variable. Similarly,
you can program the GROUP-BY and HAVING clauses in SELECT statements. For more information,
refer to the keyword documentation.
(C) SAP AG
BC401
15-8
TYPE-POOL abap.
TYPES abap_parmbind_tab ...
TYPES abap_excpbind_tab ...
Name of formal
parameter
...
Reference to the
actual parameter
How variable
is passed
(optional)
TYPE-POOLS abap.
DATA: ptab TYPE abap_parmbind_tab,
etab TYPE abap_excpbind_tab.
...
data_object = 'METHOD_NAME'.
* Fill ptab and etab
...
CALL METHOD ref->(data_object)
PARAMETER-TABLE ptab
EXCEPTION-TABLE etab.
ptab
name kind
Name of
exception
etab
value
Value for
sy-subrc
name
value
SAP AG 2002
You can call instance and static methods dynamically using parentheses in the syntax, as is normal in
ABAP. Use the PARAMETER-TABLE and EXCEPTION-TABLE additions of the CALL METHOD
statement to pass the actual parameters dynamically.
The parameter table must have the attributes of the ABAP_PARMBIND_TAB table type. The table has
three columns: NAME (for the name of the formal parameter); KIND for the way the parameter is
passed (exporting, importing, changing, or receiving); VALUE with the type REF TO data (for the
value of the actual parameter).
The way the parameter is passed is specified for each formal parameter in the declaration of the called
method. Thus, the content of the KIND column can be initial.
For the value of the actual parameter, the VALUE reference of the line in the table must point to the data
object containing that value. You can use the GET REFERENCE statement to achieve this.
The exception table must have the attributes of the ABAP_EXCPBIND_TAB table type. This table has
two columns: NAME for the name of the exception; VALUE for the value to be assigned to sy-subrc.
VALUE must be of type i.
(C) SAP AG
BC401
15-9
Field
Field Symbols
Symbols in
in Detail
Detail
Dynamic
Dynamic Calls
Calls
Data
Data References
References
Ascertaining
Ascertaining Data
Data Attributes
Attributes Dynamically
Dynamically
SAP AG 2002
(C) SAP AG
BC401
15-10
DATA
ref
Any completely
specified type
Generic type
assignment
DATA:
ref
do
15
ref
do
15
Data reference variables contain data references - that is, pointers to data objects. You use the TYPES
reftype TYPE REF TO type_name statement to define a reference type to a data object, where
type_name is any completely specified type. You can also use the generic variant TYPE REF TO
data here. You define the data reference variable itself using the DATA statement. This reference
variable is a data object that can contain any data object (TYPE REF TO data) or a data object of the
specified type.
You work with data references using references. That is, when you access a data reference variable the
data reference itself is accessed, so that changes are made to the addresses.
Data references are handled in ABAP like any data object with an elementary data type. This means that
a reference variable can be defined not only as a single field, but also as the smallest indivisible unit in a
complex data object, such as a structure or an internal table.
After it has been defined, the data reference variable is initial - that is, it contains an empty pointer. For a
data reference variable to contain a reference that points to a data object, you must use this variable to
get a reference to a data object that has already been declared (GET REFERENCE OF dataobject
INTO ref). You can also assign an existing data reference from another data reference variable or
generate a data object dynamically using it. (This will be discussed in more detail later.)
(C) SAP AG
BC401
15-11
abap_parmbind_tab,
LINE OF ptab,
string,
REF TO data,
string.
ptab
meth = 'GET_MAKE'.
CALL METHOD r_truck->(meth)
PARAMETER-TABLE ptab.
kind
value
EX_MAKE
gd_make
VOLVO
WRITE gd_make.
SAP AG 2002
In this example, the get_make method of the lcl_vehicle class is called dynamically. It has only
one export parameter and no exceptions.
First we define a parameter table ptab with the global table type abap_parmbind_tab from the
type group abap. The associated work area is called wa_ptab.
We fill the work area wa_ptab with the associated values. We assign the name of the export parameter
EX_MAKE to the component name. The component value contains the reference to the corresponding
actual parameter gd_make. We also define the data reference variable ref (TYPE REF TO data)
and fill the corresponding reference using GET REFERENCE. The kind component of the work area
need not be filled.
We then insert this work area in the parameter table ptab using the INSERT statement. Finally we
assign the name of the calling method to the data object meth. We then call the method using the syntax
already shown.
After the method call, the actual parameter gd_make contains the passed value.
(C) SAP AG
BC401
15-12
DATA
ref
{ TYPE REF TO type_name | LIKE REF TO do_name }.
CREATE DATA ref.
You can also
assign a type
dynamically
DATA ref
TYPE REF TO data.
CREATE DATA ref
PARAMETERS pa_tab
TYPE dd021-tabname.
DATA
ref_itab TYPE REF TO data.
ref_itab
All data objects declared in the declaration part of a program using the appropriate statement (such as
DATA) are generated statically and can be addressed from when the first event block is executed.
However, you can also use data reference variables to generate any data object you want dynamically
while the program is executing. You can use either of the above variants to do this.
Both of these variants generate a data object in the internal session of the current ABAP program. The
data reference in the data reference variable ref points to this object after the statement has been
executed. This dynamically generated data object does not have its own name; it can only be addressed
using the data reference variable. If you want to access the content of the data object, you need to
dereference the data reference first.
In the second variant, you specify the data type of the data object you want to generate after the TYPE
addition of the CREATE-DATA statement. In this case, you can specify the data type dynamically:
CREATE DATA ref TYPE (dataobject). You cannot do this in other ABAP statements.
dataobject is the name of a field containing the name of the relevant data type.
When you generate internal tables using the second variant, you must specify the table kind statically.
You can, however, specify the line type either statically or dynamically. You can also specify the key
components either statically or dynamically (as the contents of a table containing the component names).
You can also specify the initial number of table lines statically or dynamically (as the contents of a
variable).
(C) SAP AG
BC401
15-13
PARAMETERS pa_tab
DATA
ref_itab
TYPE dd021-tabname.
TYPE REF TO data.
fs_itab
ref_itab
SAP AG 2002
To access the contents of the data object, you need to dereference the data reference first. To access data
objects generated with data reference variables with generic types (TYPE REF TO data), you can use
field symbols: ASSIGN ref->* TO <fs>. This statement assigns the relevant data object (the one
to which the data reference in the reference variable ref points) to the field symbol <fs>. If the data
object i s assigned successfully, sy-subrc is set to 0. If the field symbol is fully generically typed, it
adopts the type of the data object. If the field symbol is partially or completely typed, the system checks
the compatibility of the data types. You can also cast to the assigned data object.
If the data reference in ref is initial or invalid, it cannot be dereferenced. In that case the field symbol
remains unchanged and sy-subrc is set to 4.
If the data reference variable ref is completely typed (that is, not generically), you can use the prefix
ref-> to access the contents of the data object to which ref is pointing. You can write this expression
in any operand position. If the data reference is typed, you can also address the components of the
referenced data object directly and use them in any operand position.
DATA ref TYPE REF TO sflight.
CREATE DATA ref.
ref->fldate = ref->fldate + 5.
WRITE: / ref->seatsmax.
(C) SAP AG
BC401
15-14
This example displays the content of a transparent table. You can make the FROM clause of the SELECT
statement dynamic. For the INTO clause, you will need a data object that has a line type compatible with
that of the table being displayed. Since the name - and thus the line type of the table is not known until
runtime, you should not create the data object until then.
Unlike conventional data objects, you can specify the type of a data object created at runtime
dynamically. The TYPE addition of the CREATE DATA statement contains the name of the table, so that
the system creates the appropriate structure.
The statement ASSIGN d_ref->* TO <fs_wa> assigns the data object to the field symbol. The
data type of the table is inherited by the field symbol, so type casting is no longer necessary.
You can now write each data record from the SELECT statement into the compatibly-typed data object
using the field symbol <fs_wa>.
If you knew the component names, you could display the fields directly using WRITE <fs_wa>-... .
However, you will not normally know the names of the components, nor how many of them there are.
For this reason, you must display the components using the ASSIGN-COMPONENT variant: The
components of the structure <fs_wa are assigned one-by-one to the field symbol <fs_comp> and then
displayed. When the loop runs out of components, the program reads the next data record.
(C) SAP AG
BC401
15-15
Field
Field Symbols
Symbols in
in Detail
Detail
Dynamic
Dynamic Calls
Calls
Data
Data References
References
Ascertaining
Ascertaining Data
Data Attributes
Attributes Dynamically
Dynamically
SAP AG 2002
(C) SAP AG
BC401
15-16
Number of lines in
the internal table
Number of lines
reserved when table
was first created
Table kind
* other variant:
no_of_lines = lines( itab ).
table_kind
Constants used
to evaluate the
return value
TYPE-POOL: sydes.
sydes_kind-undefined
sydes_kind-standard
sydes_kind-sorted
sydes_kind-hashed
SAP AG 2002
The DESCRIBE TABLE statement allows you to obtain the following information about an internal
table:
The number of lines:
After LINES, you must enter a type i variable (here no_of_lines)
The number of table lines initially reserved:After OCCURS, you must enter a type i variable (here:
initial_lines)
The table kind:
After KIND, you must enter a type c variable. The runtime system fills the variable with a constant
defined in the type group SYDES - SYDES_KIND-UNDEFINED, SYDES_KIND-STANDARD,
SYDES_KIND-SORTED, or SYDES_KIND-HASHED.
Since SAP R/3 Basis Release 6.10, there is also a built-in function, lines.
Note:
You can use the information about the number of lines in an internal table to query at runtime whether
an internal table has any entries in it at all. Alternatively, use the IS INITIAL query. The genericallytyped interface parameters of subroutines, function modules, and methods can use the information on the
table kind.
(C) SAP AG
BC401
15-17
Rules:
CL_ABAP_TYPEDESCR
CL_ABAP_TYPEDESCR
CL_ABAP_DATADESCR
CL_ABAP_DATADESCR
CL_ABAP_ELEMDESCR
CL_ABAP_ELEMDESCR
CL_ABAP_REFDESCR
CL_ABAP_REFDESCR
CL_ABAP_COMPLEXDESCR
CL_ABAP_COMPLEXDESCR
CL_ABAP_STRUCTDESCR
CL_ABAP_STRUCTDESCR
CL_ABAP_TABLEDESCR
CL_ABAP_TABLEDESCR
CL_ABAP_OBJECTDESCR
CL_ABAP_OBJECTDESCR
CL_ABAP_CLASSDESCR
CL_ABAP_CLASSDESCR
CL_ABAP_INTFDESCR
CL_ABAP_INTFDESCR
SAP AG 2002
Since the introduction of ABAP Objects, there is now a system called the RTTI concept (Run Time Type
Information) that you can use to find out type attributes at runtime. It is based on system classes. The
concept includes all ABAP types, and so covers all of the functions of the statements DESCRIBE
FIELD and DESCRIBE TABLE.
There is a description class for each type with special attributes for special type attributes. The class
hierarchy of the description classes corresponds to the hierarchy of the types in the ABAP type system.
In addition, the description classes for complex types, references, classes, and interfaces have special
methods used to specify references to sub-types. Using these methods, you can navigate through a
compound type to all its sub-types.
To obtain a reference to a description object of a type, you must use the static methods of the class
CL_ABAP_TYPEDESCR or the navigation methods of the special description class. The description
objects are then created from one of the subclasses. At runtime, exactly one description object exists for
each type. The attributes of the description object contain information on the attributes of the type.
(C) SAP AG
BC401
15-18
START-OF-SELECTION.
...
* get reference to type descripion 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.
SAP AG 2002
We can now enhance the example of dynamic type declarations so that the system also displays the
column names of the transparent table in the list.
Since we need the attributes of a structure, we first define a reference to the appropriate description
class. Instances of this class possess a COMPONENTS attribute, which you use to describe the individual
components of the relevant structure. This attribute is an internal table. Therefore you also need to define
a work area with a compatible line type.
The (functional) method call returns the reference to the description instance of the structure. (The
system creates the structure dynamically, which is why it is accessed through a field symbol).
Only the abstract class CL_ABAP_TYPEDESCR contains the method DESCRIBE_BY_DATA. Its
RETURNING parameter is typed as a reference to this superclass. However, since the actual parameter
descr_ref has the type of the subclass CL_ABAP_STRUCTDESCR, we need to assign the object
using a (widening) cast.
You can then access the attributes of the description instance in any form. In this example, the
component names are displayed as the column headers. (We have omitted the formatting options for the
sake of clarity.)
For more information and syntax examples, refer to the online documentation, either under the keyword
RTTI or the class CL_ABAP_TYPEDESCR.
(C) SAP AG
BC401
15-19
SAP AG 2002
(C) SAP AG
BC401
15-20
Exercise 1 Optional
Unit: Dynamic Programming
Topic: Casting Types
At the conclusion of these exercises, you will be able to:
Use field symbols to cast types
Perform calculations on dates
Change your program so that the default value for the key date is
calculated differently. It should be the first day of the following month.
Program:
ZBC401_##_CASTING
Template: SAPBC401_TABS_PROCESS_DATA
Model solution: SAPBC401_DYNS_CASTING
1-1
Copy your solution to the last exercise from the unit Using Internal Tables
ZBC401_##_PROCESS_DATA or the corresponding model solution
SAPBC401_TABS_PROCESS_DATA and give it the new name
ZBC401_##_CASTING.
1-2
Define a structure type (we suggest the name: st_date) with three components:
Year, month, and day. Assign an appropriate type to each component.
Define a field symbol based on this type (suggested name: <fs_date>).
1-3
(C) SAP AG
BC401
15-21
Screen Exercise 2
Unit: Dynamic Programming
Topic: Dynamic Open SQL Statements and Generating
Data Objects at Runtime
At the conclusion of these exercises, you will be able to:
Generate data objects dynamically
Program dynamic SQL statements
Develop an ABAP program that can be used as an ad hoc data browser.
You should be able to access only the table name on the selection screen.
Delegate filtering by field content and similar functions to an SAP Grid
Control instance, which you should also use to display the data.
The purpose of this program is to make you more familiar with dynamic
programming techniques. (There is already a Data Browser, installed as a
standard tool in the ABAP Workbench.)
Program:
ZBC401_##_CREATE_DATA_SQL
Template: SAPBC401_DYNT_CREATE_DATA_SQL
Model solution: SAPBC401_DYNS_CREATE_DATA_SQL
2-1
2-2
Get to know the source code and runtime behavior of this program.
Then implement the following concept: At runtime, the program should generate an
internal table whose line type is compatible with the selected transparent table. The
former should then be filled with the complete contents of the latter using a dynamic
SQL statement. The internal table filled in this way should then be passed to a SAP
Grid Control instance.
2-3
Define a reference for the internal table that will be generated (we suggest the name
ref_itab).
(C) SAP AG
BC401
15-22
2-4
At program runtime, generate the internal table. At this time, it is known which line
type must be used.
The table must be a standard table with a non-unique standard key.
2-5
2-6
Before calling the screen, insert an Open SQL statement that copies the complete
contents of the selected transparent table into the internal table using an array fetch.
If an error occurs, make sure the program terminates.
2-7
Generate a SAP Grid Control instance within the PBO module that you have created,
INIT_CONTROLS_0100. Again, if an error occurs, make sure the program
terminates.
The relevant class is called CL_GUI_ALV_GRID.
2-8
Pass the internal table filled in this way to this SAP Grid Control instance.
If an error occurs, make sure the program terminates.
The relevant method is called
SET_TABLE_FOR_FIRST_DISPLAY.
You need only pass values to two parameters: The line type to
I_STRUCTURE_NAME and the name of the internal table to
IT_OUTTAB.
(C) SAP AG
BC401
15-23
Solution 1 - Optional
Unit: Dynamic Programming
Topic:
Casting Types
REPORT sapbc401_dyns_casting.
TYPE-POOLS col.
TYPES:
BEGIN OF st_flight_c,
...
END OF st_flight_c,
BEGIN OF st_flight,
...
END OF st_flight,
BEGIN OF st_date,
year(4)
TYPE n,
month(2) TYPE n,
day(2)
TYPE n,
END OF st_date.
TYPE string,
set_string
TYPE string,
TYPE st_flight.
DATA:
(C) SAP AG
BC401
15-24
PARAMETERS:
pa_date LIKE sy-datum,
pa_alv
LOAD-OF-PROGRAM.
pa_date = sy-datum.
ASSIGN pa_date TO <fs_date> CASTING.
<fs_date>-day = '01'.
IF <fs_date>-month < 12.
<fs_date>-month = <fs_date>-month + 1.
ELSE.
<fs_date>-month = '01'.
<fs_date>-year = <fs_date>-year + 1.
ENDIF.
(C) SAP AG
BC401
15-25
AT SELECTION-SCREEN.
IF pa_date < sy-datum.
MESSAGE e085(bc401).
ENDIF.
START-OF-SELECTION.
...
(C) SAP AG
BC401
15-26
Solution 2
Unit:
Dynamic Programming
The copy template displays a selection screen where you can enter the name of a
transparent table. It then shows a screen that displays the contents of this table.
From this screen, you can either navigate back to the selection screen or end the
program.
This runtime behavior is implemented using standard ABAP programming techniques.
A docking container control instance that fills the whole screen has already been
generated and attached to the screen.
REPORT
sapbc401_dyns_create_data_sql.
DATA:
ok_code LIKE sy-ucomm,
popans.
DATA:
ref_docking TYPE REF TO cl_gui_docking_container,
ref_alv
TYPE REF TO cl_gui_alv_grid.
DATA ref_itab TYPE REF TO data.
FIELD-SYMBOLS <fs_itab> TYPE ANY TABLE.
PARAMETERS pa_tab TYPE dd02l-tabname DEFAULT 'SPFLI'.
(C) SAP AG
BC401
15-27
START-OF-SELECTION.
CREATE DATA ref_itab TYPE STANDARD TABLE OF (pa_tab)
WITH NON-UNIQUE DEFAULT KEY.
ASSIGN ref_itab->* TO <fs_itab>.
SELECT * FROM (pa_tab)
INTO TABLE <fs_itab>.
IF sy-subrc <> 0.
MESSAGE a000(rfw) WITH text-ndt.
ENDIF.
CALL SCREEN 100.
*&--------------------------------------------------------*
*&
Module clear_ok_code OUTPUT
*
*&--------------------------------------------------------*
MODULE clear_ok_code OUTPUT.
CLEAR ok_code.
ENDMODULE.
" clear_ok_code OUTPUT
*&--------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*
*&--------------------------------------------------------*
MODULE status_0100 OUTPUT.
SET PF-STATUS 'ST100'.
SET TITLEBAR 'T100'.
ENDMODULE.
" STATUS_0100 OUTPUT
*&--------------------------------------------------------*
*&
Module init_controls_0100 OUTPUT
*
*&--------------------------------------------------------*
MODULE init_controls_0100 OUTPUT.
IF ref_docking IS INITIAL.
= DOCK_AT_LEFT
= 2000
= 6
BC401
15-28
error_cntl_link
= 3
error_dp_create
= 4
OTHERS
= 5
.
IF sy-subrc <> 0.
MESSAGE a000(rfw) WITH text-aer.
ENDIF.
CALL METHOD ref_alv->set_table_for_first_display
EXPORTING
i_structure_name
= pa_tab
CHANGING
it_outtab
= <fs_itab>
EXCEPTIONS
invalid_parameter_combination = 1
program_error
= 2
too_many_lines
= 3
OTHERS
= 4
.
IF sy-subrc <> 0.
MESSAGE a033(rfw).
ENDIF.
ENDIF.
ENDMODULE.
" init_controls_0100
OUTPUT
*&--------------------------------------------------------*
*&
Module leave_programm INPUT
*
*&--------------------------------------------------------*
MODULE leave_programm INPUT.
CLEAR popans.
CALL FUNCTION 'POPUP_TO_CONFIRM_STEP'
EXPORTING
textline1
= text-dml
textline2
= text-rcn
titel
= text-cnc
cancel_display = ' '
IMPORTING
answer
= popans.
CASE popans.
WHEN 'J'.
LEAVE PROGRAM.
WHEN 'N'.
CLEAR ok_code.
ENDCASE.
ENDMODULE.
" leave_programm INPUT
*&--------------------------------------------------------*
*&
Module user_command_0100
*
*&--------------------------------------------------------*
(C) SAP AG
BC401
15-29
(C) SAP AG
BC401
15-30