Sie sind auf Seite 1von 433

TAW10 Introduction to the ABAP Workbench (2/2)

TAW10 2/2
ABAP Workbench Fundamentals
SAP AG 2003 SAP AG

n n n n

R/3 System Release 4.6D or above 2003/Q2 Material number 5006 0990

SAP AG

TAW10

0-1

Copyright

Copyright 2003 SAP AG. All rights reserved. No part of this publication may be reproduced or transmitted in any form or for any purpose without the express permission of SAP AG. The information contained herein may be changed without prior notice. All rights reserved.

SAP AG 2003

Comments on trademarks: n Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors. n Microsoft, WINDOWS, NT, EXCEL, Word, PowerPoint and SQL Server are registered trademarks of Microsoft Corporation. n IBM, DB2, DB2 Universal Database, OS/2, Parallel Sysplex, MVS/ESA, AIX, S/390, AS/400, OS/390, OS/400, iSeries, pSeries, xSeries, zSeries, z/OS, AFP, Intelligent Miner, WebSphere, Netfinity, Tivoli, Informix and Informix Dynamic ServerTM are trademarks of IBM Corporation in USA and/or other countries. n ORACLE is a registered trademark of ORACLE Corporation. n UNIX, X/Open, OSF/1 and Motif are registered trademarks of the Open Group. n Citrix, the Citrix logo, ICA, Program Neighborhood, MetaFrame, WinFrame, VideoFrame, MultiWin and other Citrix product names referenced herein are trademarks of Citrix Systems, Inc. n HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology. n JAVA is a registered trademark of Sun Microsystems, Inc. n JAVASCRIPT is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
n MarketSet and Enterprise Buyer are jointly owned trademarks of SAP AG and Commerce One.

SAP, R/, mySAP, mySAP.com, xApps, xApp, and other SAP products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other product and service names mentioned are the trademarks of their respective companies.

SAP AG

TAW10

0-2

Development Consultant mySAP Technology ABAP Workbench

TAW10

10 days

TAW12

15 days

mySAP Technology ABAP Workbench Fundamentals

mySAP Technology - ABAP Workbench Concepts

Development consultant certification mySAP Technology ABAP Workbench

SAP AG 2003

SAP AG

TAW10

0-3

Course Prerequisites

Required

l Solid EDP basic knowledge l Good programming experience in a different programming language

SAP AG 2003

SAP AG

TAW10

0-4

Target group Target group

l Development consultants and developers who are responsible for adapting and developing ABAP/ABAP Objects programs

Duration
l 10 days

SAP AG 2003

SAP AG

TAW10

0-5

Course Goals

At the end of this course, you will be able to:


l Work with the ABAP Workbench tools l Write your own simple ABAP programs l Program object-oriented ABAP Objects

SAP AG 2003

SAP AG

TAW10

0-6

Course Content: mySAP Technology ABAP Workbench Fundamentals

Preface Complex Complex Complex mySAP.com Technologies ABAP Workbench - Fundamentals ABAP Objects Case Study

SAP AG 2003

n n

This SAP Consultant Education training course contains different individual courses (sections), each of which deals with a separate topic Each individual course (section) is divided into different units.

SAP AG

TAW10

0-7

Complex

ABAP Objects

SAP AG 2003

SAP AG

TAW10

1-1

Course Content: ABAP Objects (1)

Unit Unit Unit Unit

Data Types and Data Objects in Detail Using Internal Tables Introduction to ObjectOriented Programming Analysis and Design

Unit Unit Unit Unit Unit

Principles of ObjectOriented Programming Inheritance Casting Interfaces Events

SAP AG 2003

SAP AG

TAW10

1-2

Course Content: ABAP Objects (2)

Unit Unit Unit Unit

Global Classes and Interfaces Special Techniques Exception Handling Dynamic Programming

SAP AG 2003

SAP AG

TAW10

1-3

Data Types and Data Objects in Detail

Contents:
l Data objects in programs l Elementary data objects l Structures l Character string processing in Unicode

SAP AG 2002

SAP AG

TAW10

2-1

Data Types and Data Objects in Detail: Unit Objectives

At the conclusion of this unit, you will be able to: l Use elementary data objects and structures appropriately l Use numeric data types appropriately l Use automatic type conversions appropriately l Take the special features of character string processing in Unicode into account

SAP AG 2002

SAP AG

TAW10

2-2

Data Types and Data Objects in Detail (1)

Introduction Introduction Elementary Data Objects Elementary Data Objects Structures Structures Special Features in Unicode Special Features in Unicode

SAP AG 2002

SAP AG

TAW10

2-3

Revision: Defining Data Objects

Local types TYPES type_name TYPE ... Predefined ABAP types d t i p

DATA do_name TYPE type_name. Global types

f n string c xstring x

DATA do_name_new LIKE do_name.


SAP AG 2002

n n

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.

SAP AG

TAW10

2-4

Predefined ABAP Types


Data type Numeric Description Length in bytes Attributes Differ in: Integer 4 Rules for storage Value range Arithmetic used Character string operations (allowed for all types) + date calculations + time calculations Float. point number 8 Packed number 1 .. 16

i f p Fixed length

Character string type

n c d t
Hexadecimal

Number sequence

1 .. 65535

Character sequence 1 .. 65535 Date 8 Time 6

x Variable length

Hexadecimal code

1 .. 65535

Bit operations

Character string type / hexadecimal

string xstring

Character sequence Hexadecimal code

Runtime system adjusts length dynamically

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.

SAP AG

TAW10

2-5

Type Groups in the ABAP Dictionary


Name of type group: Up to 5 characters; each type name and constant name starts with the name of the type group.

Type group zmytp TYPE-POOL zmytp zmytp. CONSTANTS zmytp zmytp_const_name ... [ TYPES zmytp zmytp zmytp_type_name1 ... ] [ TYPES zmytp zmytp_type_name2 ... ] ...

Each type group, whose types and constants you want to use, must be specified in the ABAP program

Using a constant: TYPE-POOLS: zmytp TYPE-POOLS zmytp. TYPE[ DATA var TYPE zmytp_type1. ] zmytp zmytp IF var = zmytp zmytp_const_name. ... ENDIF.
SAP AG 2002

ABAP program

n n

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.

SAP AG

TAW10

2-6

Data Types and Data Objects in Detail (2)

Introduction Introduction Elementary Data Objects Elementary Data Objects Structures Structures Special Features in Unicode Special Features in Unicode

SAP AG 2002

SAP AG

TAW10

2-7

Integers and Integer Arithmetic

DATA: counter TYPE i VALUE 1.

l l

Length: 4 bytes Value range [-2147483648; 2147483647] Integer Arithmetic

int1 = int2 / int3 + int4.

All internal auxiliary fields are integers Interim results are rounded
int2 = int1 4 = = int3 = 4 / 1 3 3 + + int4 = 2 2 2 Arithmetic operations for integers: + * / DIV MOD ** Addition Subtraction Multiplication Division Integer division Remainder integer div. Power

Integer auxiliary variable

SAP AG 2002

n n

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.

SAP AG

TAW10

2-8

Packed Numbers and Fixed Point Arithmetic


DATA: percentage(3) TYPE p DECIMALS 2 VALUE '12.34'. (3)

Length in bytes: n bytes correspond to 2n - 1 digits

Number of decimal places

Fixed point arithmetic: "like using paper and pencil" Number 12,34 Internal representation 0 1 2 3 4 +
1 digit per half-byte Sign

1234,56 78,5 1313,06

l Permitted length: 1 to 16 bytes (= 1 to 31 digits) l Number of decimal places < number of digits, max. 15 l Example: Length 3 bytes, 2 decimal places Value range: [-999.99,+999.99]

SAP AG 2002

n n

n n

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.

SAP AG

TAW10

2-9

Floating Point Arithmetic

|
-

1,5 = 120 +12 1 1 =1 + 2


| 0 0 |
-3 -6

Only 53 bits available

| 0 0 |
-7 -10

| ...
-11

0,15 = 12 + 12 + 12 + 12 + 12 + = 1 + 1 + 1 + 1 + 1 + 8 128 1024 2048 64


= 0,125 + = = = =
SAP AG 2002

Only for approximations

0,140625 + 0,1484375 + 0,1494140625+ 0,1499023437

n n

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.

SAP AG

TAW10

2-10

Summary: Recommendations for Using Numeric Data Types

Required:

Recommended predefined ABAP data type: ABAP data type: Type i, since calculations using integer arithmetic are fastest

Integers only

Decimal numbers for business calculations

Type p

Decimal numbers for rough calculations performed on very small or very large numbers

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

SAP AG

TAW10

2-11

Arithmetic and Mixed Expressions

l Fixed point arithmetic is the default l Integer arithmetic is only used if all the components are integers l Floating point arithmetic is used if at least one component is a floating point number l All components are converted to the relevant data type l After the calculation, all are converted to the result type

Example:
p DECIMALS 3 r = i a 201 / / i b 200 + + f c 0.0000...E+000

Float. point arithmetic Conversion after f and calculation

Interim result: 1.004999...E+000 + 1.005


SAP AG 2002

0.0000...E+000

1.004999...E+000 Conversion after p DECIMALS 3

n n

n n

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

SAP AG

TAW10

2-12

Predefined ABAP Types for Character Strings

Type t Description Time

Type d Date

Type n

Type c

Type string Char. string of variable variable length Variable

Sequence Fixed- length Fixedof digits char. string 1 .. 65535 characters

Length

6 digits HHMMSS By clock

8 digits 1 .. 65535 YYYYMMDD characters By Gregorian calendar Digits

Value range

Depends on Depends on codepage Conversion Conversion

Calculations

Time arithmetic HH:MM:SS

Date arithmetic Based on user default values

Conversion

Formatting options

SAP AG 2002

n n

n n

n n n

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'.

SAP AG

TAW10

2-13

Overview: Character String Processing


Description and notes

FIND FIND REPLACE TRANSLATE SHIFT CONDENSE OVERLAY

Found: sy-subrc = 0

ABAP BBAP a b ap BAP AP ABAP ABAP AB AP

Search in a character string Search in a character string character Position of search string using MATCH OFFSET off addition Replace first occurrence occurrence Replace all occurrences Move Move Remove space characters Overwrite : Spaces are overwritten by characters from the second character string Concatenate several Concatenate character strings Split a character string

ABAP ABAP ABAP AP AB P AAAA A B +A P ABCAP

CONCATENATE SPLIT

SAP AG 2002

n n n n n

Note for FIND statement (search in a character string): There are special comparison operators for strings, which you can use in logical expressions in a query (IF) to search more flexibly for character sequences in a character string. For more information, see the keyword documentation for IF. For every statement, the operands are treated like type c fields, regardless of their actual field type. No internal type conversions take place. All of the statements apart from TRANSLATE and CONDENSE set the system field sy-subrc. (SEARCH also sets the system field sy-fdpos with the offset of the character string found.) All of the statements apart from SEARCH are case-sensitive. To find out the occupied length of a string, use the standard function STRLEN(). For the SPLIT statement there is the variant SPLIT ... INTO TABLE <itab>, which you can use to split the character string dynamically. You do not need to specify the number of parts into which the string should be split.

SAP AG

TAW10

2-14

Accessing Parts of Fields

<statement> <field>+<off>(<len>) ...

Possible with any character-type field

REPORT ... PARAMETERS: pa_str(40) LOWER CASE, pa_pos TYPE i, pa_len TYPE i. WRITE pa_str+pa_pos(pa_len). +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>.

SAP AG

TAW10

2-15

Data Types and Data Objects in Detail (3)

Introduction Introduction Elementary Data Objects Elementary Data Objects Structures Structures Special Features in Unicode Special Features in Unicode

SAP AG 2002

SAP AG

TAW10

2-16

Defining Structures with Local Types


Definition of a structure type

TYPES: TYPES: OF s_name_type, BEGIN OF s_name_type prename(25) TYPE c, surname(25) TYPE c, title(5) TYPE c, END OF s_name_type. OF
Definition of a structure with reference to a user-defined type

Definition of a structure with implicit type construction

DATA: DATA: s_name TYPE s_name_type . s_name


Alternatives

DATA: DATA: BEGIN OF s_name, s_name prename(25) TYPE c, surname(25) TYPE c, title(5) TYPE c, OF s_name END OF s_name.

START-OF-SELECTION. s_name-prename = 'Smith'. s_names_name-surname = 'John'. s_name SAP AG 2002

n n

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.

SAP AG

TAW10

2-17

Defining Nested Structures with Local 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_address, name TYPE s_name_type, s_name_type street(15) TYPE c, city(25) TYPE c, END OF s_address.
Structure type s_name_type prename surname title

Nested structure s_address name prename surname title street city

s_address-name-surname = 'Smith'. s_address-city = 'London'. SAP AG 2002

Application: Logical subgrouping of data

n n n n n

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.

SAP AG

TAW10

2-18

Using Named Includes


DATA: BEGIN OF t_linetype, s_name_type prename(25) TYPE c, surname(25) TYPE c, title(5) TYPE c, END OF s_name_type. DATA BEGIN OF s_address. INCLUDE STRUCTURE s_name_type INCLUDE 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'. Structure type s_name_type prename surname title Structure with named include s_address prename surname title street city name

Use: Logical subgroup desired, but nested structures not technically possible

SAP AG 2002

In some cases, you cannot use nested structures, for example: Because you can only define database tables with flat line types In situations where user dialogs with a table -type display can only contain simple structures (such as in the SAP List Viewer or Table Control) In situations like these, you may still want to group parts of the structure and address it as a whole. You do this using named includes: You can include a substructure in another structure, and give this substructure a name: DATA: BEGIN OF structure_name, ... . INCLUDE STRUCTURE substructure_type AS name. DATA: ... , END OF structure_name. You can address this substructure using structure_name-name. You can address the fields in the substructure using structure_name-name-comp_name or directly using structure_name-comp_name. Technically, however, this structure is not nested. If naming conflicts occur - for example, if you want to include the same substructure twice - you can append another name to the component names using RENAMING. For further information, refer to the keyword documentation for the INCLUDE STRUCTURE statement.

SAP AG

TAW10

2-19

Data Types and Data Objects in Detail (4)

Introduction Introduction Elementary Data Objects Elementary Data Objects Structures Structures Special Features in Unicode Special Features in Unicode

SAP AG 2002

SAP AG

TAW10

2-20

Unicode: Overview

Previous problems l l Mixture of different incompatible character sets in one central system Data exchange between systems with incompatible character sets

a
a
Unicode
Solution: Unicode

? S

ONE codepage that comprises all known characters Every character is generally displayed by two bytes

? ?
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 Unicode-compatible. 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.

SAP AG

TAW10

2-21

Character-Type and Byte-Type Types

Character-type types in Unicode programs


byte-type Only components with the types c, n, d, and t d c t n Character-type structure types xstring

string

Difference between byte processing and character processing


c_field x_field G O E391B9A2

DATA: c_field(4) TYPE c VALUE 'HUGO', x_field(4) TYPE x VALUE 'E391B9A2'.

SHIFT c_field BY 2 PLACES [IN CHARACTER MODE]. SHIFT x_field BY 2 PLACES IN BYTE MODE.
SAP AG 2002

_ B9A20000

n n

In Unicode programs, the following data types are interpreted as character-type: c, n, d, t, string as well as structure types, that directly or in substructures only contain components with types c, n , d and t. In non-Unicode systems, a character of this type is one byte and in Unicode systems, it is as long as corresponds with the length of a character on the relevant platform. Variables of the types x and xstring are described as byte-type. The character string processing (for which, previously, all arguments were implicitly interpreted as type c fields) is separated into string processing for character-type and byte-type arguments. In the case of the string processing for character-type arguments, the single fields must be type c, n, d, t, or string; character-type structures are also permitted. If arguments of another type are transferred, this triggers a syntax or runtime error. The X variants of the string statement are distinguished from the character string commands by the IN BYTE MODE addition. For the character string varia nts, IN CHARACTER MODE is an optional addition. If the IN BYTE MODE addition is specified, only X fields and X strings are permitted as arguments. If arguments of another type are transferred, this triggers a syntax or runtime error.

SAP AG

TAW10

2-22

Functions and Comparison Operators


Length in characters Character-type type Byte-type type Length in bytes

Functions

STRLEN STRLEN

XSTRLEN BYTE-CO, BYTE-CA,

Comparison operators

CO, CA, CS, CP, CN, NA, NS, NP

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

DATA: x_field(4) TYPE x VALUE 'E391B9A2', len TYPE i. len = XSTRLEN( x_field ).

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 fie lds 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.

SAP AG

TAW10

2-23

Compatibility and Conversion

MOVE a TO b. b = a.

When are two types compatible? Two elementary types are compatible when they have exactly the same type and length (and, in the type case of packed numbers, the same number of decimal places ). decimal places Two structure types are compatible when they have the same structure and their components are compatible . components are same structure

Two table types are compatible if their row types are types compatible and their key definitions and table types compatible key definitions definitions are the same. are the same.

l l

No conversion takes place if type-compatible data objects are assigned If non-type-compatible data objects are assigned, conversion does take place if a conversion rule is defined

SAP AG 2002

n n n

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)

SAP AG

TAW10

2-24

Conversion Under Unicode (1)


Conversion between flat structures
MOVE struc1 TO struc2. struc1
C(6) N(4) X(3) N(4) I P(8)

Under what condition is this assignment possible?

struc2
C(4) C(3) C(3) X(3) C(4) I

struc1

Decisive criterion: Fragment view

struc2

Assignment is possible

C(10)

X(3)

C(4)

P(8)

Conversion between flat structures is possible if the fragments of the source and target structures match both in type and length in the length of the shorter structure.
SAP AG 2002

n n

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 adja cent components and alignment gaps (one group each for character-type 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.

SAP AG

TAW10

2-25

Conversion Under Unicode (2)


Conversion between structures and single fields
MOVE c_field TO struc. c_field
C(9)

Under what condition is this assignment possible?

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.

SAP AG

TAW10

2-26

Example of Using the Conversion Rules

PARAMETERS p_date LIKE sy-datum. DATA: BEGIN OF s_date, year(4) TYPE n, Character-type month(2) TYPE n, single field day(2) TYPE n, END OF s_date. MOVE p_date TO s_date. s_date-day = '01'. MOVE s_date TO p_date.
p_date

Character-type structure

s_date

l l

Since the structure s_date is purely character-type, it is treated like a type c data object during conversion. This means it is transferred left-aligned, character by character.

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.

SAP AG

TAW10

2-27

Offset and Length Accesses and Elementary Data Objects


Access to single fields specifying offset and length <statement> <field>+<off>(<len>) ...

DATA: c_field(6) TYPE c VALUE '*ABAP#', x_field(6) TYPE x VALUE 'E391B9A203F6'.

c_field

WRITE: c_field+1(4), x_field+3(2).

x_field E391B9A203F6

l l

For character-type fields, offset and length are interpreted character by character. In the case of byte-type fields, the values for offset and length are . taken in bytes.

SAP AG 2002

n n

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.

SAP AG

TAW10

2-28

Offset and Length Accesses and Structures

Accessing structures by specifying offset and length <statement> <structure>+<off>(<len>) ...

DATA: BEGIN OF member, title(5) TYPE prename(15) TYPE surname(15) TYPE age TYPE city(20) TYPE END OF member.

c, c, c, i, c,

member
C(5) C(15) C(15) I C(20)

+off(len)

PERFORM use_name USING member+5(30).

l l l

Structure must start with a character-type fragment. Access is only allowed within the character-type initial part. Offset and length specifications are interpreted as characters.

SAP AG 2002

n n

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.

SAP AG

TAW10

2-29

Data Types and Data Objects in Detail: Summary

You are now able to: l Use elementary data objects and structures appropriately l Use numeric data types appropriately l Use automatic type conversions appropriately l Take the special features of character string processing in Unicode into account

SAP AG 2002

SAP AG

TAW10

2-30

Data Types and Data Objects in Detail Exercise 1


Unit: Data Types and Data Objects in Detail Topic: Defining Data Types and Data Objects Basic Statements Processing Character Strings
At the conclusion of these exercises, you will be able to: Define structure types locally in the program Define elementary and complex data objects Split strings Use conversion rules Display the contents of data objects in lists In this exercise, you will use a template to create a program that receives a single data record from the database table SFLIGHT in form of a character string. The program will split the this character string into its components and display it formatted in a list. Because the focus of this exercise is not on the transfer of data as a character string, we will use a function module that will provide us with the required database. This will simulate actual cases, such as data transfer from an external system. Program: Template: ZBC401_##_SPLIT_STRING SAPBC401_DTOT_SPLIT_STRING SAPBC401_DTOS_SPLIT_STRING

Model solution:

## is your two-digit group number 1-1 Copy the program, SAPBC401_DTOT_SPLIT_STRING and give it the new name ZBC401_##_SPLIT_STRING. 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.) 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 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-2

1-3

SAP AG

TAW10

2-31

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. As a test, display the fields of the structure, wa_flight_c in a list. 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.

1-5 1-6

SAP AG

TAW10

2-32

Data Types and Data Objects in Detail Solution 1


Unit: Data Types and Data Objects in Detail Topic: Defining Data Types and Data Objects Basic Statements Processing Character Strings
REPORT
TYPES: BEGIN OF st_flight_c, mandt(3) carrid(3) connid(4) fldate(8) price(20) currency(5) planetype(10) seatsmax(10) seatsocc(10) TYPE c, TYPE c, TYPE n, TYPE n, TYPE c, TYPE c, TYPE c, TYPE n, TYPE n,

sapbc401_dtos_split_string.

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) connid(4) fldate price(9) currency(5) TYPE c, TYPE n, TYPE d, TYPE p DECIMALS 2, TYPE c,

planetype(10) TYPE c, seatsmax seatsocc TYPE i, TYPE i,

END OF st_flight.

DATA: datastring SAP AG TYPE string, TAW10 2-33

set_string

TYPE string,

wa_flight_c TYPE st_flight_c, wa_flight TYPE st_flight.

START-OF-SELECTION.

CALL FUNCTION 'BC401_GET_SEP_STRING' * EXPORTING * * * * IM_NUMBER IM_TABLE_NAME IM_SEPARATOR IM_UNIQUE IMPORTING ex_string EXCEPTIONS no_data OTHERS = 1 = 2. = datastring = '1' = 'SFLIGHT' = '#' = 'X'

IF sy-subrc <> 0. MESSAGE a038(bc401). ENDIF.

SHIFT datastring BY 2 PLACES. FIND '##' IN datastring. IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF. SPLIT datastring AT '##' INTO set_string datastring.

SPLIT set_string AT '#' INTO wa_flight_c-mandt wa_flight_c-carrid wa_flight_c-connid wa_flight_c-fldate wa_flight_c-price wa_flight_c-currency wa_flight_c-planetype SAP AG TAW10 2-34

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.

MOVE-CORRESPONDING wa_flight_c TO 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.

SAP AG

TAW10

2-35

Using Internal Tables

Contents:
l Introduction and advantages of internal tables l Defining internal tables l Internal table operations l Notes on performance l Special internal tables

SAP AG 2002

SAP AG

TAW10

3-1

Using Internal Tables: Unit Objectives

At the conclusion of this unit, you will be able to: l Define internal tables l Perform operations on internal tables l Identify table kinds and use them appropriately in different situations

SAP AG 2002

SAP AG

TAW10

3-2

Using Internal Tables (1)

Introduction and advantages of internal tables Introduction and advantages of internal tables Introduction Definition Definition Operations Operations Special situations Special situations Notes on performance Notes on performance

SAP AG 2002

SAP AG

TAW10

3-3

The Internal Table - a Data Object of Variable Length

Elementary data objects

ABAP program

Structures

Static data objects (except for types STRING, XSTRING)

Internal table At runtime, the runtime system allocates memory for the lines in the table as needed (dynamic table extension)

SAP AG 2002

n n n

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.

SAP AG

TAW10

3-4

Attributes of Internal Tables

CARRID CONNID DISTANCE DISTID Line index

Line type

1 2 3 4 5 6

AA LH LH QF SQ UA

0017 0400 0402 0005 0866 0007

2.572 6.162 5.136 10.000 1.625 2.572

MI KM KM MI MI MI
SQ 0866 0866 2

Index access

Key access

Key definition
(Key fields (Sequence Sequence (Uniqueness Uniqueness
SAP AG 2002

Table kind Standard table Standard Sorted table Hashed table table

Each internal table has the following attributes: Line type: You use the line type to specify which columns are to be included in your internal table. You must assign a name and type to each column. You generally define a line type using a structure type. Key: Internal tables have a key, just like database tables. The key is defined by: Specifying the columns that should belong to the key; the sequence; and whether or not the key should be unique or nonunique . Depending on how you define your internal table, the runtime system may create an additional unique key (the index) for some internal tables (this will be discussed in more detail later). For simplicity's sake you can think of the index as a line number. Table kind: There are three table kinds in ABAP. Each kind has different attributes, which specify whether the key is unique, how the index is managed, and how the table data is addressed internally. The table kind specifies the possible accesses. The purpose of this is to provide particular support for special access types from the runtime system (will be discussed later).

SAP AG

TAW10

3-5

Link Between Table Kind and Access Type

Index tables Table kind Index access n

Hashed table

STANDARD TABLE

SORTED TABLE TABLE

HASHED TABLE TABLE

Key access
Table scan Table scan

Binary search

Hash function

Uniqueness

NON- UNIQUE

UNIQUE | NON-UNIQUE

UNIQUE

Access by

Mostly index

Mostly key

Key only

SAP AG 2002

The table kind is linked to the access type as follows: n You can only perform an index access (the fastest type of access) on STANDARD and SORTED tables. n The runtime system implements key accesses of SORTED and HASHED tables in a way that optimizes runtime performance. Key access of STANDARD tables is by table scan - that is, comparing the field contents with the search key line by line, in a loop. n The runtime system implements key accesses of SORTED tables, for fully or partly qualified keys (left-aligned, no gaps, all fields filled with an "=") in a special way to optimize runtime. The same applies to partial sequential loops, where the loop condition is specified using the key fields. With the runtime-optimizing access, the runtime system keeps SORTED tables sorted by key fields, In all other cases, the system performs a table scan. n The runtime optimizes key accesses of HASHED tables for fully qualified keys only. The table entries are addressed by means of a special hash algorithm. This minimizes access time for reading single records with fully qualified keys. The access time is thus independent of the number of lines in the table. In all other cases, the system performs a table scan. This means that you should only use HASHED tables if you want to access table entries using a fully-qualified key.

SAP AG

TAW10

3-6

Using Internal Tables (2)

Introduction and advantages of internal tables Introduction and advantages of internal tables Definition Definition Definition Operations Operations Special situations Special situations Notes on performance Notes on performance

SAP AG 2002

SAP AG

TAW10

3-7

Overview: Types of Definitions for Internal Tables

With local table type

Implicit table type

With global table type

Local table type

Global table type

TYPES: local_type ...


Table attributes

global_type
Table attributes

Internal table

Internal table

Internal table

DATA: t_list TYPE local_type local_type.

DATA: t_list TYPE ...


Table attributes

DATA: t_list TYPE global_type global_type.

SAP AG 2002

There are several ways to define an internal table in ABAP: Use the TYPES statement to define a table type. Then use this to assign a type to one or more data objects or interface variables. Alternatively, declare the table attributes directly when you define the data object (that is, use a bound type). The third option is to define an internal table using a global table type (defined in the ABAP Dictionary). The tables you define using the first or second option are visible only in the program in which you define them. Whenever you need table type visible from all programs, create a global table type (that is, use the third option).

SAP AG

TAW10

3-8

The Data Type of an Internal Table


Local table type/internal table type/internal table TYPES
or

DATA

Attributes
( Table kind ( Line type (columns) ( Key ( Initial size (optional)

name TYPE table_kind TYPE table_type OF OF line_type key_def WITH key_def [ INITIAL SIZE n ].

Global table type Attributes global_type


( Table kind Input on screen used to specify attributes ( Line type (columns) ( Key

SAP AG 2002

n n n n

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).

SAP AG

TAW10

3-9

Table Attribute: Line Type


Line type type
Local structure type Global structure type Local structure

TYPES TYPES: BEGIN OF line_type line_type, ... END OF line_type.

line_type line_type

DATA DATA: structure TYPE ... structure structure

Table type ... name TYPE table_kind TYPE OF OF line_type line_type ... name LIKE table_kind LIKE OF structure structure WITH key_def [ INITIAL SIZE n ].

WITH key_def [ INITIAL SIZE n ].


SAP AG 2002

n n n

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, nonnested 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.

SAP AG

TAW10

3-10

Table Attribute: Table Kind and Key

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
SAP AG 2002

key_def
[NON-UNIQUE] { KEY col1 ... coln | DEFAULT KEY } {UNIQUE | NON-UNIQUE} KEY col1 ...coln UNIQUE KEY col1 ... coln

TABLE TABLE

n n n

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.

SAP AG

TAW10

3-11

Example: Standard Table with Local Type


Line type:

TYPES: s_distance_ty BEGIN OF 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 tt_distance_ty OF s_distance_ty WITH NON-UNIQUE KEY distance distid.
Internal table Internal table of the table kind STANDARD TABLE

DATA: tt_distance_ty tt_distance TYPE tt_distance_ty. tt_distance _distance


SAP AG 2002

n n n

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.

SAP AG

TAW10

3-12

Example: Sorted and Hashed Table


Sequence Sorted table carrid connid distance 2 1 2 3 4 distid 1

DATA: distance_ranc TYPE SORTED TABLE s_distance_ty s_distance_ty OF s_distance_ty WITH NON-UNIQUE KEY distid distance.
Sequence Hashed table:

LH LH AA QM

0402 0400 0017 0005

6.162 6.162 2.572 10.000

KM KM MI MI

Sequence carrid 1 connid 2 distance distid

DATA: distance_buffer distance_buffer TYPE HASHED TABLE s_distance_ty OF s_distance_ty WITH UNIQUE KEY carrid connid.

LH AA QM LH

0400 0017 0005 0402

6.162 2.572 10.000 6.162

KM MI MI KM

SAP AG 2002

n n

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.

SAP AG

TAW10

3-13

The Standard Table Type

DATA: t_name TYPE TABLE OF line_type.

Definition by standard table type

Interpreted by the system as:

DATA: t_name TYPE STANDARD TABLE TYPE 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.

SAP AG

TAW10

3-14

Internal Tables with an Unstructured Line Type


Definition:

DATA: it_fields TYPE STANDARD TABLE OF dd03l-fieldname WITH KEY table_line, table_line table_

wa_field

TYPE dd03l-fieldname.

Fill:

SELECT fieldname FROM dd03l "table of transp. tables INTO TABLE it_fields WHERE tabname = 'SPFLI'.

Key access:

READ TABLE it_fields INTO wa_field WITH KEY table_line = 'CITYFROM'. table_line table_

SAP AG 2002

n n n

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 .

SAP AG

TAW10

3-15

Using Internal Tables (3)

Introduction and advantages of internal tables Introduction and advantages of internal tables Definition Definition Operations Operations Operations Special situations Special situations Notes on performance Notes on performance

SAP AG 2002

SAP AG

TAW10

3-16

Overview: Types of Operation

Internal table as a data object object

Operations on one or more lines

Editing lines in a loop a loop

or

( Copy ( Initialize ( Initialize

( MOVE )

( Insert ( Read

( INSERT ) ( READ )

( Edit lines
sequentially

( CLEAR ) Keep memory available ( FREE ) Release memory

( Change ( MODIFY ) ( Delete


( DELETE )

( Compare using operators =,<>,><,<=,<=,>,< ( Sort


( SORT )

( Insert summated
( COLLECT )

LOOP ... * command block ENDLOOP.

( Array Fetch ( SELECT ... INTO TABLE )


SAP AG 2002

You can perform three different types of operations on internal tables: n Operations on the whole data object: Elementary operations available include MOVE (copy the content line by line), CLEAR (delete the content, but keep the memory allocated), and FREE (delete the content and release the memory). You can also use all the numerical comparison operators with internal tables in logical expressions. With these operators, the number of lines is compared first and then, if necessary, the line contents. (This is recursive for deep types). For more information, refer to the documentation on internal tables. You can use the SORT statement to sort the content of STANDARD and HASHED tables. This statement allows you to sort the table by one or columns, specifying ascending or descending for each column. For more details, refer to the keyword documentation for the SORT statement. You can use the SELECT ... INTO TABLE statement to copy the contents of database tables directly into internal tables. n Operations on lines: You can use the INSERT, READ, MODIFY, DELETE, and COLLECT statements to perform operations on one or more lines in the internal table. The syntax of the first four of these statements is dealt with in the slides that follow. For the syntax of the COLLECT statement, refer to the online documentation. n Loop processing: You can use the LOOP AT ... ENDLOOP statement to process the lines of the internal table sequentially. The exact syntax for this is dealt with in the slides that follow.

SAP AG

TAW10

3-17

Limiting the Scope of Line Operations: Target Records and Access Type
Specify set of target records
Table key n <condition> [ n1 ... n2 ] Line index (for index tables) Condition applied to any number of columns Index interval (for index tables)

Specify access type / data transfer type


Table Work area Field symbol

Copying process
SAP AG 2002

Direct access by dereferenced pointer

Insert Insert using table

n n

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.

SAP AG

TAW10

3-18

Preview: Field SymboIs (1)


Data objects in the ABAP program Defining a field symbol:

DATA: var_a TYPE i VALUE 4. FIELD-SYMBOLS: <fs> TYPE i. FIELD-SYMBOLS FIELD-

<fs> var_a

Assigning a data object to a field symbol:

<fs> var_a

ASSIGN var_a TO <fs>. 4

Assigning a value to a data object using a field symbol:

<fs> var_a

<fs> = 77. 77

Time
SAP AG 2002

n n

n n n n

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.

SAP AG

TAW10

3-19

Preview: Field SymboIs (2)


Defining the field symbol:
Data objects in the ABAP program

DATA: it_sflight TYPE TABLE OF sflight. FIELD-SYMBOLS: <fs> TYPE sflight.

<fs> it_sflight

Assigning a line to the field symbol: <fs>

* ... to be continued ...


it_sflight

Accessing the line content using the field symbol:

<fs> it_sflight

WRITE <fs>-connid. <fs>-carrid = 'LH'.

SAP AG 2002

n n

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.

SAP AG

TAW10

3-20

Insert
Key from "wa" specifies the line itab wa

* fill workarea "wa" INSERT wa INTO TABLE itab. INSERT INTO TABLE
itab

wa

* fill workarea "wa"


n n

INSERT wa INTO itab INDEX n. INSERT INTO INSERT LINES OF itab1 INSERT LINES OF

itab1 [n1] [n2]

itab2

[ FROM n1 TO n2 ] target.
n

Only if itab1 is an index table

target INTO TABLE itab2. INTO TABLE


n

INTO itab2 [ INDEX n ]. INTO

SAP AG 2002

To insert lines into a table, use the INSERT statement: n Using INSERT wa INTO TABLE itab, you insert the line whose data are stored in wa into the internal table. The record is inserted with reference to the table key. In STANDARD tables, the new line is appended to the end of the table. n Using INSERT wa INTO itab INDEX n, you insert the data from wa into the internal table at the line with the index n. If n is an index value within the internal table, the lines with the index value greater than or equal to n are pushed downwards. If n-1 is greater than the number of lines in the internal table, the line is not inserted. n Always add new lines to a SORTED table using the key. If you try to insert a line into a SORTED table using the index, you will not succeed unless the line has exactly the same index number as it would have when correctly sorted. Otherwise, a runtime error occurs. n Use INSERT LINES OF itab1 INTO TABLE itab2 to insert the lines of the internal table itab1 into the internal table itab2. Also, if itab1 is an index table, you can limit the number of lines to be inserted using an index interval (FROM n1 TO n2). n If your target table is an index table, you can use INSERT LINES OF itab1 INTO itab2 to insert the lines of the internal table itab1 into the internal table itab2. You can then specify the line index from which the lines are to be inserted using INDEX n. Also, if itab1 is an index table, you can limit the number of lines to be inserted using an index interval (FROM n1 TO n2).

SAP AG

TAW10

3-21

Reading a Single Record into a Work Area Using the Line Number
itab wa n n

Index

READ TABLE itab INDEX n INTO wa [ options ]. INDEX

[ options ] COMPARING COMPARING comp_list comp_list TRANSPORTING trans_list ( f1 ... fm ( ALL FIELDS trans_list ( f1 ... fk ( NO FIELDS
Beliebige Feldliste Any field list

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 whic h 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 sysubrc 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.

SAP AG

TAW10

3-22

Reading a Single Record into a Work Area Using the Field Contents
Key
itab wa Explicit table key Any content from field list wa1 Table key from wa1

READ TABLE itab search_clause INTO wa [ options ].


As in index access

search_clause
Table key

FROM wa1 WITH TABLE KEY k1 = f1 ... kn = fn

Any field contents


SAP AG 2002

WITH KEY col1 = f1 ... colm = fm [BINARY SEARCH]

n n

n n

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.

SAP AG

TAW10

3-23

Reading a Single Record Using a Field Symbol

itab <fs>

Key

or n

Index

FIELD-SYMBOLS: <fs> LIKE LINE OF itab. INDEX n INDEX READ TABLE itab key WRITE: / <fs>-field_1 ... <FS>-field_1,
Same as when reading into a work area
SAP AG 2002

Index Key

ASSIGNING < > <fs>.

n n

n n

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 subcomponents 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.

SAP AG

TAW10

3-24

Changing the Table Using a Work Area


Key from "wa" specifies the line itab wa

* fill workarea "wa" MODIFY TABLE itab FROM wa FROM [ TRANSPORTING f1 ... fn ]. TRANSPORTING

itab wa n n

* fill workarea "wa" MODIFY itab FROM wa INDEX n INDEX [ TRANSPORTING f1 ... fn ].

itab wa

WHERE log_expr.

MODIFY itab FROM wa FROM TRANSPORTING f1 f2 ... TRANSPORTING 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 nonunique 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.

SAP AG

TAW10

3-25

Changing a Single Record Using a Field Symbol

itab <fs> 1

Key

or 2 n

<fs>-field_1 = ...

Index

FIELD-SYMBOLS: <fs> LIKE LINE OF itab. INDEX n


1 n

Index Key

READ TABLE itab key

ASSIGNING <fs>.

<fs>-field_1 = <FS>-field_1 fs>

...

Cannot be key field in sorted or hashed tables


SAP AG 2002

Same as when reading into a work area

n n

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.

SAP AG

TAW10

3-26

Delete
* fill workarea "wa"
itab Table key wa

DELETE TABLE itab key. key


Explicit

( FROM wa ( WITH TABLE KEY k1 = f1 ... kn = fn

itab n n

DELETE itab INDEX n.

Delete using a condition

WHERE log_expr.

DELETE itab WHERE log_expr.

SAP AG 2002

n n

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).

SAP AG

TAW10

3-27

Loop Processing
result
wa itab

result
<fs>

( INTO wa ( ASSIGNING <fs>

LOOP AT itab result [TRANSPORTING NO FIELDS] { [ FROM n1 ] [ TO n2 ] | FROM [ WHERE log_expr ] } . WHERE ... ENDLOOP ENDLOOP. ENDLOOP
SAP AG 2002

Index tables only

Index table: sy-tabix contains line index of current line

n n n

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 sytleng. 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.

SAP AG

TAW10

3-28

Overview of Operations
Standard table Sorted table Hashed table

SORT
Index access
n

INSERT READ TABLE MODIFY DELETE LOOP AT


Key access Append to end of table

Sort sequence could be violated

No index accesses to hashed tables

INSERT READ TABLE MODIFY DELETE LOOP AT


SAP AG 2002

n n

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.

SAP AG

TAW10

3-29

Using Internal Tables (4)

Introduction and advantages of internal tables Introduction and advantages of internal tables Definition Definition Operations Operations Special situations Special situations situations Notes on performance Notes on performance

SAP AG 2002

SAP AG

TAW10

3-30

Internal Tables with a Header Line


DATA: Syntax variant 1 itab TYPE TABLE OF scarr WITH DEFAULT KEY WITH HEADER LINE LINE. DATA: Syntax variant 2 (obsolete) itab TYPE scarr OCCURS 0 OCCURS WITH HEADER LINE WITH HEADER LINE. LINE
Body itab itab Data object itab itab itab Work area = header

DATA: Syntax variant 3 (obsolete) BEGIN OF itab OCCURS 0, OCCURS carrid TYPE s_carr_id, ... url TYPE s_carrurl, END OF itab. OF
SAP AG 2002

n n n

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.

SAP AG

TAW10

3-31

Selection Options and Selection Tables


DATA: carrid TYPE s_carr_id. SELECT-OPTIONS SELECT-OPTIONS: SELECT OPTIONS so_carr FOR carrid. FOR ( Link to selection screen
so_carr ( Data object so_carr Identically-typed data object without header or link to selection screen

DATA: so_carr LIKE RANGE OF carrid. RANGE OF


sign(1) TYPE c option(2) TYPE c
SAP AG 2002

low LIKE carrid high LIKE carrid

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.

SAP AG

TAW10

3-32

Using Internal Tables (5)

Introduction and advantages of internal tables Introduction and advantages of internal tables Definition Definition Operations Operations Special situations Special situations Notes on performance Notes on performance

SAP AG 2002

SAP AG

TAW10

3-33

Single Record Access: Completely and Partially Qualified Key


READ TABLE itab INTO wa WITH TABLE KEY key. WITH TABLE KEY key
Must be completely qualified Table scan Binary search Hash algorithm Table kind

STANDARD

SORTED

HASHED

READ TABLE itab INTO wa WITH KEY key. WITH KEY STANDARD key
Complete/part key left-aligned without gaps leftBy qualified key Any component condition condition
SAP AG 2002

Table kind

SORTED
Binary search

HASHED

Table scan

Table scan

Table scan

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. n 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: n Whenever possible, use READ TABLE ... WITH TABLE KEY or the variant with a correspondingly-filled work area. n If you need to use READ TABLE ... WITH KEY, make your internal table a SORTED table.

SAP AG

TAW10

3-34

Loop Processing and Table Kinds


LOOP AT itab INTO wa log_ expr WHERE log_expr. ... ENDLOOP. STANDARD log_expr
First n key fields filled with "=" without gaps without gaps Binary search for starting point, then loop only through group level Table scan

Table kind

SORTED

HASHED

Table scan

Table scan

Any logical expression for columns columns

SAP AG 2002

n n

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).

SAP AG

TAW10

3-35

Partial Sequential Loop Through Standard Tables


Desired: Loop through data records where CITYFROM = 'FRANKFURT' CARRID AA LH LH UA UA CONNID CITYFROM 400 FRANKFURT 2407 BERLIN 941 FRANKFURT 3516 NEW YORK ... ... ... ... ... SORT ... BY cityfrom STABLE. CARRID CONNID CITYFROM LH Ascertain starting point: READ TABLE ... WITH KEY cityfrom = 'FRANKFURT' TRANSPORTING NO FIELDS BINARY SEARCH. startline = sy-tabix. Ascertain end point: READ TABLE ... INTO ... WITH KEY cityfrom = 'NEW YORK' TRANSPORTING NO FIELDS BINARY SEARCH. endline = sy-tabix.
SAP AG 2002

64 SAN FRANCISCO ...

... ... ... ...

2407 BERLIN 400 FRANKFURT 941 FRANKFURT

LH UA UA AA

3516 NEW YORK ... 64 SAN FRANCISCO ...

Index-controlled loop: LOOP AT ... INTO ... FROM startline to endline. ... ENDLOOP.

n n

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.

SAP AG

TAW10

3-36

Access Using Field Symbols

READ TABLE itab ASSIGNING <fs1> WITH TABLE KEY ... . READ TABLE <fs1>-col3 ASSIGNING <fs2> WITH TABLE KEY ... .
<fs2>

READ TABLE itab INTO wa1 WITH TABLE KEY ... . READ TABLE wa1-col3 INTO wa2 WITH TABLE KEY ... .
wa2 wa1 Copy

<fs1> Copy

col1

col2

col3

col4

itab

col1

col2

col3

col4

SAP AG 2002

n n

n n

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.

SAP AG

TAW10

3-37

Using Internal Tables: Unit Summary

You are now able to: l Define an internal table l Perform operations on internal tables l Identify table kinds and use them appropriately in different situations

SAP AG 2002

SAP AG

TAW10

3-38

Using Internal Tables Exercise 1


Unit: Using Internal Tables Topic: Single-Column Tables of the Type string
At the conclusion of these exercises, you will be able to: Define single-column tables of the data type string Split character strings with internal tables Process internal tables in loops Now, the character string will contain more than one data record. Extend your program in such a way that the various data records in the rows of an internal table are split. Then separate the individual data records into single components and output them as before. Program: Template: ZBC401_##_SPLIT_ITAB SAPBC401_DTOS_SPLIT_STRING SAPBC401_TABS_SPLIT_ITAB

Model solution:

## is your two-digit group number 1-1 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. Ensure that the function module BC401_GET_SEP_STRING creates a character string consisting of 30 data records. For this you must assign a suitably typed constant (suggested name c_number) to the parameter im_number. Define a single-column internal table of the type Standard. The column component is to have the data type string (suggested name: it_sets). 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. 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.

1-2

1-3

1-4

1-5

SAP AG

TAW10

3-39

Exercise 2 - Optional
Unit: Using Internal Tables Topic: Table Types
At the conclusion of these exercises, you will be able to: Select the appropriate types of internal table Process data using internal tables Now the character string will contain duplicate data records. Extend your program in such a way that the various data records are kept sorted in internal tables. Those data records that appear twice are to be sorted into a separate internal table. Program: Template: ZBC401_##_TABKIND SAPBC401_TABS_SPLIT_ITAB SAPBC401_TABS_TABKIND

Model solution:

## is your two-digit group number 2-1 Copy your solution to the last exercise ZBC401_##_SPLIT_ITAB or the corresponding model solution SAPBC401_TABS_SPLIT_ITAB and give it the new name ZBC401_##_TABKIND. Ensure that the function module BC401_GET_SEP_STRING creates a character string containing duplicate data records. For this, assign the parameter im_unique the value space. Test your program. 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. Display the contents of both internal tables with the flight data.
TAW10 3-40

2-2

2-3

2-4
SAP AG

Exercise 3 - Optional
Unit: Using Internal Tables Topic: Processing Data Using Internal Tables
At the conclusion of these exercises, you will be able to: Select the appropriate types of internal table Process data using internal tables Extend your program so that it displays the flight data sorted by the flight date. The data is to be displayed in different colors, according to a key date selected by the user. If desired, the data is to be displayed using the SAP Grid Control. Program: Template: ZBC401_##_PROCESS_DATA SAPBC401_TABS_TABKIND SAPBC401_TABS_PROCESS_DATA

Model solution:

## is your two-digit group number 3-1 Copy your solution to the last exercise ZBC401_##_TABKIND or the corresponding model solution SAPBC401_TABS_TABKIND and give it the new name ZBC401_##_PROCESS_DATA. 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. Make sure that the data is first displayed sorted by flight date. 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. Display flights that occurred between todays data and the key date with the background color col_total.

3-2

3-3 3-4

SAP AG

TAW10

3-41

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 The training course BC412: ABAP Dialog Programming with EnjoySAP Controls 3-5-2 Find out about the types of the two internal tables that can/must be transferred to the function module as a parameter. Define two corresponding internal tables and an appropriate work area in your program (suggested names it_col_flights, it_col_doubles, and wa_col_flight). 3-5-3 The line type of the internal table that you must/can transfer contains a column COLOR, in which you can set the color values col_negative, col_total, col_positive, and col_background for every single line. Copy the contents of the tables it_flights and it_doubles to the internal tables it_col_flights and it_col_doubles respectively. Use two loops to do this, and to fill the COLOR column. it_flights: Logical condition fldate < sy-datum fldate BETWEEN sydatum AND p_date fldate > p_date Color value col_negative col_total col_positive

Always use col_background to display it_doubles.


SAP AG TAW10 3-42

Using Internal Tables Solution 1


Unit: Using Internal Tables Topic: Single-Column Tables of the Type string

REPORT

sapbc401_tabs_split_itab.

TYPES: BEGIN OF st_flight_c, mandt(3) carrid(3) connid(4) fldate(8) price(20) currency(5) planetype(10) seatsmax(10) seatsocc(10) TYPE c, TYPE c, TYPE n, TYPE n, TYPE c, TYPE c, TYPE c, TYPE n, 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) connid(4) fldate price(9) currency(5) TYPE c, TYPE n, TYPE d, TYPE p DECIMALS 2, TYPE c,

planetype(10) TYPE c, seatsmax seatsocc TYPE i, TYPE i,

END OF st_flight.

CONSTANTS c_number TYPE i VALUE 30.

SAP AG

TAW10

3-43

DATA: datastring set_string TYPE string, TYPE string,

wa_flight_c TYPE st_flight_c, wa_flight 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 * * * IM_TABLE_NAME IM_SEPARATOR IM_UNIQUE IMPORTING ex_string EXCEPTIONS no_data OTHERS = 1 = 2. = datastring = c_number = 'SFLIGHT' = '#' = 'X'

IF sy-subrc <> 0. MESSAGE a038(bc401). ENDIF.

SHIFT datastring BY 2 PLACES IN CHARACTER MODE. FIND '##' IN datastring. IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF.

SPLIT datastring AT '##' INTO TABLE it_sets.

LOOP AT it_sets INTO set_string. SAP AG TAW10 3-44

SPLIT set_string AT '#' INTO wa_flight_c-mandt 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.

MOVE-CORRESPONDING wa_flight_c TO 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.

SAP AG

TAW10

3-45

Solution 2 - Optional
Unit: Using Internal Tables Topic: Table Types

REPORT

sapbc401_tabs_tabkind.

TYPES: BEGIN OF st_flight_c, mandt(3) carrid(3) connid(4) fldate(8) price(20) currency(5) planetype(10) seatsmax(10) seatsocc(10) TYPE c, TYPE c, TYPE n, TYPE n, TYPE c, TYPE c, TYPE c, TYPE n, 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) connid(4) fldate price(9) currency(5) TYPE c, TYPE n, TYPE d, TYPE p DECIMALS 2, TYPE c,

planetype(10) TYPE c, seatsmax seatsocc TYPE i, TYPE i,

END OF st_flight.

CONSTANTS c_number TYPE i VALUE 30.

SAP AG

TAW10

3-46

DATA: datastring set_string TYPE string, TYPE string,

wa_flight_c TYPE st_flight_c, wa_flight 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 * * IM_TABLE_NAME IM_SEPARATOR IM_UNIQUE IMPORTING ex_string EXCEPTIONS no_data OTHERS = 1 = 2. = datastring = c_number = 'SFLIGHT' = '#' = space

IF sy-subrc <> 0. MESSAGE a038(bc401). ENDIF.

SAP AG

TAW10

3-47

SHIFT datastring BY 2 PLACES IN CHARACTER MODE. FIND '##' IN datastring. IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF.

SPLIT datastring AT '##' INTO TABLE it_sets.

LOOP AT it_sets INTO set_string.

SPLIT set_string AT '#' INTO wa_flight_c-mandt 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.

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: *********

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, SAP AG TAW10 3-48

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.

SAP AG

TAW10

3-49

Solution 3 - Optional
Unit: Using Internal Tables Topic: Processing Data Using Internal Tables

REPORT sapbc401_tabs_process_data.

TYPE-POOLS col.

TYPES: BEGIN OF st_flight_c, mandt(3) carrid(3) connid(4) fldate(8) price(20) currency(5) planetype(10) seatsmax(10) seatsocc(10) TYPE c, TYPE c, TYPE n, TYPE n, TYPE c, TYPE c, TYPE c, TYPE n, 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) connid(4) fldate price(9) currency(5) TYPE c, TYPE n, TYPE d, TYPE p DECIMALS 2, TYPE c,

planetype(10) TYPE c, seatsmax seatsocc TYPE i, TYPE i,

END OF st_flight.

SAP AG

TAW10

3-50

CONSTANTS c_number TYPE i VALUE 30.

DATA: datastring set_string TYPE string, TYPE string,

wa_flight_c TYPE st_flight_c, wa_flight 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,

it_col_flights TYPE bc401_t_flights_color, it_col_doubles LIKE it_col_flights, wa_col_flight LIKE LINE OF it_col_flights.

PARAMETERS: pa_date LIKE sy-datum, pa_alv AS CHECKBOX DEFAULT 'X'.

LOAD-OF-PROGRAM. pa_date = sy-datum + 30.

AT SELECTION-SCREEN. IF pa_date < sy-datum. MESSAGE e085(bc401). ENDIF. " date in the past

SAP AG

TAW10

3-51

START-OF-SELECTION.

CALL FUNCTION 'BC401_GET_SEP_STRING' EXPORTING im_number * * IM_TABLE_NAME IM_SEPARATOR im_unique IMPORTING ex_string EXCEPTIONS no_data OTHERS = 1 = 2. = datastring = c_number = 'SFLIGHT' = '#' = space

IF sy-subrc <> 0. MESSAGE a038(bc401). ENDIF.

SHIFT datastring BY 2 PLACES IN CHARACTER MODE. FIND '##' IN datastring. IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF.

SPLIT datastring AT '##' INTO TABLE it_sets.

LOOP AT it_sets INTO set_string.

SPLIT set_string AT '#' INTO wa_flight_c-mandt 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.

SAP AG

TAW10

3-52

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. ENDLOOP.

CALL FUNCTION 'BC401_ALV_LIST_OUTPUT' EXPORTING it_list1 it_list2 EXCEPTIONS control_error = 1 OTHERS IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF. SAP AG TAW10 3-53 = 2. = it_col_flights = it_col_doubles

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.

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.

SAP AG

TAW10

3-54

Introduction to Object-Oriented Programming

Contents:
l Procedural programming l Object-oriented programming l Aims of the ABAP Objects programming language

SAP AG 2002

SAP AG

TAW10

4-1

Introduction to Object-Oriented Programming: Unit Objectives

At the conclusion of this unit, you will be able to: l Name the most significant differences between procedural and object-oriented programming l State the aims behind developing the ABAP Objects programming language

SAP AG 2002

SAP AG

TAW10

4-2

History of Programming Languages

Machine language Assembler

C++

ABAP

Java

ABAP Objects

SAP AG 2002

n n

Before ABAP, SAP used a macro assembler. ABAP was created with the intention of improving reporting. ABAP developed almost independently as an in-house programming language, although it was influenced by other programming languages, for example, COBOL and PASCAL. ABAP Objects is a true extension of ABAP. ABAP Objects unites the most promising aspects of other object-oriented programming languages, such as Java, C++, and Smalltalk.

SAP AG

TAW10

4-3

Introduction: Programming Models (1)

Procedural programming Procedural programming Object-oriented programming Object-oriented programming

SAP AG 2002

SAP AG

TAW10

4-4

Characteristics of Procedural Programming

Data

Data Data

Data

Characteristics: l Separation of functions and data Possibility of encapsulating functions using modularization Direct access to data possible visibility? l l

Data Data

Function Function

Function Function

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.

SAP AG

TAW10

4-5

Typical ABAP Program

REPORT ZABAP_DEMO. REPORT ZABAP_DEMO. *---------------------*---------------------TYPES: ... TYPES: DATA: ... DATA: ... ... PERFORM form1 ... PERFORM form1 ... CALL FUNCTION 'FB1' CALL FUNCTION 'FB1' ... ... CALL FUNCTION 'FB2' CALL FUNCTION 'FB2' ... ... *---------------------*---------------------FORM f1 ... FORM f1 ... ... ... ENDFORM. ENDFORM.

l Type definitions l Data declarations

l Main program Calling subroutines Calling function modules

l Definition of subroutines

SAP AG 2002

n n

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.

SAP AG

TAW10

4-6

ABAP Main Memory and Function Groups


Internal session Global data objects in main program 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

n n n

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.

SAP AG

TAW10

4-7

Function Group Example

FUNCTION-POOL s_vehicle. FUNCTION-POOL s_vehicle. * speed is a global variable * speed is a global variable * used in the funtion-pool * used in the DATA: speed TYPE I. DATA: speed TYPE I. ... ... FUNCTION INC_SPEED. FUNCTION INC_SPEED. ... ... ADD imp_speed TO speed. ENDFUNCTION. ENDFUNCTION. FUNCTION DEC_SPEED. FUNCTION DEC_SPEED. ... ... SUBTRACT IMP_SPEED from speed. ENDFUNCTION. ENDFUNCTION. FUNCTION GET_SPEED. FUNCTION GET_SPEED. exp_speed = speed. exp_speed ENDFUNCTION. ENDFUNCTION. ... ...
SAP AG 2002

Function group with functions for controlling the speed of a car

S_VEHICLE speed
inc_speed dec_speed get_speed stop

n n

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.

SAP AG

TAW10

4-8

Use of Function Group

REPORT zvehicledemo. REPORT zvehicledemo. TYPES: ... TYPES: DATA: wa_car TYPE ... DATA: wa_car TYPE ... * no direct access to speed * no direct access to speed

Main program that uses function modules of this function group

S_VEHICLE * use functions of pool * use functions of pool CALL FUNCTION 'INC_SPEED' CALL ... ... CALL FUNCTION 'GET_SPEED' CALL ... ... speed
inc_speed dec_speed get_speed stop

CALL FUNCTION 'STOP' CALL ... ...

SAP AG 2002

The main program cannot access speed directly.

SAP AG

TAW10

4-9

Several Instances of One Function Group

S_VEHICLE speed
inc_speed dec_speed get_speed stop

Displaying a number of vehicles and their speed is only possible with additional administration

SAP AG 2002

If the main program is to work with several vehicles, this is not possible without extra programming and administration effort.

SAP AG

TAW10

4-10

Instantiation and Object-Oriented Languages

speed speed speed speed

Multiple instances (objects) of the same blueprint (type or class) are a fundamental attribute of object-oriented languages

SAP AG 2002

The ability to create multiple instances of a "class", such as a vehicle, is one of the central attributes of object-oriented languages.

SAP AG

TAW10

4-11

Introduction: Programming Models (2)

Procedural programming Procedural programming Object-oriented programming Object-oriented programming

SAP AG 2002

SAP AG

TAW10

4-12

Programming Models

Data and functions

Object model as abstraction of real world Real world


Functions

Data

Data

Data

Data Data

Data

Functions Functions

Functions Data Function Function Functions Functions

Function Function Function Function Function Function

Function Function Function Function Function Function Function Function Data

Functions Functions Functions

SAP AG 2002

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.

SAP AG

TAW10

4-13

Characteristics of the Object-Oriented Approach

l
Real world

Objects are an abstraction of the real world Processes can be implemented realistically Objects are units made up of data and the functions belonging to that data Improves software structure and consistency in the development process Maintenance requirements are reduced Modeler, end user, and developer are all included in analysis and design process

l l l l l

SAP AG 2002

n n

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

SAP AG

TAW10

4-14

Technical Implementation of the Object-Oriented Approach


l Encapsulation of data and functions l Polymorphism for support of generic programming l Inheritance
Functions Data Data Functions

Code 2 display_data Code 3

Code 1

Superclass

Code 4

Subclass 1

Subclass 2

l Improved structuring and consistency in the software development process

SAP AG 2002

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.

SAP AG

TAW10

4-15

Client/Server Behavior

l Objects behave towards each other just like client/server systems l Objects normally adopt both roles l Responsibilities must be specified between the objects

Methods Data Data

CALL METHOD server->do_it

Methods

call_it

do_it

Data

Client
SAP AG 2002

Server

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.

n n

SAP AG

TAW10

4-16

Compatibility and Design Aims


Compatibility: l
DATA: counter TYPE i, DATA: counter TYPE i, wa type KNA1. wa type KNA1. ... ... CLASS lcl_car DEFINITION. CLASS lcl_car DEFINITION. ... ... ENDCLASS. ENDCLASS. *--- main program --------*--- main program ---------

* ABAP Objects Programm * ABAP Programm

ABAP Objects is a true, compatible extension of ABAP ABAP Objects statements can be used in procedural ABAP programs Objects (classes) themselves contain classic ABAP statements

Design aims were:


CREATE OBJECT ... CREATE OBJECT ... counter = counter + 1. counter = counter + 1. MOVE wa TO ... MOVE wa

l l l

As simple as possible Only object-oriented concepts that have proved useful Increased use of type checks

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.

SAP AG

TAW10

4-17

ABAP Main Memory and Encapsulation


Internal session Global data objects
Modularization units

l Modularization units for encapsulating functions l Working with global data of the main program

Internal session session Global data objects


Functions Data

Data and business functions are encapsulated in objects

Functions Data

SAP AG 2002

n n

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.

SAP AG

TAW10

4-18

The Software Development Process

Requirement, idea
Already specified for the purposes of this course

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.

SAP AG

TAW10

4-19

Introduction to Object-Oriented Programming: Summary

You are now able to: l Name the most significant differences between procedural and object-oriented programming l State the aims behind developing the ABAP Objects programming language

SAP AG 2002

SAP AG

TAW10

4-20

Analysis and Design

Contents:
l Classification of objects l UML l Class diagrams l Sequence diagrams

SAP AG 2002

SAP AG

TAW10

5-1

Analysis and Design: Unit Objectives

At the conclusion of this unit, you will be able to: l List some important diagram types in UML l Create a class diagram l Create a sequence diagram

SAP AG 2002

SAP AG

TAW10

5-2

Analysis and Design (1)

Classification Classification UML -- the modeling standard UML the modeling standard

SAP AG 2002

SAP AG

TAW10

5-3

Classification of Objects

Real world

lcl_vehicle

lcl_people

Class creation / modeling


SAP AG 2002

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.

SAP AG

TAW10

5-4

Different Abstractions of a Class

Car enthusiast

Scrap merchant

Price
price

Make
make

Weight
weight

lcl_vehicle
- make - ... - price - equipping - color

Equipping
equipping

Type
model

Doors
doors

lcl_vehicle Scrap value


scrapvalue - make - ... - weight - scrapvalue

Color
color

Wheels
wheels

PS

SAP AG 2002

n n n

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.

SAP AG

TAW10

5-5

Representation of a Class

Class name

lcl_vehicle
make modell

Attributes

... price color set_make

Optional, does not have to be Assoziationsme specified

Methods
(functions)

display_attributes increase_speed ...

SAP AG 2002

n n n

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 obje ct. 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.

SAP AG

TAW10

5-6

Classes and Objects

Class: l l General description of objects (blueprint) Specifies status data (attributes) and behavior (methods)
...

Represented in course by:

lcl_vehicle
or
...

lcl_vehicle

Object (instance): l Representation of real world l Specific instance of a class


(5) lcl_vehicle

or

SAP AG 2002

n n n

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.

SAP AG

TAW10

5-7

Analysis and Design (2)

Classification Classification UML -- the modeling standard UML the modeling standard

SAP AG 2002

SAP AG

TAW10

5-8

Modeling with UML

l UML stands for Unified Modeling Language l It is a global standard l It is a language and form of notation for the specification, construction, visualization, and documentation of models for software systems
n

Diagram types:

w w w w w

Class diagram Behavior diagram, such as a sequence diagram Component diagram Distribution diagram ...

SAP AG 2002

n n n n n

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 obje ct-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.

SAP AG

TAW10

5-9

Example of a Class Diagram

lcl_rental
1

0..*

lcl_booking

0..* 1

lcl_customer

1..*

lcl_vehicle

1..*

lcl_wheel

lcl_car

lcl_truck

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.

SAP AG

TAW10

5-10

Association

A customer can rent several cars

A booking refers to a customer

lcl_booking

0..*

books

lcl_customer

Common cardinalities
* or 0..* 1 1..* 0..1 Many Exactly one One or more Zero or one

Association name

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.

SAP AG

TAW10

5-11

Aggregation and Composition

Aggregation is a special case of association, a whole-part relationship


1

Aggregation symbol

lcl_vehicle

0..*

lcl_wheel

Composition is a special case of aggregation, an existence-dependent whole-part relationship

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.

SAP AG

TAW10

5-12

Generalization and Specialization

lcl_vehicle
Generalization Generalization
5-13

Inheritance arrow

lcl_car or lcl_vehicle

lcl_truck

lcl_car
SAP AG 2002

lcl_truck

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.

SAP AG

TAW10

Specialization

Specialization

Sequence Diagrams: Example

lcl_driver

lcl_car

1:Method (parameter) Time Process description (optional) Return value

Life line of object

Control focus

SAP AG 2002

n n n

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.

SAP AG

TAW10

5-14

Sequence Diagram: Delegation

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

n n

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.

SAP AG

TAW10

5-15

Analysis and Design: Summary

You are now able to: l List some diagram types in UML l Create a class diagram l Create a sequence diagram

SAP AG 2002

SAP AG

TAW10

5-16

Analysis and Design Exercises


Unit: Analysis and Design Topic: UML Class Diagrams
At the conclusion of these exercises, you will be able to: Create a UML class diagram

An airline needs to manage its airplanes.

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.

SAP AG

TAW10

5-17

Analysis and Design Solutions


Unit: Analysis and Design Topic: UML Class Diagrams

SAP AG

TAW10

5-18

Principles of Object-Oriented Programming

Contents:
l Classes l Objects l Attributes l Methods l Visibility/encapsulation l Instantiation l Constructor l Garbage collector

SAP AG 2002

SAP AG

TAW10

6-1

Principles of Object-Oriented Programming: Unit Objectives

At the conclusion of this unit, you will be able to: l Create classes l Create objects l Call methods l Explain how the garbage collector works

SAP AG 2002

SAP AG

TAW10

6-2

Principles (1)

Classes, attributes, and methods Classes, attributes, and methods Objects, instances of classes Objects, instances Accessing attributes and methods Accessing attributes methods The constructor The constructor Additional principles Additional

SAP AG 2002

SAP AG

TAW10

6-3

Example of a Class

lcl_vehicle
Public components
get_make set_make

Represented in course by

Private components
make model

Methods: Implementation Public access Interface Normally methods, events

Private access Encapsulation Normally attributes

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.

SAP AG

TAW10

6-4

Defining Classes

ABAP code
CLASS lcl_vehicle DEFINITION.

lcl_vehicle
Public components Private components

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.


Method
implementation

ENDCLASS.

SAP AG 2002

n n

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.

SAP AG

TAW10

6-5

Attributes

l Attributes can have any kind of data type: l C, N, I, P, ..., STRING l Dictionary types l User-defined types l TYPE REF TO defines a reference to an object, in this case r_car
Public

(5) lcl_car
Private make TYPE STRING, ... r_motor TYPE REF TO ...

(3) lcl_rental

r_car

SAP AG 2002

n n

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) - ...

SAP AG

TAW10

6-6

Attributes, Types, and Constants: Syntax

CLASS <classname> DEFINITION. ... TYPES: <normale Typdefinition>. CONSTANTS: constant TYPE <type> VALUE <value>. DATA: variable1 variable2 variable3 variable4 variable5 variable6 variable7 TYPE TYPE LIKE TYPE TYPE TYPE TYPE <type>, <ddic_type>, variable1, <type> VALUE <value>, <type> READ-ONLY, REF TO <classname>, REF TO <interface>.

CLASS-DATA: only_once TYPE ... . ENDCLASS.

SAP AG 2002

n n n n

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.

SAP AG

TAW10

6-7

Attributes and Visibility

CLASS lcl_vehicle DEFINITION.

l Public attributes
n

PUBLIC SECTION. DATA: make TYPE string. PRIVATE SECTION. ENDCLASS.

Can be viewed and changed by all users and in all methods Direct access

CLASS lcl_vehicle DEFINITION.

l Private attributes
n

PUBLIC SECTION.
...

Can only be viewed and changed from within the class No direct access from outside the class

PRIVATE SECTION. DATA: make ENDCLASS.

TYPE string.

SAP AG 2002

n n n n

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.

SAP AG

TAW10

6-8

Accessing Private Attributes

Client

(5) lcl_vehicle
Public Private
make set_make get_make

r_vehicle

...

SAP AG 2002

n n

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.

SAP AG

TAW10

6-9

Instance Attributes and Static Attributes (1)

l Instance attributes
n n

CLASS lcl_vehicle DEFINITION. PUBLIC SECTION.


...

One per instance Statement: DATA

PRIVATE SECTION. DATA: make


...

TYPE string,

l Static attributes
n n n

Only one per class Statement: CLASS-DATA Also known as class attributes

CLASS-DATA: n_o_vehicles TYPE i. ENDCLASS.

SAP AG 2002

n n

n n

There are two kinds of attributes: - Static attributes - Instance attributes Instance attributes are attributes that exist separately for each object. Instance attributes are defined using the ABAP keyword DATA. Static attributes exist only once for each class and are visible for all (runtime) instances in that class. Static attributes usually contain information that applies to all instances, such as: - Data that is the same in all instances - Administrative information about the instances in that class (for example, counters, ...) Static attributes are defined using the CLASS-DATA keyword. You may come across the expression "class attributes" in documentation, however, the official term in ABAP Objects (as in C++, Java) is "static" attributes.

SAP AG

TAW10

6-10

Instance Attributes and Static Attributes (2)

Internal session Internal session Global data objects n_o_vehicles


Static attributes attributes
(1) lcl_vehicle

Static attributes only exist once

r_vehicle1 r_vehicle2
(3) lcl_vehicle

(2) lcl _vehicle

Instances / objects ...

r_vehicle3 ...

SAP AG 2002

n n

The graphic shows the static attribute n_o_vehicles. It exists only once, regardless of how many instances there are of lcl_vehicle. Therefore, you can say that instances share their common attributes.

SAP AG

TAW10

6-11

Methods: Syntax

Methods can have CLASS <classname> DEFINITION. a signature ... METHODS: <method_name> [ IMPORTING <im_var> TYPE <type> EXPORTING <ex_var> TYPE <type> CHANGING <ch_var> TYPE <type> RETURNING VALUE(<re_var>) TYPE <type> EXCEPTIONS <exception> RAISING <class_exception> ]. ENDCLASS. CLASS <classname> IMPLEMENTATION. METHOD <method_name>. ... ENDMETHOD. ENDCLASS.

Methods contain the source code, and hence define the behavior of an object

SAP AG 2002

n n n

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.

SAP AG

TAW10

6-12

Accessing Private Methods

Client

(5) lcl_vehicle
Public Private
make
...

r_vehicle

... set_make

init_make

SAP AG 2002

n n n

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.

SAP AG

TAW10

6-13

Methods and Visibility


CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. METHODS: set_make importing im_make TYPE string. PRIVATE SECTION. METHODS: init_make. DATA: make TYPE string. ENDCLASS. CLASS lcl_vehicle IMPLEMENTATION. METHOD init_make. make = 'no make'. ENDMETHOD. METHOD set_make. IF im_make IS INITIAL. * Calling init_make ... ELSE. make = im_make. ENDIF. ENDMETHOD. ENDCLASS.

l Public methods
n

Can be called from anywhere

l Private methods
n

Can only be called within the class

SAP AG 2002

In this example, init_make is a private method that is called by the public method set_make.

SAP AG

TAW10

6-14

Instance Methods and Static Methods

Rules:
l Instance methods
n

Can use both static and instance components in their implementation part Can be called using an instance

l Static methods
n

Can only use static components in their implementation part Can be called using the class

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".

SAP AG

TAW10

6-15

Instance Methods and Static Methods: Example

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. ENDCLASS. CLASS lcl_vehicle IMPLEMENTATION. ... METHOD get_count. ex_count = n_o_vehicles. ENDMETHOD ENDCLASS.

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.

SAP AG

TAW10

6-16

Summary and UML Notation

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

+ refers to public components - refers to private components _ static components are underlined

n n

n n

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.

SAP AG

TAW10

6-17

Principles (2)

Classes, attributes, and methods Classes, attributes, and methods Objects, instances of classes Objects, instances Accessing attributes and methods Accessing attributes methods The constructor The constructor Additional principles Additional

SAP AG 2002

SAP AG

TAW10

6-18

Creating Objects

Rules:

l l

Objects are created using the CREATE OBJECT statement Objects can only be created and addressed using reference variables

lcl_vehicle
- make - model - ser_no - n_o_vehicles + set_make - init_make + get_count ...

CREATE OBJECT r_vehicle

(5) lcl_vehicle
Public
set_make get_count ...

Private
make modell ser_no ...

... r_vehicle

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.

SAP AG

TAW10

6-19

Reference Variables

... CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. ... PRIVATE SECTION. ... ENDCLASS.

What do these reference variables point to?

CLASS lcl_vehicle IMPLEMENTATION. ... ENDCLASS. r_vehicle1 DATA: r_vehicle1 TYPE REF TO lcl_vehicle, r_vehicle2 TYPE REF TO lcl_vehilce. 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.

SAP AG

TAW10

6-20

Creating Objects: Syntax

DATA: r_vehicle1 TYPE REF TO lcl_vehicle, r_vehicle2 TYPE REF TO lcl_vehicle. CREATE OBJECT r_vehicle1. CREATE OBJECT r_vehicle2.
(3) lcl_vehicle
Public Private

r_vehicle1

r_vehicle2

(4) lcl_vehicle
Public Private

SAP AG 2002

n n

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.

SAP AG

TAW10

6-21

Garbage Collector

DATA: r_vehicle1 TYPE REF TO lcl_vehicle, r_vehicle2 TYPE REF TO lcl_vehicle. CREATE OBJECT r_vehicle1. CREATE OBJECT r_vehicle2. r_vehicle2 = r_vehicle1
(3) lcl_vehicle
Public Private

r_vehicle1

r_vehicle2

(4) lcl_vehicle
Public Private

SAP AG 2002

n n

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.

SAP AG

TAW10

6-22

Garbage Collector: Procedure

l l l

All independent references in the global main memory are checked. The references point to active objects, which are marked internally. References of class or instance attributes to other objects are followed. These objects are also marked. Objects that are not marked are deleted from the main memory.

Deleted
(2) lcl_object

(4) lcl_object

(5) lcl_object

SAP AG 2002

Independent references are references that have not been defined within a class.

SAP AG

TAW10

6-23

Buffering References

DATA: r_vehicle TYPE REF TO lcl_vehicle, itab TYPE TABLE OF REF TO lcl_vehicle. CREATE OBJECT r_vehicle. APPEND r_vehicle TO itab.

CREATE OBJECT r_vehicle. APPEND r_vehicle TO itab.

(2) lcl_object

(3) lcl_object

LOOP AT itab INTO r_vehicle. * work with the current instance ENDLOOP.
... SAP AG 2002

n n

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.

SAP AG

TAW10

6-24

Aggregation Example

(5) lcl_vehicle
Public Private
itab_wheels

(17) lcl_wheel

(25) lcl_wheel

(29) lcl_wheel

(36) lcl_wheel

SAP AG 2002

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.

SAP AG

TAW10

6-25

Principles (3)

Classes, attributes, and methods Classes, attributes, and methods Objects, instances of classes Objects, instances Accessing attributes and methods Accessing attributes methods The constructor The constructor Additional principles Additional

SAP AG 2002

SAP AG

TAW10

6-26

Calling Methods

Client
(5) lcl_vehicle
Public Private

r_vehicle->motor_on( )

motor_on

Method Reference Component selector

SAP AG 2002

n n

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.

SAP AG

TAW10

6-27

Calling Instance Methods: Syntax


Instance methods: CALL METHOD <instance>-><instance_method> EXPORTING <im_var> = <variable> IMPORTING <ex_var> = <variable> CHANGING <ch_var> = <variable> RECEIVING <re_var> = <variable> EXCEPTIONS <exception> = <nr>. Shortened notation as of 4.6C: (see online documentation) <instance> -><instance_method> ( [additions] )

DATA: r_vehicle TYPE REF TO lcl_vehicle. DATA: make_name TYPE STRING.


...

make_name = 'the make of the car'. CALL METHOD r_vehicle->set_make EXPORTING im_make = make_name. * other variant, since 6.1 available, see documentation! r_vehicle->set_make( make_name ) * now getting something back from method... r_vehicle->get_make( IMPORTING ex_make = make_name ).
SAP AG 2002

n n n n

n n

Instance methods are called using CALL METHOD <reference>-><instance_method>. Since SAP R/3 Basis Release 6.10, the shortened form is also supported; CALL METHOD is omitted. For further information, refer to the online documentation. Special case: When calling an instance method from within another instance method, you can omit the instance name. The method is automatically executed for the current object. For the method call set_make, you can omit the EXPORTING addition in the brackets. In this case, it is sufficient to set the actual parameter of the caller (in the example: make_name). However, if the method has two or more parameters in its interface, all actual and formal parameters within the brackets must have the EXPORTING addition. In the case of methods that return parameters to the caller, the IMPORTING addition must always be used and all actual and formal parameters must be listed. In method calls, multiple parameters are separated by spaces.

SAP AG

TAW10

6-28

Calling Static Methods: Syntax

Static methods:

CALL METHOD <classname>=><class_method> ( [additions] ) <classname>=><class_method> ( [additions] )

DATA: r_vehicle TYPE REF TO lcl_vehicle. DATA: make_name TYPE STRING, count TYPE I.
...

* get_count has one interface-parameter re_count CALL METHOD lcl_vehicle=>get_count( IMPORTING re_count = count ). * other variant, since 6.1 available, see documentation lcl_vehicle=>get_count( IMPORTING re_count = count ).

SAP AG 2002

n n n

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.

SAP AG

TAW10

6-29

Functional Methods

Example

a = b +
l When defining:
Only one RETURNING parameter

Functional method

Only IMPORTING parameters and exceptions are possible

l When calling:
a) RECEIVING parameters possible b) Various forms of direct call possible:

w w w

MOVE, CASE, LOOP Logical expressions (IF, ELSEIF, WHILE, CHECK, WAIT) Arithmetic expressions and bit expressions (COMPUTE), see example: a = b + c

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.

SAP AG

TAW10

6-30

Functional Methods: Example


CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. METHODS: get_average_fuel IMPORTING im_distance TYPE s_distance, im_fuel TYPE ty_fuel RETURNING VALUE(re_fuel) TYPE ty_fuel, ENDCLASS.

DATA: r_vehicle1 TYPE REF TO lcl_vehicle, r_vehicle2 TYPE REF TO lcl_vehicle, avg_fuel TYPE ty_fuel.
...

* example for short syntax in aritmet. operation avg_fuel = r_vehicle1->get_average_fuel( im_distance = 500 im_fuel = 50 ) + r_vehicle2->get_average_fuel( im_distance = 600 im_fuel = 60 ).

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.

SAP AG

TAW10

6-31

External Access to Public Attributes

CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. DATA: make TYPE string READ-ONLY. CLASS-DATA: n_o_vehicles TYPE i READ-ONLY.
...

just a demo just a demo

ENDCLASS.
...

(2) lcl_vehicle make


...

DATA: r_vehicle TYPE REF TO lcl_vehicle. DATA: make_name TYPE string, count TYPE i. START-OF-SELECTION. *--------------------------------------* main program, think of a client ! CREATE OBJECT r_vehicle. r_vehicle make_name = r_vehicle->make. count = lcl_vehicle=>n_o_vehicles.

only if public attr. only if public attr.

SAP AG 2002

There are different ways of accessing public attributes from outside the class: n You access static attributes using <classname>=><class_attribute> n You access instance attributes using <instance>-><instance_attribute> n => and -> are the component selectors

SAP AG

TAW10

6-32

Principles (4)

Classes, attributes, and methods Classes, attributes, and methods Objects, instances of classes Objects, instances Accessing attributes and methods Accessing attributes methods The constructor The constructor Additional principles Additional

SAP AG 2002

SAP AG

TAW10

6-33

Constructor

lcl_vehicle
l l l Special method for creating objects with defined initial state Only has IMPORTING parameters and EXCEPTIONS Is executed only once per instance
- make - model - n_o_vehicles ... + constructor ...

CREATE OBJECT

(3) lcl_vehicle
Public Private

METHODS constructor IMPORTING <im_parameter> EXCEPTIONS <exception>.

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.

SAP AG

TAW10

6-34

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.

Automatic constructor call

DATA r_vehicle TYPE REF TO lcl_vehicle. ... CREATE OBJECT r_vehicle EXPORTING im_make = 'Ferrari' im_model = 'F40'.
SAP AG 2002

Call from the main program

You need to implement the constructor when, for example: - You need to allocate (external) resources - You need to initialize attributes that cannot be covered by the VALUE addition to the DATA statement - You need to modify static attributes You cannot normally call the constructor explicitly.

SAP AG

TAW10

6-35

Preview: Static Constructor

CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. CLASS-METHODS: CLASS_CONSTRUCTOR. PRIVATE SECTION. CLASS-DATA: n_o_vehicles TYPE I. ENDCLASS. CLASS lcl_vehicle IMPLEMENTATION. METHOD CLASS_CONSTRUCTOR. ... ENDMETHOD. ... ENDCLASS.

l l l

Special static method Automatically called before the class is first accessed Only executed once per program

* Static Constructor is called before following statements: * demo 1 CREATE OBJECT r_vehicle. * demo 2
counter = lcl_vehicle=>n_o_vehicles. if attribute is public * demo 3 lcl_vehicle=>get_count( importing re_count = counter ).
SAP AG 2002

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.

SAP AG

TAW10

6-36

Principles (5)

Classes, attributes, and methods Classes, attributes, and methods Objects, instances of classes Objects, instances of classes Accessing attributes and methods Accessing attributes and methods The constructor The constructor Additional principles Additional

SAP AG 2002

SAP AG

TAW10

6-37

Namespace Within a Class

l The same namespace for


n n n n n n

lcl_vehicle
Public components Private components

Attributes Methods Events Types Constants ALIAS names

Method make

Attribute make

Method
implementation

l There is a local namespace within methods

SAP AG 2002

n n

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.

SAP AG

TAW10

6-38

The Reference Variable ME


CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. METHODS constructor IMPORTING im_make TYPE string im_modell TYPE string. PRIVATE SECTION. DATA make TYPE string. ... ENDCLASS. CLASS lcl_vehicle IMPLEMENTATION. METHOD constructor. just a demo DATA make TYPE string VALUE 'Benz'. CONCATENATE im_make make INTO ME->make. ENDMETHOD. METHOD DUMMY. * calling own methods from inside class * call method display_attributes( ) * with the short syntax variant: display_attributes( ). ENDMETHOD. ENDCLASS.
SAP AG 2002

lcl_vehicle
Public components Private components

Attribute make

Method
implementation

ME->make

n n

n n

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.

SAP AG

TAW10

6-39

Principles of Object-Oriented Programming: Unit Summary

You are now able to: l Create classes l Create objects l Call methods l Explain how the garbage collector works

SAP AG 2002

SAP AG

TAW10

6-40

Principles of Object-Oriented Programming Exercises


Unit: Principles of Object-Oriented Programming Topic: Creating a Class
At the conclusion of these exercises, you will be able to: Create a local class

An airline needs to manage its airplanes.

Model solution: SAPBC401_AIRS_MAIN_A SAPBC401_AIRS_A include program

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. Create the main program ZBC401_##_MAIN_AIRPLANE and the include program ZBC401_##_AIRPLANE the main program contains (##: group number). Create the class lcl_airplane in the include program. 1-3-1 This class has two private instance attributes: - name - planetype. The attribute for the airplane name should be of the type STRING. Define the attribute for the plane type using the table field saplane-planetype. 1-3-2 The class has a private static attribute: - n_o_airplanes. This attribute should be type I. 1-3-3 The class has a public instance method set_attributes to set the private instance attributes name and plane type. Enter two corresponding importing parameters for the declaration of the method in the definition part. The definition of these parameters should be analogous to the two attributes. 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-2

1-3

SAP AG

TAW10

6-41

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.)

SAP AG

TAW10

6-42

Exercises
Unit: Principles of Object-Oriented Programming Topic: Instantiating Objects
At the conclusion of these exercises, you will be able to: Instantiate objects

Model solution: SAPBC401_AIRS_MAIN_B SAPBC401_AIRS_A include program

2-1 Create a reference to the class lcl_airplane. 2-2 Define an internal table for buffering objects of the class lcl_airplane. The type of the internal table should therefore be REF TO lcl_airplane. 2-3 Create several objects of the class lcl_airplane and store them in the internal table. 2-4 Follow the program flow in the Debugger.

(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.)

SAP AG

TAW10

6-43

Exercises
Unit: Principles of Object-Oriented Programming Topic: Method Calls
At the conclusion of these exercises, you will be able to: Call instance methods and static methods

Model solution: SAPBC401_AIRS_MAIN_C SAPBC401_AIRS_C include program

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.

SAP AG

TAW10

6-44

Exercises
Unit: Principles of Object-Oriented Programming Topic: Constructor
At the conclusion of these exercises, you will be able to: Create a constructor for a class Create an object using the constructor Model solution: SAPBC401_AIRS_MAIN_D SAPBC401_AIRS_D include program

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 4-1-2 The constructor must have two importing parameters that fill the instance attributes name and planetype. The static attribute n_o_airplanes should have an ascending sequence of one in the constructor.

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.

SAP AG

TAW10

6-45

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

Model solution: SAPBC401_AIRS_MAIN_E SAPBC401_AIRS_E include program

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: 5-5-1 5-5-2 5-3-3 By calling it from the main program By calling it within the display_attributes method Which call was successful, and why?

SAP AG

TAW10

6-46

Principles of Object-Oriented Programming 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 *

*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION.

PUBLIC SECTION. "-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.

METHODS: set_attributes IMPORTING im_name TYPE string

im_planetype TYPE saplane-planetype, display_attributes.

CLASS-METHODS: display_n_o_airplanes.

PRIVATE SECTION. "---------------------------------DATA: name TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i. SAP AG TAW10 6-47

ENDCLASS.

*------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION *

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.

METHOD set_attributes. name planetype = im_name. = 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.

SAP AG

TAW10

6-48

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. *##############################

CREATE OBJECT r_plane. APPEND r_plane TO plane_list.

CREATE OBJECT r_plane. APPEND r_plane TO plane_list.

CREATE OBJECT r_plane. APPEND r_plane TO plane_list.

SAP AG

TAW10

6-49

Solutions
Unit: Principles of Object-Oriented Programming Topic: Method Calls
*&---------------------------------------------------------------------* *& Report SAPBC401_AIRS_MAIN_C *

*&---------------------------------------------------------------------* *& *& call method set_Attributes to initialize objects and visualize content of objects via display_attributes * *

*&---------------------------------------------------------------------*

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' ).

LOOP AT plane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP. SAP AG TAW10 6-50

lcl_airplane=>display_n_o_airplanes( ).

* calling the functional method get_n_o_airplanes * long syntax for functional call: * lcl_airplane=>get_n_o_airplanes( receiving re_count = count ). * short syntax for functional call: count = lcl_airplane=>get_n_o_airplanes( ). write: / 'Number of airplanes : ', count.

SAP AG

TAW10

6-51

*&---------------------------------------------------------------------* *& *& Include SAPBC401_AIRS_C * *

Develops functional static method get_n_o_airplanes

*&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION *

*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION.

PUBLIC SECTION. "-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.

METHODS: set_attributes IMPORTING im_name TYPE string

im_planetype TYPE saplane-planetype, display_attributes.

CLASS-METHODS: display_n_o_airplanes, get_n_o_airplanes returning VALUE(re_count) type I.

PRIVATE SECTION. "---------------------------------DATA: name TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i.

ENDCLASS.

*------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION *

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.

METHOD set_attributes. name planetype = im_name. = im_planetype.

n_o_airplanes = n_o_airplanes + 1. ENDMETHOD.

SAP AG

TAW10

6-52

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.

SAP AG

TAW10

6-53

Solutions
Unit: Principles of Object-Oriented Programming Topic: Constructor
*&---------------------------------------------------------------------* *& Report SAPBC401_AIRS_MAIN_d *

*&---------------------------------------------------------------------* *& call constructor of class lcl_airplane *

*&---------------------------------------------------------------------*

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( ).

SAP AG

TAW10

6-54

*&---------------------------------------------------------------------* *& Include SAPBC401_AIRS_d *

*&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION *

*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION.

PUBLIC SECTION. "-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.

METHODS: constructor IMPORTING im_name TYPE string

im_planetype TYPE saplane-planetype, display_attributes.

CLASS-METHODS: display_n_o_airplanes.

PRIVATE SECTION. "---------------------------------DATA: name TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i.

ENDCLASS.

*------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION *

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.

METHOD constructor. 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. SAP AG TAW10 6-55

METHOD display_n_o_airplanes. WRITE: /, / 'Number of airplanes: '(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. ENDMETHOD.

ENDCLASS.

SAP AG

TAW10

6-56

Solutions
Unit: Principles of Object-Oriented Programming Topic: Calling a Private Method
*&---------------------------------------------------------------------* *& Report *& SAPBC401_AIRS_MAIN_e * *

*&---------------------------------------------------------------------* *& *& inside display_attributes a private method is called to get further details on technical aspects of the planetype * *

*&---------------------------------------------------------------------* 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( ).

*&---------------------------------------------------------------------* *& Include SAPBC401_AIRS_e *

*&---------------------------------------------------------------------* SAP AG TAW10 6-57

*------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION *

*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION.

PUBLIC SECTION. "-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.

METHODS: constructor IMPORTING im_name TYPE string

im_planetype TYPE saplane-planetype, display_attributes.

CLASS-METHODS: display_n_o_airplanes.

PRIVATE SECTION. "---------------------------------METHODS: get_technical_attributes IMPORTING im_type EXPORTING ex_weight ex_tankcap type saplane-planetype TYPE s_plan_wei TYPE s_capacity.

DATA: name

TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS. "lcl_airplane DEFINITION

SAP AG

TAW10

6-58

*------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION *

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.

METHOD constructor. name planetype = im_name. = 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. "get_technical_attributes

ENDCLASS.

"lcl_airplane IMPLEMENTATION

SAP AG

TAW10

6-59

Inheritance

Contents:
l Generalization / specialization of classes

SAP AG 2002

SAP AG

TAW10

7-1

Inheritance: Unit Objectives

At the conclusion of this unit, you will be able to: l Define an inheritance relationship between classes l Redefine methods

SAP AG 2002

SAP AG

TAW10

7-2

Inheritance: UML Example


lcl_vehicle
- make - modell - ser_no - color - n_o_vehicles +constructor +display_attributes +get_count

"is a" relationship

lcl_car
- car_type - max_seats - accelertion +... +get_type
SAP AG 2002

lcl_truck
- max_cargo - n_o_tanks - n_o_wheels +... +get_cargo

lcl_bus
- max_passengers - lavatory - television +... +get_passengers

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.

SAP AG

TAW10

7-3

Multiple Inheritance?
Generalization
lcl_sub3

lcl_super1

lcl_super2

lcl_sub1

lcl_sub2

SAP AG 2002

n n

Inheritance should be used to implement generalization and specialization relationships. A superclass is a generalization of its subclasses. The subclass in turn is a specialization of its superclasses. The situation in which a class, for example lcl_sub2, inherits from two classes (lcl_super1 and lcl_super2) simultaneously, is known as multiple inheritance. However, this is not implemented in ABAP Objects. ABAP Objects only has single inheritance. You can, however, simulate multiple inheritance in ABAP Objects using interfaces (see the section on interfaces). Single inheritance does not mean that the inheritance tree only has one level. On the contrary, the direct superclass of one class can in turn be the subclass of a further superclass. In other words: The inheritance tree can have any number of levels, so that a class can inherit from several superclasses, as long as it only has one direct superclass. Inheritance is a "one-sided relationship": Subclasses know their direct superclasses, but (super)classes do not know their subclasses.

SAP AG

TAW10

Specialization
7-4

No multiple inheritance

Relationships Between Superclasses and Subclasses

l Common components only exist once in the superclass


n

lcl_super

New components in the superclass are automatically available in subclasses Amount of new coding is reduced ("programming by difference")

l Subclasses are extremely dependent on superclasses


n

"White Box Reuse": Subclass must possess detailed knowledge of the implementation of the superclass

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.

SAP AG

TAW10

7-5

Inheritance: Syntax

CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. METHODS: estimate_fuel IMPORTING im_distance TYPE s_distance RETURNING VALUE(re_fuel) TYPE ty_fuel. PRIVATE SECTION. DATA: make TYPE string,
...

ENDCLASS. CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle. PUBLIC SECTION. METHODS: get_cargo RETURNING VALUE(re_cargo) TYPE ty_cargo. PRIVATE SECTION. DATA: max_cargo TYPE ty_cargo. ENDCLASS.
SAP AG 2002

n n

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.

SAP AG

TAW10

7-6

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.
SAP AG 2002

Cannot change the interface

Always points to the superclass component

New implementation of method

n n n n

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.

SAP AG

TAW10

7-7

Inheritance and Redefining the Constructor

CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. METHODS: constructor IMPORTING im_make TYPE string. ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION. METHOD CONSTRUCTOR. make = im_make. ENDMETHOD. ENDCLASS.

CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle. PUBLIC SECTION. METHODS: constructor IMPORTING im_make TYPE string im_cargo TYPE ty_cargo. PRIVATE SECTION. DATA: max_cargo TYPE ty_cargo. ENDCLASS. Can change the interface CLASS lcl_truck IMPLEMENTATION. METHOD constructor. CALL METHOD super->constructor( im_make = im_make ). max_cargo = im_cargo. ENDMETHOD. ENDCLASS. Call constructor of immediate superclass
SAP AG 2002

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.

SAP AG

TAW10

7-8

Rules for Calling the Constructor

DATA: r_2 TYPE REF TO lcl_2, r_3 TYPE REF TO lcl_3. CREATE OBJECT r_2 EXPORTING im_a1 = 100. CREATE OBJECT r_3 EXPORTING im_a1 = 100 im_a2 = 1000.

lcl_1
a1 constructor (im_a1:i)

l Case 1: Class of instance to be created has constructor Fill its parameters l 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

n n

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.

SAP AG

TAW10

7-9

Inheritance and Visibility

CLASS lcl_vehicle DEFINITION.

Public components
n n

PUBLIC SECTION.

...

Visible to all Direct access PROTECTED SECTION. DATA tank TYPE REF TO lcl_tank. PRIVATE SECTION. DATA make TYPE string. ENDCLASS.

Protected components
n

Only visible within the class and its subclasses

Private components
n n

Only visible within the class No access from outside the class, not even from the subclass

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.

SAP AG

TAW10

7-10

Visibility of Protected Components

Can be addressed "from outside" for all clients Public

(5) lcl_bus
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 nonprivate methods.

SAP AG

TAW10

7-11

Rules for Redefining Methods


l Inherited methods can be redefined in subclasses
n n n n

Redefined methods must be re-implemented in subclasses The signature of redefined methods cannot be changed Static methods cannot be redefined In inheritance, static components are "shared": A class shares its non-private static attributes with all its subclasses

lcl_vehicles
estimate_fuel

lcl_car
estimate_fuel

lcl_truck
estimate_fuel

lcl_bus
estimate_fuel

The method is implemented in different ways


SAP AG 2002

n n

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.

SAP AG

TAW10

7-12

Redefining Methods: Example

lcl_bus
- max_passengers ...

lcl_truck
- 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.

SAP AG

TAW10

7-13

Inheritance: Unit Summary

You are now able to: l Define an inheritance relationship between classes l Redefine methods

SAP AG 2002

SAP AG

TAW10

7-14

Inheritance
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

Exercises

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.

SAP AG

TAW10

7-15

1-4

Switch to your main program. 1-4-1 Use the DATA statement to create a reference for each subclass (lcl_passenger_plane, lcl_cargo_plane). 1-4-2 Call the static method display_n_o_airplanes (before instantiating any objects). 1-4-3 Use the two references to create one instance each of the subclasses lcl_passenger_plane and lcl_cargo_plane. Decide for yourself how to fill the attributes. 1-4-4 Call the display_attributes method for both instances. 1-4-5 Call the static method display_n_o_airplanes a second time.

1-5

Follow the program flow in the Debugger, paying special attention to the call of display_attributes. Can the method get_technical_attributes be called directly from the redefined method display_atributes of the subclass? 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?

1-6

1-7

SAP AG

TAW10

7-16

Inheritance Solutions
Unit: Inheritance Topic: Creating Class Hierarchies

*&---------------------------------------------------------------------* *& Report SAPBC401_INHS_MAIN_a *

*&---------------------------------------------------------------------* *& *& the classes lcl_passenger_plane and lcl_cargo_plane are instantiated. Inheritance is shown * *

*&---------------------------------------------------------------------*

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. r_cargo->display_attributes( ). r_passenger->display_attributes( ). lcl_airplane=>display_n_o_airplanes( ). SAP AG TAW10 7-17

*&---------------------------------------------------------------------* *& Include SAPBC401_INHS_a *

*&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION *

*------------------------------------------------------------------* *...

*---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* 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

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION.

METHOD constructor. CALL METHOD super->constructor( im_name = im_name im_planetype = im_planetype ). max_cargo = im_cargo. ENDMETHOD. SAP AG "constructor TAW10 7-18

METHOD display_attributes. super->display_attributes( ). WRITE: / 'Max Cargo = ', max_cargo. ULINE. ENDMETHOD. ENDCLASS. "display_attributes "lcl_cargo_plane IMPLEMENTATION

SAP AG

TAW10

7-19

*---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* 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

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* 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. "display_attributes "lcl_passenger_plane IMPLEMENTATION

SAP AG

TAW10

7-20

Casting

Contents:
l Cast l Polymorphism

SAP AG 2002

SAP AG

TAW10

8-1

Casting: Unit Objectives

At the conclusion of this unit, you will be able to: l Use casts l Develop generic programs using polymorphism with inheritance

SAP AG 2002

SAP AG

TAW10

8-2

Casting (1)

Narrowing cast Narrowing Widening cast Widening Inheritance and polymorphism Inheritance and polymorphism

SAP AG 2002

SAP AG

TAW10

8-3

Principle of Narrowing Cast

DATA: r_vehicle TYPE REF TO lcl_vehicle, r_truck TYPE REF TO lcl_truck.

CREATE OBJECT r_truck. Public r_truck r_vehicle

(5) lcl_truck
Geerbt
get_make get_count

Redefiniert
* Narrowing Cast r_vehicle = r_truck display_attributes set_attributes estimate_fuel 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.

SAP AG

TAW10

8-4

Compatibility and Narrowing Cast

l l l

Instances from subclasses can be used in any context, in which the instances of the superclass appear The components inherited from the superclass can be addressed Generic access by the client is possible

DATA: r_vehicle r_truck level

TYPE REF TO lcl_vehicle, TYPE REF TO lcl_truck, TYPE ty_level.

* generic access to subclass services level = r_truck->estimate_fuel( 1000 ). * Narrowing Cast r_vehicle = r_truck. * Use of the subclass instance in the superclass context level = r_vehicle->estimate_fuel( 1000 ).

SAP AG 2002

n n

n n

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.

SAP AG

TAW10

8-5

Generic Access?

lcl_rental
The client

1..*

lcl_vehicles

lcl_truck
(1) lcl_rental
Public Private

lcl_bus

itab

(4) lcl_bus

?
(2) lcl_car

(5) lcl _truck

SAP AG 2002

A possible client (car rental company for example) wants to access the list of vehicles with identically-named 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.

SAP AG

TAW10

8-6

Preparations for Generic Access (1)

The client
Public

(1) lcl_rental
Private vehicle _list

2 lcl _bus

add_vehicle

3 lcl_truck

4 lcl_car

...

METHODS: add_vehicle IMPORTING im_vehicle TYPE REF TO lcl_vehicle.


...

SAP AG 2002

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.)

SAP AG

TAW10

8-7

Preparations for Generic Access (2)

CLASS lcl_rental DEFINITION. PUBLIC SECTION. METHODS add_vehicle IMPORTING im_vehicle TYPE REF TO lcl_vehicle. METHODS calc_estimated_fuel RETURNING VALUE(re_fuel) ... PROTECTED SECTION. DATA: vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS. CLASS lcl_rental IMPLEMENTATION. METHOD add_vehicle. APPEND im_vehicle TO vehicle_list. ENDMETHOD. METHOD calc_estimated_fuel. DATA: r_vehicle TYPE REF TO lcl_vehicle. LOOP AT vehicle_list INTO r_vehicle. re_fuel = re_fuel + r_vehicle->estimate_fuel( im_distance ) . ENDLOOP. ENDMETHOD. ENDCLASS.
SAP AG 2002

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.

SAP AG

TAW10

8-8

Polymorphism - Generic Access

METHOD calc_estimated_fuel. DATA: r_vehicle TYPE REF TO lcl_vehicle. LOOP AT vehicle_list into r_vehicle. re_fuel = re_fuel + r_vehicle->estimate_fuel( im_distance ) ENDLOOP. ENDMETHOD.

(5) lcl_truck
Public Geerbt / redefiniert

vehicle_list

Estimate_fuel

METHOD estimate_fuel. ... total_weight = max_passengers * average_weight + weight. re_fuel = total_weight * im_distance * factor. ENDMETHOD.

(2) lcl_bus
Public Geerbt / redefiniert Estimate_fuel

METHOD estimate_fuel. ... total_weight = max_cargo + weight. re_fuel = total_weight * im_distance * factor. ENDMETHOD.

SAP AG 2002

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.

SAP AG

TAW10

8-9

Static and Dynamic Types of References

l The static type of a reference variable


Is defined using TYPE REF TO

DATA: r_vehicle TYPE REF TO lcl_vehicle.

Remains constant throughout the program flow Defines which attributes and methods can be addressed

l The dynamic type of a reference variable


Is defined by assignment Can change during the program run Defines which code is to be executed for redefined methods
(5) lcl_truck Inherited / redefined Estimate_ fuel Estimate_fuel

(2) lcl_bus Inherited / redefined r_vehicle Estimate_ fuel Estimate_fuel

SAP AG 2002

n n

A reference variable always has two types, static and dynamic: The static type of a reference variable is determined by variable definition using TYPE REF TO. It cannot and does not change. It specifies which attributes and methods can be addressed The dynamic type of a reference variable is the type of the instance currently being referred to, it is therefore determined by assignment and can change during the program run. It defines what code is to be executed for redefined methods. In the example, the static type of the r_vehicle variable is always REF TO lcl_vehicle, but its dynamic type after the cast is REF TO lcl_bus or REF TO lcl_truck. In the Debugger, the reference me can be used to determine the dynamic type.

SAP AG

TAW10

8-10

Comparison to Procedural Programming


l l In object-oriented programming, you do not need to change the coding if you add use cases In a procedural program, you would have to adjust CASE constructions, for example:

* Procedural realisation of the example without polymorphism DATA: vehicle_list TYPE TABLE OF vehicle_list_type, vehicle TYPE vehicle_list_type, ... ... vehicle_list LOOP AT vehicle_list INTO vehicle. name category CASE vehicle-category. WHEN 'TRUCK'. truck1 PERFORM estimate_fuel_truck USING ... bus1 CHANGING fuel. bus2 WHEN 'BUS'. truck2 PERFORM estimate_fuel_bus USING ... CHANGING fuel. truck3 ENDCASE. ADD fuel TO needed_fuel. ENDLOOP.
SAP AG 2002

...

Using polymorphism makes generic programming easier. Instead of implementing a CASE or IF statement, you can have one access or call, which improves readability and does not need to be changed if you extend the program by adding further subclasses.

SAP AG

TAW10

8-11

Casting (2)

Narrowing cast Narrowing Widening cast Widening Inheritance and polymorphism Inheritance and polymorphism

SAP AG 2002

SAP AG

TAW10

8-12

Use of Widening Cast

2 lcl_bus

The client
Public

(1) lcl_rental
3 lcl_truck

Private vehicle_list
4 lcl _car

max_cargo = 30

get_max_cargo

3 lcl_truck

max_cargo = 50

METHOD get_max_cargo. DATA: r_vehicle TYPE REF TO lcl_vehicle. LOOP AT vehicle_list INTO r_vehicle. * Problem: is this really a truck ? * Determine the max cargo ENDLOOP. ENDMETHOD.
SAP AG 2002

Truck or other vehicle?

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.

SAP AG

TAW10

8-13

Widening Cast: Example

(2) lcl _bus

5 lcl_rental
get _max_cargo

(1) lcl_rental
vehicle_list (3) lcl_truck

max_cargo = 30
(4) lcl_car

(9) lcl_truck

METHOD get_max_cargo. DATA: r_vehicle TYPE REF TO lcl_vehicle, r_truck TYPE REF TO lcl_truck. LOOP AT vehicle_list INTO r_vehicle. TRY. r_truck ?= r_vehicle. * put max cargo in variable re_cargo...

max_cargo = 50

CATCH cx_sy_move_cast_error. react on that cast error

ENDTRY. ENDLOOP. ENDMETHOD.


SAP AG 2002

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.

SAP AG

TAW10

8-14

Casting (3)

Narrowing cast Narrowing Widening cast Widening Inheritance and polymorphism Inheritance and polymorphism

SAP AG 2002

SAP AG

TAW10

8-15

Semantics and Use with Inheritance

Rules:

l l l

Inherited components must behave in subclasses exactly as they do in superclasses for all users When you redefine a method its semantics must remain the same; you cannot change the signature Using inheritance: l Allows you to enhance classes using generalization/specialization and hence achieve better software structure l Provides possibility of polymorphic behavior, "generic programming"; CASE constructions no longer needed
n

Must not be used solely for "code inheritance"

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.

SAP AG

TAW10

8-16

Incorrect Use of Inheritance

Rules:

l Inheritance is often used incorrectly:


n n

To simply reuse code Instead of additional attributes/aggregation/role concepts


car
de sig n?

car_red
n

car_blue

The use of inheritance does not always correspond to expectations in the real world
change_width Superclass Rectangular change_height
de sig n?

Subclass square

SAP AG 2002

Using inheritance instead of attributes, or a misunderstanding of inheritance as an is-one relationship often leads to the following kind of design: the superclass car has the subclasses red car, green car, and so on. These subclasses all have an identical structure and identical behavior. Because an instance cannot change its class, in circumstances like the following, you should not use inheritance directly, but use a so-called role design pattern instead: The class employee has the subclasses full-time employee and part-time employee. What happens when a part-time employee becomes a full-time employee? A new full-time employee object would have to be instantiated and all the information copied from the part-time employee object. However, users who still have a reference to the part-time employee instance would then be working with a part-time employee object that logically does not exist anymore. The use of inheritance does not always correspond to expectations in the real world: For example, if the class square inherits from the class rectangle, the latter will have two separate methods for changing length or width, although the sides of the square actually need to be changed by the same measurement.

SAP AG

TAW10

8-17

Casting: Unit Summary

You are now able to: l Use casts l Develop generic programs using polymorphism with inheritance

SAP AG 2002

SAP AG

TAW10

8-18

Casting
Unit: Casting Topic: Polymorphism
At the conclusion of these exercises, you will be able to: Describe polymorphism and inheritance

Exercises

Use generic programming for inheritance relationships and implement polymorphic method calls Model solution: SAPBC401_CASS_MAIN_A SAPBC401_INHS_A include program

1-1

Extend your existing program ZBC401_##_MAIN_AIRPLANE or start with the model solution from the last chapters exercises. 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-2

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?

SAP AG

TAW10

8-19

Model solution: SAPBC401_CASS_MAIN_B SAPBC401_CASS_B include program Template: SAPBC401_CAST_B

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). Add the following public instance methods to the class lcl_carrier: 2-2-1 The first method is add_airplane, which adds planes to the list of planes airplane_list already defined in the class. The transfer parameter is a reference to the class lcl_airplane. Have a close look at the definition of the internal table airplane_list. 2-2-2 The second method is display_airplanes, which displays the planes from the list airplane_list. The display_attributes method from class lcl_airplane should be called at this point. 2-2-3 The third method is display_attributes, which displays the airline attributes. This includes the airline name and the list of planes (you can use icon_flight as an icon before the name).

2-2

2-3

Go back to your main program. 2-3-1 At the DATA statement, create a reference to the class lcl_carrier. 2-3-2 Comment out all statements affecting the internal table (or delete them). 2-3-3 Create an airline and fill the transfer parameters with data of your own choice. 2-3-4 Add the planes already created in the last exercise (passenger and cargo planes) to the list of planes airplane_list. To do this, call the method add_airplane of the class lcl_carrier. Create more planes and add them to the airplane list. 2-3-5 Display the airline attributes by calling the display_attributes method of the class lcl_carrier. 2-3-6 Question: Which code is executed when you execute display_attributes within display_airplanes.

SAP AG

TAW10

8-20

Casting Solutions
Unit: Casting Topic: Polymorphism

*&---------------------------------------------------------------------* *& Report *& SAPBC401_CASS_MAIN_a * *

*&---------------------------------------------------------------------* *& show casting operations ... *

*&---------------------------------------------------------------------*

REPORT

sapbc401_cass_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.

APPEND r_passenger TO plane_list.

CREATE OBJECT r_cargo EXPORTING im_name = 'US HErcules' im_planetype = '747-500' SAP AG TAW10 8-21

im_cargo = 533.

APPEND r_cargo TO plane_list.

LOOP AT plane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP.

lcl_airplane=>display_n_o_airplanes( ).

SAP AG

TAW10

8-22

*&---------------------------------------------------------------------* *& Report *& SAPBC401_CASS_MAIN_b * *

*&---------------------------------------------------------------------* *& carrier adds airplanes to its airplane_list --> polymorphism *

*&---------------------------------------------------------------------*

REPORT

sapbc401_cass_main_b.

INCLUDE <icon>. INCLUDE sapbc401_cass_b.

DATA: r_plane TYPE REF TO lcl_airplane, r_cargo TYPE REF TO lcl_cargo_plane, r_passenger TYPE REF TO lcl_passenger_plane, r_carrier type ref to lcl_carrier.

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 ).

r_carrier->add_airplane( r_cargo ).

***** show all airplanes inside carrier *************************** r_carrier->display_attributes( ). SAP AG TAW10 8-23

*---------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION

*---------------------------------------------------------------------* * Class definitions of ... lcl_airplane, cargo- and passenger_plane * ... * ...

*---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION

*---------------------------------------------------------------------* 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,

airplane_list type TABLE OF REF TO lcl_airplane. ENDCLASS.

*---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION

*---------------------------------------------------------------------* 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.

METHOD display_airplanes. SAP AG TAW10 8-24

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.

SAP AG

TAW10

8-25

Interfaces

Contents:
l Interfaces l Compound interfaces l Polymorphism

SAP AG 2002

SAP AG

TAW10

9-1

Interfaces: Unit Objectives

At the conclusion of this unit, you will be able to: l Define and implement interfaces l Develop generic programs using polymorphism with interfaces

SAP AG 2002

SAP AG

TAW10

9-2

Interfaces (1)

Interfaces: Principles Interfaces: Principles Working with interfaces Working with interfaces Preview: Compound interfaces Preview: Compound interfaces

SAP AG 2002

SAP AG

TAW10

9-3

Interfaces: Use

Service 1 Service 2 Service 3 ...

Interfaces

Shared services lcl_carrier lcl_hotel lcl_rental

lcl_airplane

lcl_vehicles

...
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.

SAP AG

TAW10

9-4

Interfaces: Services

Client uses

Interface

display_partner check_availability ...

Shared services lcl_carrier lcl_hotel lcl_rental

lcl_airplane

lcl_vehicles

...
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.

SAP AG

TAW10

9-5

Interface: UML Example

lcl_travel_agency
uses
<<Interface>> <<Interface>>

Client Client

It is possible to Implementation implement several mehrerer Interfaces interfaces mglich ! <<Interface>>

lif_partners
implements

lif_license
...

lcl_carrier

lcl_hotel

lcl_rental

lcl_airplane

lcl_vehicles

...
SAP AG 2002

...

...

...

n n

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.

SAP AG

TAW10

9-6

Defining and Implementing an Interface

Declaring the interface

INTERFACE lif_partners. METHODS: display_partner. ENDINTERFACE.

The server classes "make the interface public"

CLASS lcl_rental DEFINITION. PUBLIC SECTION. INTERFACES lif_partners. ENDCLASS.

Interfaces are implemented in classes

CLASS lcl_rental IMPLEMENTATION. METHOD lif_partners~display_partner. * just call existing method that fits display_attributes( ).
...

Interfaces do not have visibility sections

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>.
Changes to an interface usually invalidate all the classes implementing it.

SAP AG

TAW10

9-7

Interfaces: Features

Separation of external point of contact (interface) and implementation (class)


n n

The client defines the protocol, the server implements it "Black Box principle": Client only knows the interface, not the implementation Looser linkage between client and server
Code 2 Code 1 display_partner Code 3 Code 4

Polymorphism
n

Generic handling of objects of different classes

Abstraction
n

Interface as a generalization of the implementing class


super1 Interf.

Simulation of multiple inheritance


sub1 SAP AG 2002 sub2

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.

SAP AG

TAW10

9-8

Interfaces (2)

Interfaces: Principles Interfaces: Principles Working with interfaces Working with interfaces Preview: Compound interfaces Preview: Compound interfaces

SAP AG 2002

SAP AG

TAW10

9-9

Working with Interface Components

CLASS lcl_rental IMPLEMENTATION. ... METHOD lif_partners~display_partner. * special coding to display partners or * just calling existing method that fits display_attributes( ). ENDMETHOD. ENDCLASS.

lif_partners
display_partner check_availability ...

implements

DATA: r_vehicle TYPE REF TO lcl_vehicle.


...

lcl_rental
- name - vehicle_list + add_vehicle + display_attributes ...

CREATE OBJECT r_vehicle. * syntactically possible but not useful: r_vehicle->lif_partners~display_partner( ).

Interface resolution operator


SAP AG 2002

n n

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.

SAP AG

TAW10

9-10

Interface References: Narrowing Cast

DATA: r_rental TYPE REF TO lcl_rental, r_lif TYPE REF TO lif_partners.

CREATE OBJECT r_rental. Public r_rental r_lif

(1) lcl_rental
Private

Interface components
* Narrowing Cast r_lif = r_rental display_partner check_availability ...

r_lif
SAP AG 2002

n n

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 interfacereference.

SAP AG

TAW10

9-11

Using the Interface

(9) lcl_travel_agency
Public Private partner_list

2 lcl _hotel

add_partner

2 lcl_rental

2 lcl _carrier

...

METHODS: add_partner IMPORTING im_partner TYPE REF TO lif_partners.


...

SAP AG 2002

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.

SAP AG

TAW10

9-12

Polymorphism and Interfaces

METHOD display_agency_partners. DATA: r_partner TYPE REF TO lif_partners. LOOP AT partner_list INTO r_partner. r_partner->display_partner( ). ENDLOOP. ENDMETHOD.

(7) lcl _hotel

METHOD ...~display_partner. display_hotel_attributes( ). ENDMETHOD.


partner_list
(1) lcl_rental

...

METHOD ...~display_partner. display_rental_data( ). ... ENDMETHOD.

(6) lcl _carrier

METHOD ...~display_partner. display_attributes( ). ... ENDMETHOD.


SAP AG 2002

n n

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.

SAP AG

TAW10

9-13

Interface References: Widening Cast

2 lcl_hotel

5 lcl_rental
book_flight

3 lcl_travel_agency
partner_list 2 lcl_rental

2 lcl _carrier

METHOD book_flight. DATA: r_carrier TYPE REF TO lcl_carrier, r_partner TYPE REF TO lcl_partner. LOOP AT partner_list INTO r_partner. TRY. r_carrier ?= r_partner. * call method of lcl_carrier to book flight...

CATCH cx_sy_move_cast_error.
* react on that cast error ENDTRY. ENDLOOP. ENDMETHOD.
SAP AG 2002

n n

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.

SAP AG

TAW10

9-14

Interfaces (3)

Interfaces: Principles Interfaces: Principles Working with interfaces Working with interfaces Preview: Compound interfaces Preview: Compound interfaces

SAP AG 2002

SAP AG

TAW10

9-15

Compound Interfaces
Interface

lif_partners

?
lif_partners

book_room

lcl_hotel

lcl_carrier

lcl_rental

Problem: Extending interfaces

Solution: Compound interfaces

Interface

lif_room_booking

Interface Interface

lcl_hotel
SAP AG 2002

lcl_carrier

lcl_rental

n n

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.

SAP AG

TAW10

9-16

Compound Interfaces: Example


INTERFACE lif_partners. METHODS display_partner. ENDINTERFACE. INTERFACE lif_room_booking. INTERFACES lif_partners. METHODS book_room. ENDINTERFACE. CLASS lcl_hotel DEFINITION. PUBLIC SECTION. INTERFACES lif_room_booking. ENDCLASS. CLASS lcl_hotel IMPLEMENTATION. METHOD lif_partners~display_partner. ENDMETHOD. METHOD lif_room_booking~book_room. ENDMETHOD. ENDCLASS.

DATA: i_partner i_room_book


...

TYPE REF TO lif_partners, TYPE REF TO lif_room_booking,

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.


SAP AG 2002

Widening Cast

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.

SAP AG

TAW10

9-17

Interfaces: Unit Summary

You are now able to: l Define and implement interfaces l Develop generic programs using polymorphism with interfaces

SAP AG 2002

SAP AG

TAW10

9-18

Interfaces
Unit: Interfaces Topic: Defining Interfaces
At the conclusion of these exercises, you will be able to: Define and implement interfaces

Exercises

Model solution: SAPBC401_INTS_MAIN_A SAPBC401_VEHD_F include program SAPBC401_INTS_A include program

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. Copy the include program SAPBC401_VEHD_F to your own include program ZBC401_##_VEHICLE. As well as the classes lcl_rental, lcl_vehicle, lcl_truck, lcl_bus, the program also contains the interface lif_partners. Incorporate this include program into your main program. Add the types ty_fuel and ty_cargo (both TYPE P DECIMALS 2) to the main program. Pay attention to the position of the interface definition; you may have to change the order of the include programs or move the interface into the other include program. Familiarize yourself with the interface definition.

1-2

1-3

SAP AG

TAW10

9-19

1-4 1-5

Now implement the interface of your class lcl_carrier. 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.)

UML-Template for Exercise 1-1

SAP AG

TAW10

9-20

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. Copy the definition of the class lcl_travel_agency from the template SAPBC401_VEHT_B to your own include program. Then complete this new class. 2-2-1 The travel agency uses the public method add_partner to add business partners (that is car rental companies and airlines) to the internal table partner_list. 2-2-2 What are the types of the internal table and the interface parameter of add_partner? 2-2-3 The travel agency will use the method display_agency_partners to display the data of its business partners.

2-2

SAP AG

TAW10

9-21

2-3 2-4

Go back to your main program. Create an instance of the class lcl_travel_agency. 2-4-1 Use the add_partner method to add the travel agencys business partners to the internal table. 2-4-2 Use the display_agency_partners method to display the travel agencys business partners. 2-4-3 At which point does polymorphism take place? Follow this in the Debugger.

UML-Template for Exercise 2-1

SAP AG

TAW10

9-22

Interfaces
Unit: Interfaces Topic: Defining Interfaces

Solutions

*&---------------------------------------------------------------------* *& Report *& SAPBC401_INTS_MAIN_A * *

*&---------------------------------------------------------------------* *& include interface lif_partners and include file with lcl_vehicle.. *

*&---------------------------------------------------------------------*

REPORT

sapbc401_ints_main_a.

types ty_fuel type p decimals 2. types ty_cargo type p decimals 2.

INCLUDE <icon>. INCLUDE sapbc401_vehd_f. include sapbc401_ints_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, r_carrier type ref to lcl_carrier, r_agency type ref to lcl_travel_agency, r_rental type ref to lcl_rental, r_truck type ref to lcl_truck, r_bus type ref to lcl_bus.

START-OF-SELECTION. *##############################

***** Create Carrier ******************************************** create object r_carrier exporting im_name = 'Smile&Fly-Travel'.

***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING SAP AG TAW10 9-23

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 ).

r_carrier->add_airplane( r_cargo ).

***** show all airplanes inside carrier *************************** r_carrier->display_attributes( ).

******* create RENTAL ***************************************** CREATE OBJECT r_rental EXPORTING im_name = 'HAPPY CAR RENTAL'.

******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = 'MAN' im_cargo = 45. r_rental->add_vehicle( r_truck ). ******* create truck ***************************************** CREATE OBJECT r_bus EXPORTING im_make = 'Mercedes' im_passengers = 80. r_rental->add_vehicle( r_bus ). ******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = 'VOLVO' im_cargo = 48. r_rental->add_vehicle( r_truck ).

SAP AG

TAW10

9-24

*&---------------------------------------------------------------------* *& Include SAPBC401_INTS_a *

*&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION *

*------------------------------------------------------------------* ... *---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION

*---------------------------------------------------------------------* *---------------------------------------------------------------------* 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,

airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS. "lcl_carrier DEFINITION

*---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION

*---------------------------------------------------------------------* 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. "add_airplane

METHOD display_attributes. WRITE: icon_flight AS ICON, name . ULINE. ULINE. SAP AG TAW10 9-25

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. "get_name

ENDCLASS.

"lcl_carrier IMPLEMENTATION

SAP AG

TAW10

9-26

Solutions
Unit: Interfaces Topic: Using Interfaces
*&---------------------------------------------------------------------* *& Report *& SAPBC401_INTS_MAIN_B * *

*&---------------------------------------------------------------------* *& *& include interface lif_partners and include file with lcl_vehicle.. * the client (travel_agency) uses the interface... *

*&---------------------------------------------------------------------*

REPORT

sapbc401_ints_main_b.

types ty_fuel type p decimals 2. types ty_cargo type p decimals 2.

INCLUDE <icon>. INCLUDE sapbc401_vehd_g. include sapbc401_ints_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, r_carrier type ref to lcl_carrier, r_agency type ref to lcl_travel_agency, r_rental type ref to lcl_rental, r_truck type ref to lcl_truck, r_bus type ref to lcl_bus.

START-OF-SELECTION. *##############################

***** Create TRAVEL_AGENCY ************************************** CREATE OBJECT r_agency EXPORTING im_name = 'Fly&Smile Travel'.

***** Create CARRIER ******************************************** create object r_carrier exporting im_name = 'Smile&Fly-Travel'. SAP AG TAW10 9-27

***** 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 ). r_carrier->add_airplane( r_cargo ).

***** insert business-parnter of agency into partner_list*********** r_agency->add_partner( r_carrier ).

******* create RENTAL ***************************************** CREATE OBJECT r_rental EXPORTING im_name = 'HAPPY CAR RENTAL'.

******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = 'MAN' im_cargo = 45. r_rental->add_vehicle( r_truck ). ******* create truck ***************************************** CREATE OBJECT r_bus EXPORTING im_make = 'Mercedes' im_passengers = 80. r_rental->add_vehicle( r_bus ). ******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = 'VOLVO' im_cargo = 48. r_rental->add_vehicle( r_truck ).

***** insert business-partner of agency into partner_list*********** r_agency->add_partner( r_rental ).

******* show attributes of all partners of travel_agency ****** r_agency->display_agency_partners( ).

SAP AG

TAW10

9-28

*&---------------------------------------------------------------------* *& 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

*---------------------------------------------------------------------* 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 METHODS METHODS constructor IMPORTING im_make TYPE string. display_attributes. set_make IMPORTING im_make TYPE string. get_make EXPORTING ex_make TYPE string.

CLASS-METHODS get_count EXPORTING re_count TYPE i.

PRIVATE SECTION. "------------------DATA: make TYPE string.

METHODS

init_make.

CLASS-DATA:

n_o_vehicles TYPE i.

ENDCLASS.

"lcl_vehicle DEFINITION

*---------------------------------------------------------------------* * CLASS lcl_vehicle IMPLEMENTATION

*---------------------------------------------------------------------* CLASS lcl_vehicle IMPLEMENTATION. METHOD get_average_fuel. SAP AG TAW10 9-29

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 " me->init_make( ). also possible

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. "get_count

ENDCLASS.

"lcl_vehicle IMPLEMENTATION

*---------------------------------------------------------------------* * CLASS lcl_truck DEFINITION

*---------------------------------------------------------------------* CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.

PUBLIC SECTION. "------------------ SAP AG TAW10 9-30

METHODS:

constructor IMPORTING im_make TYPE string im_cargo TYPE ty_cargo.

METHODS METHODS

display_attributes REDEFINITION. get_cargo RETURNING value(re_cargo) TYPE ty_cargo.

PRIVATE SECTION. "------------------DATA: max_cargo TYPE ty_cargo.

ENDCLASS.

"lcl_vehicle DEFINITION

*---------------------------------------------------------------------* * CLASS lcl_truck IMPLEMENTATION

*---------------------------------------------------------------------* 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. "get_cargo

ENDCLASS.

"lcl_vehicle DEFINITION

*---------------------------------------------------------------------* * CLASS lcl_bus DEFINITION

*---------------------------------------------------------------------* CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle. SAP AG TAW10 9-31

PUBLIC SECTION. "------------------METHODS: constructor IMPORTING im_make TYPE string im_passengers TYPE i.

METHODS

display_attributes REDEFINITION.

PRIVATE SECTION. "------------------DATA: max_passengers TYPE i.

ENDCLASS.

"lcl_vehicle DEFINITION

*---------------------------------------------------------------------* * CLASS lcl_bus IMPLEMENTATION

*---------------------------------------------------------------------* 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. ENDCLASS. "display_attributes "lcl_vehicle DEFINITION 20 ' Passengers = ', max_passengers.

*---------------------------------------------------------------------* * CLASS lcl_rental DEFINITION

*---------------------------------------------------------------------* CLASS lcl_rental DEFINITION.

PUBLIC SECTION. "------------------METHODS: METHODS constructor IMPORTING im_name TYPE string. add_vehicle IMPORTING im_vehicle TYPE REF TO lcl_vehicle. SAP AG TAW10 9-32

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

*---------------------------------------------------------------------* CLASS lcl_rental IMPLEMENTATION. METHOD lif_partners~display_partner. display_attributes( ). ENDMETHOD. "lif_partners~display_partner

METHOD

constructor.

name = im_name. ENDMETHOD. "constructor

METHOD

add_vehicle.

APPEND im_vehicle TO vehicle_list. ENDMETHOD. "add_vehicle

METHOD

display_attributes.

DATA: r_vehicle TYPE REF TO lcl_vehicle. WRITE: / WRITE: icon_transport_proposal AS ICON, name. ' Here comes the vehicle list: '. ULINE. ULINE.

LOOP AT vehicle_list INTO r_vehicle. r_vehicle->display_attributes( ). ENDLOOP. ENDMETHOD. ENDCLASS. "display_attributes "lcl_rental IMPLEMENTATION

*---------------------------------------------------------------------* * CLASS lcl_travel_agency DEFINITION

*---------------------------------------------------------------------* CLASS lcl_travel_agency DEFINITION.

PUBLIC SECTION. "------------------METHODS: SAP AG constructor IMPORTING im_name TYPE string. TAW10 9-33

METHODS

add_partner IMPORTING im_partner TYPE REF TO lif_partners.

METHODS PRIVATE SECTION.

display_agency_partners.

"------------------DATA: name TYPE string, partner_list TYPE TABLE OF REF TO lif_partners. ENDCLASS. "lcl_travel_agency DEFINITION

*---------------------------------------------------------------------* * CLASS lcl_travel_agency IMPLEMENTATION

*---------------------------------------------------------------------* CLASS lcl_travel_agency IMPLEMENTATION. METHOD display_agency_partners. DATA: r_partner TYPE REF TO lif_partners. WRITE: icon_dependents AS ICON, name. WRITE: ' Here are the partners of the travel agency: '.ULINE.ULINE.

LOOP AT partner_list INTO r_partner. r_partner->display_partner( ). ENDLOOP. ENDMETHOD. "display_agency_partners

METHOD

constructor.

name = im_name. ENDMETHOD. "constructor

METHOD

add_partner.

APPEND im_partner TO partner_list. ENDMETHOD. ENDCLASS. "add_partner "lcl_travel_agency IMPLEMENTATION

SAP AG

TAW10

9-34

Events

Contents:

l Defining and triggering events l Registering and handling events

SAP AG 2002

SAP AG

TAW10

10-1

Events: Unit Objectives

At the conclusion of this unit, you will be able to: l Define and trigger events l Handle events l Register and deregister events l Receive a reference from the sender l Explain the conceptual differences between methods and events

SAP AG 2002

SAP AG

TAW10

10-2

Events: Overview

Receiver / handler
* main program CREATE OBJECT r_car EXPORTING
...

Car rental company

Car

Vehicle registration office

Sender
...

Event: vehicle_created
SAP AG 2002

n n

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.

SAP AG

TAW10

10-3

Features

l Looser linkage than for a method call


n n

Triggering object makes status change known Handler objects can show interest and react

l Different communication model


n

The trigger does not know the user; user's reaction is of no interest to trigger

l Areas of use
n

GUI implementations

n Conformity with other object models: COM, ActiveX controls, OpenDoc

SAP AG 2002

n n

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.

SAP AG

TAW10

10-4

Triggering and Handling Events: Overview

Rules:
1 2

l Triggering events
Class defines event (EVENTS, CLASS-EVENTS) Object or class triggers event (RAISE EVENT)

l Handling events
3 Event handler class defines and implements event handler method ([CLASS-]METHODS... FOR EVENT ... OF ...)

Event handler object or handler class registers itself to specific events at runtime (SET HANDLER)

SAP AG 2002

At the moment of implementation, a class defines its: - Instance events (using the EVENTS statement) - Static events (using the CLASS-EVENTS statement) Classes or their instances that receive a message when an event is triggered at runtime and want to react to this event define event handler methods. Statement: [CLASS-]METHODS <handler_method> FOR EVENT <event> OF <classname>. These classes or their instances are registered to one or more events at runtime. Statement: SET HANDLER <handler_method> FOR <reference>. (for instance events) SET HANDLER <handler_method>. (for static events) A class or instance can trigger an event at runtime using the RAISE EVENT statement.

SAP AG

TAW10

10-5

Defining and Triggering Events: Syntax


CLASS <classname> DEFINITION. EVENTS: <event> EXPORTING VALUE(<ex_par>) TYPE <type>. CLASS <classname> IMPLEMENTATION. METHOD <m>. RAISE EVENT <event> EXPORTING <ex_par> = <act_par>. CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. METHODS constructor IMPORTING EVENTS vehicle_created. 1
...

...

ENDCLASS. CLASS lcl_vehicle IMPLEMENTATION. METHOD constructor.


...

car

vehicle_created

RAISE EVENT vehicle_created. ENDMETHOD. ENDCLASS.

SAP AG 2002

n n n n

Both instance and static events can be triggered in instance methods. Only static events can be triggered in static methods. Events can only have EXPORTING parameters which must be passed by value. Triggering an event using the statement RAISE EVENT has the following effect: - The program flow is interrupted at that point - The event handler methods registered to this event are called and processed - Once all event handler methods have been executed, the program flow continues If an event handler method in turn triggers an event, then the program flow is again interrupted and all event handler methods are executed (nesting).

SAP AG

TAW10

10-6

Handling and Registering Events

Sender
Interest in event?
car1

Handler

rental

registration office
car2

carrier
truck

vehicle_created
SAP AG 2002

n n n

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.

SAP AG

TAW10

10-7

Event Handler Methods

CLASS <class_handle> DEFINITION. METHODS: <on_event> FOR EVENT <event> OF <classname> | <interface> IMPORTING <ex_par1> ... <ex_parN> [sender].

CLASS lcl_rental DEFINITION. ... PRIVATE SECTION. METHODS: add_vehicle FOR EVENT vehicle_created OF lcl_vehicle 3 IMPORTING sender. ENDCLASS.

car1
vehicle_created
SAP AG 2002

rental
add_vehicle

n n

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.

SAP AG

TAW10

10-8

Registering for an Event: Syntax


SET HANDLER <ref_handle>-><on_event> FOR <ref_sender> | FOR ALL INSTANCES [ACTIVATION <var>].

CLASS lcl_rental DEFINITION.


...

PRIVATE SECTION. METHODS: add_vehicle FOR EVENT vehicle_created OF ENDCLASS. CLASS lcl_rental IMPLEMENTATION. METHOD constructor.
...

...

SET HANDLER add_vehicle FOR ALL INSTANCES. ENDMETHOD. ENDCLASS.

car1
set handler
vehicle_created
SAP AG 2002

rental

n n n

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.

SAP AG

TAW10

10-9

Registration/Deregistration: Handler Tables

Handler table for "car2


r_car vehicle_created (event) Registered Handler object method reg_vehicle

car2

registration office

Handler table for "car1"


r_car vehicle_created (event) Registered Handler object method add_vehicle reg_vehicle rental

car1

registration office

SAP AG 2002

n n

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.

SAP AG

TAW10

10-10

Event Handling: Features

l l l

Event handling is sequential Sequence in which event handler methods are called is not defined With regard to the Garbage Collector, registration has the same effect as a reference to the registered object
n

Registered objects are never deleted

l l

The visibility of an event defines authorization for event handling The visibility in an event handler method defines authorization for using SET HANDLER statements
n

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.

SAP AG

TAW10

10-11

Events: Unit Summary

You are now able to: l Define and trigger events l Handle events l Register and deregister events l Explain the conceptual differences between methods and events

SAP AG 2002

SAP AG

TAW10

10-12

Events
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

Exercises

As soon as a new airplane is created, this event must be made known to the airline. .

Model solution: SAPBC401_EVES_MAIN_A SAPBC401_VEHD_H include program SAPBC401_EVES_A include program 1 The add_airplane method of the class lcl_carrier will no longer be explicitly called in the main program, but be triggered automatically from the class lcl_airplane. Triggering an event when a plane is created (CREATE OBJECT) will result in the automatic execution of the airline method add_airplane. 1-1 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. Trigger the event airplane_created in a suitable method within the class lcl_airplane. 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. In the main program, comment out the calls r_carrier->add_airplane. 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.

1-2 1-3

1-4 1-5

1-6 Optional:

SAP AG

TAW10

10-13

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? Implement your solution for lcl_carrier and lcl_rental.

2-2

SAP AG

TAW10

10-14

Solutions
Unit: Events

Topic: Triggering and Handling Events

*&---------------------------------------------------------------------* *& Report *& SAPBC401_EVES_MAIN_A * *

*&---------------------------------------------------------------------* *& Implement Events in lcl_vehicle and lcl_airplane *

*&---------------------------------------------------------------------*

REPORT

sapbc401_eves_main_a.

TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2.

INCLUDE <icon>. include sapbc401_vehd_h. INCLUDE sapbc401_eves_a.

DATA: r_vehicle TYPE REF TO lcl_vehicle, r_truck TYPE REF TO lcl_truck, r_bus TYPE REF TO lcl_bus,

r_passenger type ref to lcl_passenger_plane, r_cargo type ref to lcl_cargo_plane, r_carrier type ref to lcl_carrier, r_rental type ref to lcl_rental, r_agency type ref to lcl_travel_agency.

START-OF-SELECTION. *########################

***** Create TRAVEL_AGENCY ************************************** CREATE OBJECT r_agency EXPORTING im_name = 'Fly&Smile Travel'.

***** Create CARRIER ******************************************** SAP AG TAW10 10-15

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 ). r_carrier->add_airplane( r_cargo ).

***** insert business-parnter of agency into partner_list*********** r_agency->add_partner( r_carrier ).

******* create RENTAL ***************************************** CREATE OBJECT r_rental EXPORTING im_name = 'HAPPY CAR RENTAL'.

******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = 'MAN' im_cargo = 45. * r_rental->add_vehicle( r_truck ).

******* create truck ***************************************** CREATE OBJECT r_bus EXPORTING im_make = 'Mercedes' im_passengers = 80. * r_rental->add_vehicle( r_bus ).

******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = 'VOLVO' im_cargo = 48. * r_rental->add_vehicle( r_truck ).

***** insert business-parnter of agency into partner_list*********** r_agency->add_partner( r_rental ).

******* show attributes of all partners of travel_agency ****** r_agency->display_agency_partners( ).

SAP AG

TAW10

10-16

*&---------------------------------------------------------------------* *& Include SAPBC401_EVES_A *

*&---------------------------------------------------------------------* *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION *

*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION.

PUBLIC SECTION. "--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.

METHODS: constructor IMPORTING im_name TYPE string

im_planetype TYPE saplane-planetype, display_attributes.

CLASS-METHODS: display_n_o_airplanes. events airplane_created.

PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes IMPORTING im_type EXPORTING ex_weight ex_tankcap TYPE saplane-planetype TYPE s_plan_wei TYPE s_capacity.

DATA: name

TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i.

ENDCLASS.

"lcl_airplane DEFINITION

*------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION *

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.

METHOD constructor. name planetype SAP AG = im_name. = im_planetype. TAW10 10-17

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.

"get_technical_attributes

ENDCLASS.

"lcl_airplane IMPLEMENTATION

*---------------------------------------------------------------------* * CLASS lcl_cargo_plane DEFINITION

*---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.

PUBLIC SECTION. SAP AG TAW10 10-18

"---------------------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

*---------------------------------------------------------------------* 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. "display_attributes

ENDCLASS.

"lcl_cargo_plane IMPLEMENTATION

*---------------------------------------------------------------------* * CLASS lcl_passenger_plane DEFINITION

*---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..

PUBLIC SECTION. METHODS: constructor IMPORTING im_name TYPE string SAP AG TAW10 10-19

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

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* 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. ENDCLASS. "display_attributes "lcl_passenger_plane IMPLEMENTATION

*---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION

*---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION.

PUBLIC SECTION. "---------------------------------------INTERFACES lif_partners. METHODS: constructor IMPORTING im_name TYPE string, SAP AG TAW10 10-20

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,

airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS. "lcl_carrier DEFINITION

*---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION

*---------------------------------------------------------------------* 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. "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. set handler add_airplane for all instances. ENDMETHOD. "constructor

METHOD get_name. SAP AG TAW10 10-21

ex_name = name. ENDMETHOD. "get_name

ENDCLASS.

"lcl_carrier IMPLEMENTATION

SAP AG

TAW10

10-22

Solutions (optional)
Unit: Events

Topic: Triggering and Handling Events


*&---------------------------------------------------------------------* *& Report *& SAPBC401_EVES_MAIN_B * *

*&---------------------------------------------------------------------* *& *& Implement Events in LCL_vehicle and lcl_airplane Implement Events in LCL_carrier and lcl_rental * *

*&---------------------------------------------------------------------*

REPORT

sapbc401_eves_main_b.

TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2.

INCLUDE <icon>. include sapbc401_vehd_i. INCLUDE sapbc401_eves_b.

DATA: r_vehicle TYPE REF TO lcl_vehicle, r_truck TYPE REF TO lcl_truck, r_bus TYPE REF TO lcl_bus,

r_passenger type ref to lcl_passenger_plane, r_cargo type ref to lcl_cargo_plane, r_carrier type ref to lcl_carrier, r_rental type ref to lcl_rental, r_agency type ref to lcl_travel_agency.

START-OF-SELECTION. *########################

******* create travel_agency ***************************************** CREATE OBJECT r_agency EXPORTING im_name = 'Fly&Smile Travel'.

******* create rental ***************************************** CREATE OBJECT r_rental EXPORTING im_name = 'HAPPY CAR RENTAL'.

SAP AG

TAW10

10-23

******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = 'MAN' im_cargo = 45. ******* create truck ***************************************** CREATE OBJECT r_bus EXPORTING im_make = 'Mercedes' im_passengers = 80.

******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = 'VOLVO' im_cargo = 48.

***** 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.

******* show attributes of all partners of travel_agency ****** r_agency->display_agency_partners( ).

SAP AG

TAW10

10-24

*&---------------------------------------------------------------------* *& Include SAPBC401_EVES_B *

*&---------------------------------------------------------------------* *------------------------------------------------------------------* * events in: lcl_airplane and lcl_carrier ! * *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION *

*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION. PUBLIC SECTION. "--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.

METHODS: constructor IMPORTING im_name TYPE string

im_planetype TYPE saplane-planetype, display_attributes.

CLASS-METHODS: display_n_o_airplanes. EVENTS:airplane_created.

PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes IMPORTING im_type EXPORTING ex_weight ex_tankcap TYPE saplane-planetype TYPE s_plan_wei TYPE s_capacity.

DATA: name

TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i.

ENDCLASS.

"lcl_airplane DEFINITION

*------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION *

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.

METHOD constructor. SAP AG TAW10 10-25

name planetype

= im_name. = 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. METHOD display_n_o_airplanes. WRITE: /, / 'Number of airplanes: '(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. ENDMETHOD. "display_n_o_airplanes "display_attributes

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. ... *---------------------------------------------------------------------* * CLASS lcl_carrier DEFINITION ex_weight = 100000. ex_tankcap = 10000. ENDIF. "get_technical_attributes "lcl_airplane 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, SAP AG TAW10 10-26

PRIVATE SECTION. "----------------------------------DATA: name TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS. "lcl_carrier DEFINITION

*---------------------------------------------------------------------* * CLASS lcl_carrier IMPLEMENTATION

*---------------------------------------------------------------------* 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. 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 "display_attributes

METHOD constructor. name = im_name. SET HANDLER add_airplane FOR ALL INSTANCES. RAISE EVENT lif_partners~partner_created. ENDMETHOD. ENDCLASS. "constructor "lcl_carrier IMPLEMENTATION

SAP AG

TAW10

10-27

*&---------------------------------------------------------------------* *& 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

*---------------------------------------------------------------------* 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 METHODS METHODS constructor IMPORTING im_make TYPE string. display_attributes. set_make IMPORTING im_make TYPE string. get_make EXPORTING ex_make TYPE string.

CLASS-METHODS get_count EXPORTING re_count TYPE i. EVENTS: vehicle_created. PRIVATE SECTION. "------------------DATA: make TYPE string.

METHODS

init_make.

CLASS-DATA:

n_o_vehicles TYPE i.

ENDCLASS.

"lcl_vehicle DEFINITION

*---------------------------------------------------------------------* SAP AG TAW10 10-28

CLASS lcl_vehicle IMPLEMENTATION

*---------------------------------------------------------------------* 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 " me->init_make( ). also possible

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. "get_count

ENDCLASS.

"lcl_vehicle IMPLEMENTATION

*---------------------------------------------------------------------* * CLASS lcl_rental DEFINITION

*---------------------------------------------------------------------* SAP AG TAW10 10-29

CLASS lcl_rental DEFINITION.

PUBLIC SECTION. "------------------METHODS: METHODS constructor IMPORTING im_name TYPE string. add_vehicle for event vehicle_created of lcl_vehicle importing sender. 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

*---------------------------------------------------------------------* CLASS lcl_rental IMPLEMENTATION. METHOD lif_partners~display_partner. display_attributes( ). ENDMETHOD. "lif_partners~display_partner

METHOD

constructor.

name = im_name. set handler add_vehicle for all instances. raise event lif_partners~partner_created. ENDMETHOD. "constructor

METHOD

add_vehicle.

APPEND sender TO vehicle_list. ENDMETHOD. "add_vehicle

METHOD

display_attributes.

DATA: r_vehicle TYPE REF TO lcl_vehicle. skip 2. WRITE: / WRITE: icon_transport_proposal AS ICON, name. ' Here comes the vehicle list: '. ULINE. ULINE.

LOOP AT vehicle_list INTO r_vehicle. r_vehicle->display_attributes( ). ENDLOOP. ENDMETHOD. SAP AG "display_attributes TAW10 10-30

ENDCLASS.

"lcl_rental IMPLEMENTATION

*---------------------------------------------------------------------* * CLASS lcl_travel_agency DEFINITION

*---------------------------------------------------------------------* CLASS lcl_travel_agency DEFINITION.

PUBLIC SECTION. "------------------METHODS: METHODS constructor IMPORTING im_name TYPE string. add_partner for event partner_created of lif_partners IMPORTING sender. METHODS PRIVATE SECTION. "------------------DATA: name TYPE string, partner_list TYPE TABLE OF REF TO lif_partners. ENDCLASS. "lcl_travel_agency DEFINITION display_agency_partners.

*---------------------------------------------------------------------* * CLASS lcl_travel_agency IMPLEMENTATION

*---------------------------------------------------------------------* CLASS lcl_travel_agency IMPLEMENTATION. METHOD display_agency_partners. DATA: r_partner TYPE REF TO lif_partners. WRITE: icon_dependents AS ICON, name. WRITE: ' Here are the partners of the travel agency: '.ULINE.ULINE.

LOOP AT partner_list INTO r_partner. r_partner->display_partner( ). ENDLOOP. ENDMETHOD. "display_agency_partners

METHOD

constructor.

name = im_name. set handler add_partner for all instances. ENDMETHOD. "constructor

METHOD

add_partner.

APPEND sender TO partner_list. ENDMETHOD. ENDCLASS. SAP AG "add_partner "lcl_travel_agency IMPLEMENTATION TAW10 10-31

Global Classes and Interfaces

Contents:
l Local versus global classes and interfaces l Class Builder

SAP AG 2002

SAP AG

TAW10

11-1

Global Classes and Interfaces: Unit Objectives

At the conclusion of this unit, you will be able to: l Describe the difference between local and global classes and interfaces l Create global classes and interfaces using the Class Builder

SAP AG 2002

SAP AG

TAW10

11-2

Global Classes / Interfaces (1)

Class Builder Class Builder Working with global classes and interfaces Working with global classes and interfaces

SAP AG 2003

SAP AG

TAW10

11-3

Review: Local Classes and Interfaces

Programm-1 Programm-2 REPORT prog1. REPORT prog2. CLASS lcl_airplane DEFINITION.


...

ENDCLASS.
...

DATA: r_airplane TYPE REF TO lcl_airplane.


...

l Local program classes


n n n

Local classes are only visible in the program they were defined in No global access possible Not stored in the Repository, no where-used list, and so on

SAP AG 2002

n n

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).

SAP AG

TAW10

11-4

Global Classes and Interfaces


l l

ABAP Workbench development tool: Class Builder Tool for creating, testing, and managing global classes and interfaces
n n

Stored in Repository Generates the framework coding, for example CLASS <name> DEFINITION Manages the include programs in which the coding is stored

l l l

Access from all programs using TYPE REF TO Customer namespace for global classes and interfaces: Y* or Z* Where-used list available

SAP AG 2002

n n

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.

SAP AG

TAW10

11-5

Creating Global Classes in the Object Navigator

Workbench

Edit

Goto

Utilities

Environment

System

Help

MIME Repository Repository Browser Diese Kn pre hier Repository Information System ich auch brauche Tag Library Transport Organizer
Package ZBC401_00

Create Report a class in the Object Navigator

Instance creation
Description

Object Name
ZBC401_00 Class Library Classes

private protected public abstract

Normal ABAP class Exception class Persistent class Final class Only modeled

SAP AG 2002

n n n n n

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)

SAP AG

TAW10

11-6

Class Builder: Attributes


Class Edit Goto Utilities Environment System Help

Define class attributes

Class Builder: Change Class ZCL_AIRPLANE_00


Class Constructor Class Interface Properties ZCL_AIRPLANE_00 Interfaces Friends Implemented/Active Attributes Methods Events Internal Types Filter Attribute Name PLANE _TYPE N_O_AIRPLANES Level Instan Instan Static Visib. Mod. Re. Priv Priv Priv Typing Type Type Type Assoc. Type STRING SAPLANE I Description Name of airplane Airplane type Number of airplanes Aliases

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)

SAP AG

TAW10

11-7

Class Builder: Methods


Class Edit Goto Utilities Environment System Help

Define class methods

Class Builder: Change Class ZCL_ AIRPLANE_00


Constructor Class Interface
Properties Interfaces

ZCL_AIRPLANE_00
Friends Attribute Methods

Implemented/Active
Events Internal Types Aliases

Parameters Methods CONSTRUCTOR

Exceptions Level Visibility Mod. Met. Description CONSTRUCTOR Airplane attributes Number of planes Instance Method Public Instance Method Public Static Method Public

DISPLAY ATTRIBUTES DISPLAY_N_O_AIRPLANES

Define signature of selected method, here: CONSTRUCTOR

SAP AG 2002

n n n

Under the Methods tab, you can create methods. This task is simplified by the Constructor function, choosing which automatically creates the constructor method. You still have to specify the interface and the source code for the method. Choose Parameter to define the signature for the method the cursor is currently on.

SAP AG

TAW10

11-8

Class Builder: Interface Methods


Class Edit Goto Utilities Environment System Help

Class Builder: Change Class ZCL_ AIRPLANE_00

Class Interface
Properties Interfaces

ZCL_AIRPLANE_00
Friends Attribute Methods

Implemented/Active
Events Internal Types Aliases

Parameters Methods CONSTRUCTOR

Exceptions Level Visibility Mod. Met. Description CONSTRUCTOR Airplane attributes Number of planes Preparations for start Instance Method Public Instance Method Public Static Method Public

DISPLAY ATTRIBUTES DISPLAY_N_O_AIRPLANES ZIF_FLY~START

Interface Method Public

2) Method implementation of a global interface


SAP AG 2002

1) Announce a global interface in a global class

n n n

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.

SAP AG

TAW10

11-9

Class Builder: Method Interface

Class

Edit

Goto

Utilities

Environment

System

Help

Class Builder: Change Class ZCL_AIRPLANE_00


Constructor Class Interface
Properties

ZCL_AIRPLANE_00
Interfaces Friends Attributes

Implemented/Active Methods
Events Internal Types Aliases

Method Parameters Methods Parameter IM_ NAME IM_PLANETYPE

CONSTRUCTOR Exceptions P O Typing Type Type Type Type Assoc. Type STRING SAPLANE-... C C Plane type Default Value Description

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.

SAP AG

TAW10

11-10

Class Builder: Method Implementation

Method

Edit

Goto

Utilities

Environment

System

Help

Class Builder: Change Class ZCL_ AIRPLANE_00


Signature Type Parameters IM_NAME IM_PLANETYPE Type spec. TYPE STRING TYPE SAPLANE-PLANETYPE Plane type Description

Method

CONSTRUCTOR

active

METHOD constructor. make = im_name. plane_type = im_planetype. ADD 1 TO n_o _airplanes. ENDMETHOD.

Display the interface to Display thewith implementing help interface to help with implementing the method the method

SAP AG 2002

n n

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.

SAP AG

TAW10

11-11

Class Builder: Inheritance


Class Edit Goto Utilities Environment System Help

Class Builder: Change Class CL_VEHICLE Announce superclass


Class Constructor Class Interface Properties ZCL_CARGO_PLANE_00 Interfaces Friends Implemented/Active Events Internal Types Aliases

Attributes Methods

Superclass Superclass

Superclass Description Instantiation Final ...


SAP AG 2002

ZCL_AIRPLANE_00 ... ...

n n n

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.

SAP AG

TAW10

11-12

Class Builder: Test Environment

Class

Edit

Goto

Utilities

Test Class ZCL_AIRPLANE_00


Instance Upper/Lower Case Active TestObject-> Upper/Lower Case Active Handler

Test Class ZCL_AIRPLANE_00


Handler

ZCL_AIRPLANE_00 Attributes Methods DISPLAY_N_O_AIRPLANES

ZCL_AIRPLANE_00 Interfaces Attributes Methods

45<CL_AIRPLANE_00

DISPLAY_ATTRIBUTES DISPLAY_N_O_AIRPLANES

Create an instance with the test environment


SAP AG 2002

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.

SAP AG

TAW10

11-13

Global Classes / Interfaces (2)

Class Builder Class Builder Working with global classes and interfaces Working with global classes and interfaces

SAP AG 2003

SAP AG

TAW10

11-14

Global Classes in the Object Navigator

Workbench

Edit

Goto

Utilities

Environment

System

Help

ABAP Editor: Report zdemo


Pattern

MIME Repository Repository Browser Diese Kn pre hier Repository Information System ich auch brauche Tag Library Transport Organizer
Class/Interface ZCL_AIRPLANE_00

Report

zdemo

Active

Left: Displaying a class in the navigation window allows you to access the class components

Object Name
ZCL_AIRPLANE_00 Attributes n NAME n N_O_AIRPLANES n PLANE _TYPE Methods

Description
Class Airplane Name of airplane Number of planes Airplane type e

START-OF-SELECTION. ****************************** CREATE OBJECT r_airplane EXPORING IMPORTING ...

= CONSTRUCTOR CONSTRUCTOR = DISPLAY_ ATTRIBUTES Displays airplane attributes = DISPLAY_N_O_ AIRPLANES Displays number of airplanes

Right: Edit an ABAP program in the Editor

SAP AG 2002

n n

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).

SAP AG

TAW10

11-15

Class Builder: CREATE OBJECT


Workbench Edit Goto Utilities Environment System Help

ABAP Editor: Report zdemo


Pattern

MIME Repository Repository BrowserDiese Kn pre hier Selecting and dragging Repository Information the Editor creates System brauche ich auch Tag Library Transport Organizer
Class/Interface ZCL_AIRPLANE_00

Report

zdemo

Active

into
********************************************************************* * XY_00_airplane ********************************************************************* * XY_00_airplane CLASS lcl_airplane DEFINITION. START -OF-SELECTION. ####################

CREATE OBJECT

Object Name
ZCL_AIRPLANE_00 Attributes n NAME n N_O_AIRPLANES n PLANE _TYPE Methods

Description
Class Airplane Name of airplane Number of planes Airplane type e

CREATE OBJECT r_airplane EXPORING ... IMPORTING ...

= CONSTRUCTOR CONSTRUCTOR = DISPLAY_ ATTRIBUTES Displays airplane attributes = DISPLAY_N_O_ AIRPLANES Displays number of airplanes

SAP AG 2002

n n

Drag & drop the class name: Instantiates an object. Selecting and dragging a class name to the right automatically creates a CREATE OBJECT statement with the whole interface of the constructor. You still have to add the call's actual parameters.

SAP AG

TAW10

11-16

Class Builder: CALL METHOD

Workbench

Edit

Goto

Utilities

Environment

System

Help

ABAP Editor: Report zdemo


Pattern

MIME Repository Repository BrowserDiese Kn pre hier Repository Information System ich auch brauche Tag Library Selecting and dragging Transport Organizer
Class/Interface ZCL_AIRPLANE_00

Report

zdemo

Active

into

the Editor creates CALL

METHOD
Description
Class Airplane e Name of airplane Number of planes Airplane type

********************************************* * XY_00_airplane ********************************************* * XY_00_airplane class lcl airplane definition START-OF-SELECTION. #################################

Object Name
ZCL_AIRPLANE_00 Attributes n NAME n N_O_AIRPLANES n PLANE _TYPE Methods

CALL METHOD xxx->display_attributes

= CONSTRUCTOR CONSTRUCTOR = DISPLAY_ ATTRIBUTES Displays airplane attributes = DISPLAY_N_O_ AIRPLANES Displays number of airplanes

SAP AG 2002

n n

Drag & drop the method name: Calls a method Selecting and dragging a method to the right automatically creates a CALL METHOD statement with the whole interface of the method. In this case you must also add the call's actual parameters and set the call's reference variable.

SAP AG

TAW10

11-17

Global Classes and Interfaces: Unit Summary

You are now able to: l Describe the difference between local and global classes and interfaces l Create global classes and interfaces using the Class Builder

SAP AG 2002

SAP AG

TAW10

11-18

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

A travel agency communicates with its business partners. Various hotels are now also to be business partners.

Model solution: CL_HOTEL CL_HOUSE IF_PARTNERS

1-1 1-2

Create the global class ZCL_##_HOTEL in the Class Builder. The class is to have the following attributes: name type STRING, private instance attribute max_beds type I, private instance attribute n_o_hotel type I, private static attribute The class is to have the following methods: constructor with import parameters im_name and im_beds display_attributes for displaying the instance attributes of the class display_n_o_hotels static method for displaying instances created Implement these methods. Activate and test your class using the Class Builder test tool.

1-3

1-4 1-5

SAP AG

TAW10

11-19

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_car_rental

lcl_airplane

lcl_vehicles

...
4

...

...

...

(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.

SAP AG

TAW10

11-20

Solutions
Unit: Global Classes and Interfaces

Topic: Creating Global Classes

*&---------------------------------------------------------------------* *& Report SAPBC401_CLSS_MAIN_A *

*&---------------------------------------------------------------------* *& *& Global Class lcl_hotel is also a business partner of the travel agency * *

*&---------------------------------------------------------------------* REPORT sapbc401_clss_main_a.

TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2.

INCLUDE <icon>. include sapbc401_vehd_j. INCLUDE sapbc401_clss_a.

DATA: r_vehicle TYPE REF TO lcl_vehicle, r_truck TYPE REF TO lcl_truck, r_bus TYPE REF TO lcl_bus,

r_passenger type ref to lcl_passenger_plane, r_cargo type ref to lcl_cargo_plane, r_carrier type ref to lcl_carrier, r_rental type ref to lcl_rental, r_agency type ref to lcl_travel_agency, r_hotel type ref to cl_hotel.

START-OF-SELECTION. *########################

******* create travel_agency ***************************************** CREATE OBJECT r_agency EXPORTING im_name = 'Fly&Smile Travel'.

******* create rental ***************************************** CREATE OBJECT r_rental EXPORTING im_name = 'HAPPY CAR RENTAL'. SAP AG TAW10 11-21

******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = 'MAN' im_cargo = 45.

***** 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.

******* create hotel ***************************************** create object r_hotel exporting im_name = 'HOLIDAY INN' im_beds = 345.

******* show attributes of all partners of travel_agency ****** r_agency->display_agency_partners( ).

SAP AG

TAW10

11-22

Special Techniques

Contents:
l Abstract and final classes l Visibility of constructors l Friends l Object Services

SAP AG 2002

SAP AG

TAW10

12-1

Special Techniques: Unit Objectives

At the conclusion of this unit, you will be able to: l Create and describe abstract and final classes l Explain the visibility criteria of constructors l Describe the friend concept l Describe the persistence service of Object Services

SAP AG 2002

SAP AG

TAW10

12-2

Special Techniques (1)

Abstract and final classes Abstract and final classes Visibility of constructors Visibility of constructors The friend concept The friend concept Persistent objects Persistent objects

SAP AG 2002

SAP AG

TAW10

12-3

Abstract Classes

Abstract classes themselves cannot be instantiated (although their subclasses can)


n

References to abstract classes can refer to instances of subclasses

Abstract (instance) methods are defined in the class, but not implemented
n

They must be redefined in subclasses

CLASS lcl_vehicle DEFINITION ABSTRACT. PUBLIC SECTION. METHODS estimate_fuel_consumption ABSTRACT IMPORTING ... ENDCLASS.

Class cannot be instantiated

Method not implemented in this class


SAP AG 2002

n n

n n

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).

SAP AG

TAW10

12-4

Final Classes

Final classes cannot have subclasses

CLASS lcl_truck DEFINITION FINAL INHERITING FROM lcl_vehicle. ... ENDCLASS.


truck

vehicle

bus

...

...

...

Final methods cannot be redefined in subclasses

CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle. PUBLIC SECTION. METHODS estimate_number_of_free_seats FINAL. ENDCLASS.

SAP AG 2002

n n n

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.

SAP AG

TAW10

12-5

Special Techniques (2)

Abstract and final classes Abstract and final classes Visibility of constructors Visibility of constructors The friend concept The friend concept Persistent objects Persistent objects

SAP AG 2002

SAP AG

TAW10

12-6

Who Can Instantiate Classes?

The usability of classes can be restricted: CLASS cl_class DEFINITION ...


n

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

l l

This implicitly controls the visibility of the class Possible use: Singleton concept
Client

(1) lcl_singleton
Public

Private
r_singl

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.

SAP AG

TAW10

12-7

Special Techniques (3)

Abstract and final classes Abstract and final classes Visibility of constructors Visibility of constructors The friend concept The friend concept Persistent objects Persistent objects

SAP AG 2002

SAP AG

TAW10

12-8

Friends
l

In rare cases, classes have to work together closely and make all their components, including the protected and private ones, available to each other
n

Efficient direct access to the data of a class providing friendship Methods that access the same data can therefore be spread over several classes Package creation support Friend Provides friendship
(5) lcl_flight_data flight_list (3) lcl_flight_factory create_flight get_flight delete_flight

Package Friend
...

SAP AG 2002

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.

SAP AG

TAW10

12-9

Special Techniques (4)

Abstract and final classes Abstract and final classes Visibility of constructors Visibility of constructors The friend concept The friend Persistent objects Persistent

SAP AG 2002

SAP AG

TAW10

12-10

Persistence Service

ABAP program

Transient objects

Persistence service

Read/write objects

Database

Persistent data in tables


SAP AG 2002

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 programindependently, that is persistently, it must be stored in the database. (You could also use files on operating system level.) In ABAP Objects, this is done using the OPEN SQL interface. To be able to work with ABAP Objects persistently, the persistence service was introduced with SAP R/3 Basis Release 6.10. Objects and their attributes can be written to the database and reimported.

SAP AG

TAW10

12-11

Features of the Persistence Service

l l l

Objects of a running ABAP program are transient The persistence service allows you to work with persistent objects Persistent classes are created in the Class Builder
Create Class CL_PERSISTENT_CLASS Class Type Normal ABAP Class Exception Class Persistent Class

...

Persistence service tasks


n n n

Loading the objects from the database Managing changes to the objects Storing the objects in the database

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.

SAP AG

TAW10

12-12

Class Agent
l Within the persistence service, the class actor or class agent manages the persistent objects
n

The agent provides a range of services (methods), which are used to manage the objects and the encapsulated data Technically, the agent is a singleton, which is addressed using the public static attribute AGENT

...

DATA: r_carrier TYPE REF TO cl_carrier, r_agent TYPE REF TO ca_carrier, carrname TYPE s_carrname. r_agent = ca_carrier=>agent.

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.

SAP AG

TAW10

12-13

Special Techniques: Unit Summary

You are now able to: l Create and describe abstract and final classes l Explain the visibility criteria of constructors l Describe the friend concept l Describe the persistence service of Object Services

SAP AG 2002

SAP AG

TAW10

12-14

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

Model solution: CL_SINGLETON SAPBC401_SPCS_MAIN_A

(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.) Instantiation only takes place within the class. The class has a static reference variable r_singleton that refers to the instantiated object. The class has a static reference variable r_singleton that refers to the instantiated object.

1-2 1-3

1-4

In the main program ZBC401_##_MAIN_SPECIAL, instantiate the singleton class ZCL_##_SINGLETON by calling the get_singleton method. 2-1 2-2 Why must the get_singleton method in this example be static? Verify your blueprint by calling get_singleton several times. (Debug.) When does instantiation take place and how often?

SAP AG

TAW10

12-15

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 Add a static attribute connection_list (with type TY_CONNECTIONS, that is an itab) to the singleton class. When instantiating the singleton, this internal table is to be automatically filled with the flight connections from the table SPFLI.

3-2

Create a global class ZCL_##_AGENCY, which is to be provided friendship by the singleton. 4-1 4-2 Define and implement a constructor for ZCL_##_AGENCY. In the constructor, the private attribute of the class name is to be initialized. This class is to have a public method get connection. 4-2-1 Import parameter: im_carrid and im_connid (types: S_CARR_ID and S_CONN:ID) 4-2-2 Export parameter: A structure with line type SPFLI Name the export parameter ex_connection.

SAP AG

TAW10

12-16

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 Go back to the singleton class. Here, provide friendship to the class ZCL_##_AGENCY.

In your main program, instantiate the class ZCL_##_AGENCY. The singleton should have been instantiated in the last exercise. There, the internal table with the flight connections is already filled. 6-1-1 Execute the get_connection method of ZCL_##_AGENCY requesting a flight connection that exists in the SPFLI table. (for example LH / 0400)

friend
(3) lcl_agency (1) cl_singleton connection_ list get_ connection

SAP AG

TAW10

12-17

Solutions - optional
Unit: Special Techniques

Topic: Singleton Classes

*&---------------------------------------------------------------------* *& Report SAPBC401_spcS_MAIN_A *

*&---------------------------------------------------------------------* *& *& *& *& *& *& *& Work with singleton: The singleton class consists of a static pointer r_singleton pointing to the class itself; the class is final and has the attribute create private. in the class-constructor the class is instantiated via this reference. The static method get_singleton passes the reference to the outside world so that the singleton can be used!

*&---------------------------------------------------------------------*

REPORT

sapbc401_spcs_main_a.

DATA: r_single type ref to cl_singleton.

START-OF-SELECTION. *########################

r_single = cl_singleton=>get_singleton( ).

SAP AG

TAW10

12-18

Solutions - optional
Unit: Special Techniques

Topic: Concluding Project Exercise


*&---------------------------------------------------------------------* *& Report SAPBC401_spcS_MAIN_B *

*&---------------------------------------------------------------------* *& *& *& *& *& *& *& *& The class cl_agency is a friend of the singleton; cl_agency works directly with the private data of the singleton the method get_connection reads single records out of an internal table of the singleton; so the singleton acts as a kind of data-container. cl_agency uses this data in the singleton directly. (performance aspects, package-concept...) Practice with singleton & friends (show package concept )

*&---------------------------------------------------------------------*

REPORT

sapbc401_spcs_main_b.

DATA: r_single type ref to cl_singleton, r_agency type ref to cl_agency, rec type spfli.

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.

SAP AG

TAW10

12-19

Exception Handling

Contents:
l Predefined exceptions and exceptions you define yourself l Raising, handling, and passing along exceptions

SAP AG 2002

SAP AG

TAW10

13-1

Exception Handling: Unit Objectives

At the conclusion of this unit, you will be able to: l Create your own exception classes l Raise exceptions in a program l Handle exceptions l Pass exceptions along

SAP AG 2002

SAP AG

TAW10

13-2

Class-Based Exceptions: Overview


Exception class (either predefined or defined by you)

cx_exception
...

...

ABAP program

... RAISE EXCEPTION TYPE cx_exception [EXPORTING attr1 = ... attr2 = ...]. ... * Exception handling ...

ABAP runtime system


SAP AG 2002

Exception raised either in ABAP statement or by runtime system

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.

SAP AG

TAW10

13-3

Exception Classes: The Inheritance Hierarchy


cx_root
textid kernel_errid ... get_text get_source_position

cx_no_check

cx_dynamic_check

cx_static_check

cx_sy_arithmetic_error

cx_sy_move_cast_error

cx_sy_arithmetic_overflow
SAP AG 2002

n n

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.

SAP AG

TAW10

13-4

Handling Exceptions

TRY. ... CATCH cx_... ... CATCH cx_... ... CLEANUP. ... ENDTRY. ... [INTO r_exc2]. cx_... ... [INTO r_exc1].

Code whose exceptions (if any) are to be handled

Handlers for the Handlers for the specified specified exception exception classes classes and their and their subclasses subclasses

Block for "tidying up" if there is no handler available in the TRYENDTRY structure

SAP AG 2002

Like all ABAP control structures, TRY-ENDTRY structures can be nested. Thus the TRY block, CATCH- blocks, 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 TRYENDTRY 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.

SAP AG

TAW10

13-5

Example: Handling a Predefined Exception


PARAMETERS: int1 int2 TYPE i, TYPE i.

DATA: result TYPE i, text TYPE string, r_exc TYPE REF TO cx_root. ...

If an overflow error occurs, the runtime system raises the cx_sy_arithmetic_overflow exception

TRY. result = int1 * int2. WRITE result. CATCH cx_sy_arithmetic_overflow INTO r_exc. text = r_exc->get_text( ). MESSAGE text TYPE 'I'. ENDTRY.
Information

...

i
?
SAP AG 2002

Overflow in the operation '*'

n n

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.

SAP AG

TAW10

13-6

Example: Using Your Own Exceptions


CLASS lcl_airplane DEFINITION. ... METHODS get_technical_attributes IMPORTING im_type TYPE saplane-planetype EXPORTING ex_weight TYPE s_plan_wei ex_tankcap TYPE s_capacity. ... ENDCLASS.

CLASS lcl_airplane IMPLEMENTATION. ... METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) WHERE planetype = im_type. IF sy-subrc <> 0. ex_weight = 100000. ex_tankcap = 10000. ENDIF. ENDMETHOD. ... ENDCLASS.
SAP AG 2002

Adapting the program: If there is no table entry available, raise and handle an exception you have written

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.

SAP AG

TAW10

13-7

Creating Your Own Exception Classes

Workbench

Edit

Goto

Utilities

Environment

System

Help

Pattern

Pretty Printer Report

MIME Repository Object Navigator Diese Knpre hier Repository Infosystem brauche ich auch Tag Library Transport Organizer
Package ZBC401_00

Object Name
ZBC401_00 Class Library Classes

Description

ZCX_WRONG_PLANETYPE privat protected CX_STATICS_CHECK Inherits From public abstract Class Type: Usual ABAP Class Exception Class Persistent Class ! Final Class Only modeled

Class

SAP AG 2002

n n n

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 cla sses. 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.

SAP AG

TAW10

13-8

Maintaining Your Own Attributes and Exception Texts


Class Edit Goto Utilities Environment System Help

Class Builder: Change Class ZCX_WRONG_PLANETYPE


Class Documentation Class Interface ZCX_WRONG_PLANETYPE Implemented/Active

Attributes Texts

Your own attributes provide the user with Attribute additional information Type
CX_ROOT TEXTID PREVIOUS Const.. Instan.. Pub.. Pub.. Pub.. Pub.. Pub..

Filter Nu Re ! ! ! ! Typing Type Type Type Re Type Type Associated Type SOTR_CONC SOTR_CONC CX_ROOT S380ERRID SAPLANE-PLANETYPE

Instan.. KERNEL_ERRID Instan.. PL_TYPE Instan..

Exception text used to describe exception situation in more detail

Exception ID CX_ROOT
SAP AG 2002

Text An exception occurred

ZCX_WRONG_PLANETYPE This airplane type is unknown

n n

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.

SAP AG

TAW10

13-9

Raising and Handling Exceptions You Have Written


METHOD get_technical_attributes. DATA: r_exc TYPE REF TO cx_root, text TYPE string. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) WHERE planetype = im_type. IF sy-subrc <> 0. TRY. RAISE EXCEPTION TYPE zcx_wrong_planetype EXPORTING pl_type = im_type. CATCH zcx_wrong_planetype INTO r_exc. text = r_exc->get_text( ). MESSAGE text TYPE 'I'. ENDTRY. ENDIF. ENDMETHOD.
Information

Example: im_type = A390-200

i
?

The airplane type A390-200 is unknown

SAP AG 2002

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.

SAP AG

TAW10

13-10

Passing Exceptions Along


CLASS class DEFINITION. ... METHODS meth IMPORTING <im_parameter> EXPORTING <ex_parameter> RAISING cx_exception. ... ENDCLASS. CLASS class IMPLEMENTATION. ... METHOD meth. ... RAISE EXCEPTION TYPE cx_exception. ENDMETHOD. ENDCLASS.

REPORT propagate_exceptions. ... DATA r_obj TYPE REF TO class. ... TRY. r_obj->meth( EXPORTING ... IMPORTING ... ). CATCH cx_exception. ... ENDTRY.

Exceptions that occur in procedures do not necessarily need to be handled there; they can be passed along to the calling program.

SAP AG 2002

n n

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.

SAP AG

TAW10

13-11

Example: Passing Exceptions Along


CLASS lcl_airplane DEFINITION. METHODS display_attributes. METHODS get_technical_attributes IMPORTING im_type TYPE saplane-planetype EXPORTING ex_weight TYPE s_plan_wei ex_tankcap TYPE s_capacity RAISING zcx_wrong_planetype. ENDCLASS. METHOD display_attributes. DATA: r_exc TYPE REF TO cx_root, text TYPE string. ... TRY. get_technical_attributes( EXPORTING im_type = planetype IMPORTING ex_weight = weight ex_tankcap = cap ). WRITE: /'Gewicht:'(003), weight, 'Tankkapazitt:'(004), cap. CATCH zcx_wrong_planetype INTO r_exc. text = r_exc->get_text( ). MESSAGE text TYPE 'I'. ENDTRY. ENDMETHOD.
SAP AG 2002

METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) WHERE planetype = im_type. IF sy-subrc <> 0. RAISE EXCEPTION TYPE zcx_wrong_planetype EXPORTING pl_type = im_type. ENDIF. ENDMETHOD.

n n

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.

SAP AG

TAW10

13-12

Exceptions That Must Be Declared


cx_root

cx_no_check

cx_dynamic_check

cx_static_check

You can handle these exceptions. If you do not, they are passed along automatically. You cannot pass them explicitly using the RAISING addition Not part of syntax check

You must handle these exceptions or pass them along explicitly using the RAISING addition Not part of syntax check

You must handle these exceptions or pass them along explicitly using the RAISING addition Part of syntax 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.

SAP AG

TAW10

13-13

Exception Handling: Unit Summary

You are now able to: l Create your own exception classes l Raise exceptions in a program l Handle exceptions l Pass exceptions along

SAP AG 2002

SAP AG

TAW10

13-14

Exception Handling Exercise 1


Unit: Exception Handling Topic: Defining, raising, propagating, and catching class-based exceptions
At the conclusion of these exercises, you will be able to: Define exception classes Raise class-based exceptions Pass exceptions along Catch class-based exceptions Improve your program so that, when the airplane attributes are displayed, an error text is displayed instead of the default values if the airplane type is invalid. Implement this using the class-based exceptions concept. Program: ZBC401_##_RAISE_TRY Template: SAPBC401_EVES_MAIN_8B Model solution: SAPBC401_EXCS_RAISE_TRY ## is your two-digit group number 1-1 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. Define a global exception class. (We suggest the name ZCX_##_INVALID_PLANETYPE.) Choose the appropriate superclass so that the system performs a syntax check to ensure that, after the relevant exception is raised, it is either handled or passed explicitly along using a RAISING addition. Add an attribute for the airplane type (suggested name: PLANETYPE) and assign the type S_PLANETYPE to it.
Create a default error message that can be enhanced dynamically to include the airplane type.

1-2

1-3

Raise the exception in the get_technical_attributes method of your local class lcl_airplane. Add a RAISING addition to the definition part of the method, so that the exception can be passed along.

SAP AG

TAW10

13-15

1-4

Catch the exception in the display_attributes method of your local class lcl_airplane. To do this, you will need a local reference to the exception instance (suggested name: r_exception). Assign a type to this reference using the superclass CX_ROOT. Read the error text from the exception instance using the get_text method. To do this you will need an auxiliary variable of the type string (suggested name exc_text).

SAP AG

TAW10

13-16

Exception Handling Solution 1


Unit: Exception Handling Topic: Defining, propagating, and raising events

Model solution: Include BC401_EXCS_RAISE_TRY_CL2.

*&---------------------------------------------------------------------* *& Include BC401_EXCS_RAISE_TRY_CL2 *

*&---------------------------------------------------------------------* ... *------------------------------------------------------------------* * CLASS lcl_airplane DEFINITION *

*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION.

PUBLIC SECTION. "--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.

METHODS: constructor IMPORTING im_name TYPE string

im_planetype TYPE saplane-planetype, display_attributes.

CLASS-METHODS: display_n_o_airplanes. EVENTS: airplane_created.

PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes IMPORTING im_type EXPORTING ex_weight ex_tankcap RAISING TYPE saplane-planetype TYPE s_plan_wei TYPE s_capacity

cx_bc401_invalid_planetype.

DATA: name

TYPE string,

planetype TYPE saplane-planetype.

SAP AG

TAW10

13-17

CLASS-DATA: n_o_airplanes TYPE i.

ENDCLASS.

"lcl_airplane DEFINITION

*------------------------------------------------------------------* * CLASS lcl_airplane IMPLEMENTATION *

*------------------------------------------------------------------* 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. ... ENDMETHOD. "display_n_o_airplanes

METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) SAP AG TAW10 13-18

WHERE planetype = im_type. IF sy-subrc <> 0. RAISE EXCEPTION TYPE cx_bc401_invalid_planetype EXPORTING planetype = im_type. ENDIF. ENDMETHOD. ENDCLASS. "get_technical_attributes "lcl_airplane IMPLEMENTATION

SAP AG

TAW10

13-19

Dynamic Programming

Contents:
l Dynamic attributes l Data reference variables l Field symbols l Runtime Type Identification (RTTI)

SAP AG 2002

SAP AG

TAW10

14-1

Dynamic Programming: Unit Objectives

At the conclusion of this unit, you will be able to: l Use dynamic attributes in suitable ABAP statements l Use data objects generated at runtime l Ascertain the attributes of data objects at runtime

SAP AG 2002

SAP AG

TAW10

14-2

Dynamic Programming (1)

Field Symbols in Detail Field Symbols in Detail Dynamic Calls Dynamic Calls Data References Data References Ascertaining Data Attributes Dynamically Ascertaining Data Attributes Dynamically

SAP AG 2002

SAP AG

TAW10

14-3

Field Symbols
FIELD-SYMBOLS <fs> TYPE|LIKE ... |TYPE ANY}. ASSIGN ... dataobject TO <fs>. UNASSIGN <fs>. ... <fs> IS ASSIGNED ... DATA int TYPE i VALUE 15. FIELD-SYMBOLS <fs_int> TYPE i. ASSIGN int TO <fs_int>. WRITE: / int, <fs_int>. <fs_int> = 17. WRITE: / int, <fs_int>. UNASSIGN <fs_int>. IF <fs_int> IS ASSIGNED. WRITE: / int, <fs_int>. ELSE. WRITE: / 'fieldsymbol not assigned'(fna). ENDIF.

Generic or complete type specification

fs_int

15

int

fs_int

15

int

fs_int

17

int

fs_int

17

int

SAP AG 2002

n n

n n

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.

SAP AG

TAW10

14-4

The CASTING Addition

ASSIGN ... dataobject TO <fs> CASTING [TYPE type|...] .

TYPES: BEGIN OF st_date, year(4) TYPE n, month(2) TYPE n, day(2) TYPE n, END OF st_date. * option 1: implicit FIELD-SYMBOLS <fs> TYPE st_date. ASSIGN sy-datum TO <fs> CASTING.

Inhalt des zugewiesenen The content of the assigned Datenobjekts wird so data object is interpreted as interpretiert, als ob er den if it had the implicit or implizit bzw. explizit explicit type specified angegeben Typ htte

sy ... date
20011221

... ...

* access after casting: WRITE: / <fs>-year, <fs>-month, <fs>-day. * option 2: explicit FIELD-SYMBOLS <fs> TYPE ANY. ASSIGN sy-datum TO <fs> CASTING TYPE st_date. ...
SAP AG 2002

...

fs

n n

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. ASSIGN line TO <fs_wa> CASTING TYPE (tabname). You can now access line through <fs_wa> as if this elementary data object had the same type as the line type of the transparent table passed using tabname. (You define the dummy data object only to ensure that line has the correct alignment).

SAP AG

TAW10

14-5

Dynamic Programming (2)

Field Symbols in Detail Field Symbols in Detail Dynamic Calls Dynamic Calls Data References Data References Ascertaining Data Attributes Dynamically Ascertaining Data Attributes Dynamically

SAP AG 2002

SAP AG

TAW10

14-6

Using Dynamic Attributes in Statements


l Replacing a literal with a variable:

CALL TRANSACTION 'T_CODE'. * dynamic: data_object = 'T_CODE'. CALL TRANSACTION data_object. l

Replacing an identifier with a variable in parentheses (without spaces):

SUBMIT report_name. * dynamic: data_object = 'REPORT_NAME'. SUBMIT (data_object). l Replacing a list with an internal table:

SET PF-STATUS 'STATUS_NAME' EXCLUDING 'FC1' 'FC2' ... . * dynamic: * ... fill internal_table with function codes ... SET PF-STATUS 'STATUS_NAME' EXCLUDING internal_table .
SAP AG 2002

n n

n n n

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.

SAP AG

TAW10

14-7

Calling Methods Dynamically


TYPE-POOL abap. TYPES abap_parmbind_tab ... TYPES abap_excpbind_tab ... ...
Name of formal parameter

Internal table types


Reference to the actual parameter

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

How variable is passed (optional)

name kind

value

Name of exception etab name

Value for sy-subrc value

SAP AG 2002

n n n

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 sysubrc. VALUE must be of type i.

SAP AG

TAW10

14-8

Creating Objects Dynamically


l You can enter the class name with CREATE OBJECT both statically and dynamically
n n

Subclasses possible with reference to class Classes carrying out the implementation possible with references to interfaces

CREATE OBJECT < reference> TYPE <classname> [EXPORTING...] [EXCEPTIONS ...]. CREATE OBJECT < reference> TYPE (<classname_string>) ...

DATA: doc TYPE REF TO if_document , class _name(20) TYPE c VALUE CL_TEXT_DOC. CREATE OBJECT CREATE OBJECT doc TYPE cl _html _ doc . doc TYPE ( class_name ).

SAP AG 2003

n n

You can enter the class of the instance to be created either statically, using the class name, or dynamically, using a variable containing the class name. Once the statement has been executed (successfully), a (runtime) instance of the class entered will have been created, and the reference variable entered points to this instance. There are two possible situations: - For a reference variable referring to a class, enter the name of a subclass (or of the class itself). - For a reference variable referring to an interface, enter the name of the class carrying out the implementation. A check can be carried out in the static form ... TYPE <classname> to see if one of the two situations above has occurred. If it has not, a syntax error occurs. In the dynamic form ...TYPE (<classname_string>). the classname_string field provides the class name. A check can be carried out at runtime to ensure that the reference variable type is compatible with the class entered. If this is not the case, a runtime error occurs.

SAP AG

TAW10

14-9

Dynamic Programming (3)

Field Symbols in Detail Field Symbols in Detail Dynamic Calls Dynamic Calls Data References Data References Ascertaining Data Attributes Dynamically Ascertaining Data Attributes Dynamically

SAP AG 2002

SAP AG

TAW10

14-10

Data Reference Variables


TYPES reftype { TYPE REF TO type_name | LIKE REF TO do_name | TYPE REF TO data }. TYPE REF TO type_name | LIKE REF TO do_name | TYPE REF TO data }.

Any completely specified type

DATA

ref

Generic type assignment

GET REFERENCE OF dataobject INTO ref.

DATA:

ref TYPE REF TO i, do TYPE i VALUE 15.

ref do
15

GET REFERENCE OF do INTO ref.

ref do
15

Get a reference to a data object


SAP AG 2002

n n

Data reference varia bles 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.)

SAP AG

TAW10

14-11

Example: Using Data Reference Variables in Dynamic Method Calls


CLASS lcl_vehicle DEFINITION. ... METHODS get_make EXPORTING ex_make TYPE string. ... ENDCLASS. TYPE-POOLS abap. DATA: ptab TYPE wa_ptab LIKE meth TYPE ref TYPE gd_make TYPE ... CLASS lcl_vehicle IMPLEMENTATION. ... METHOD get_make. ex_make = make. ENDMETHOD. ... ENDCLASS.

abap_parmbind_tab, LINE OF ptab, string, REF TO data, string.

After the dynamic method call: name kind value

GET REFERENCE OF gd_make INTO ref. wa_ptab-value = ref. wa_ptab-name = 'EX_MAKE'. INSERT wa_ptab INTO TABLE ptab. meth = 'GET_MAKE'. CALL METHOD r_truck->(meth) PARAMETER-TABLE ptab. WRITE gd_make.
SAP AG 2002

ptab EX_MAKE

gd_make

VOLVO

n n n

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.

SAP AG

TAW10

14-12

Generating Data Objects at Runtime

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 TYPE { type_name | itab_type_def }.

PARAMETERS pa_tab TYPE dd021-tabname. DATA ref_itab TYPE REF TO data.

ref_itab

CREATE DATA ref_itab TYPE STANDARD TABLE OF (pa_tab) WITH DEFAULT KEY. Standard table with standard key and line type appropriate for the content of the data object pa_tab
SAP AG 2002

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).

SAP AG

TAW10

14-13

Dereferencing Data References


You can then address the contents of the internal table using the field symbol

ASSIGN ref->* TO <fs> [CASTING ... ].

PARAMETERS pa_tab DATA ref_itab

TYPE dd021-tabname. TYPE REF TO data.

fs_itab

ref_itab

FIELD-SYMBOLS <fs_itab> TYPE ANY TABLE.

CREATE DATA ref_itab TYPE STANDARD TABLE OF (pa_tab) WITH DEFAULT KEY. ASSIGN ref_itab->* TO <fs_itab>. SELECT * FROM (pa_tab) INTO TABLE <fs_itab>.

SAP AG 2002

n n

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.

SAP AG

TAW10

14-14

Example: Generating Data Objects at Runtime


PARAMETERS pa_dbtab TYPE dd02l-tabname DEFAULT 'SFLIGHT'. DATA d_ref TYPE REF TO data. FIELD-SYMBOLS: <fs_wa> TYPE ANY, <fs_comp> TYPE ANY. START-OF-SELECTION. CREATE DATA d_ref TYPE (pa_dbtab). ASSIGN d_ref->* TO <fs_wa>. SELECT * FROM (pa_dbtab) INTO <fs_wa>. DO. ASSIGN COMPONENT sy-index OF STRUCTURE <fs_wa> TO <fs_comp>. IF sy-subrc NE 0. SKIP. EXIT. ENDIF. WRITE <fs_comp>. ENDDO. ENDSELECT.
SAP AG 2002

n n n

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.

SAP AG

TAW10

14-15

Dynamic Programming (4)

Field Symbols in Detail Field Symbols in Detail Dynamic Calls Dynamic Calls Data References Data References Ascertaining Data Attributes Dynamically Ascertaining Data Attributes Dynamically

SAP AG 2002

SAP AG

TAW10

14-16

Ascertaining Internal Table Attributes


Number of lines in the internal table

DATA: no_of_lines TYPE i, initial_lines TYPE i, table_kind TYPE c. DESCRIBE TABLE itab LINES no_of_lines OCCURS initial_lines KIND table_kind. * other variant: no_of_lines = lines( itab ).

Number of lines reserved when table was first created Table kind

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

n n

The DESCRIBE TABLE statement allows you to obtain the following information about an internal table: n The number of lines: After LINES, you must enter a type i variable (here no_of_lines) n The number of table lines initially reserved:After OCCURS, you must enter a type i variable (here: initial_lines) n 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_KINDSTANDARD, 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 generically-typed interface parameters of subroutines, function modules, and methods can use the information on the table kind.

SAP AG

TAW10

14-17

Dynamic Type Descriptions for RTTI Classes


Hierarchy of description classes:

Rules:
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

Ascertaining the type attributes of a data object at runtime: l Pass the data object to the static method DESCRIBE_BY_DATA of the class CL_ABAP_TYPEDESCR Get the reference to the appropriate description object Evaluate the public attributes of this object

l l

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.

SAP AG

TAW10

14-18

Declaring Types Dynamically: Example


... DATA: descr_ref TYPE REF TO cl_abap_structdescr, wa_comp TYPE abap_compdescr. ...

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

n n

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.

SAP AG

TAW10

14-19

Dynamic Programming: Unit Summary

You are now able to: l Use dynamic attributes in suitable ABAP statements l Use data objects generated at runtime l Ascertain the attributes of data objects at runtime

SAP AG 2002

SAP AG

TAW10

14-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. 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>). In the LOAD-OF-PROGRAM event block: Copy todays date to the input parameter pa_date. Assign the input parameter to the field symbol. Now fill the input parameter with the first day of the next month by accessing the pseudo-components for the year, month, and day, using the field symbol.

1-2

1-3

SAP AG

TAW10

14-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

Copy your program, SAPBC401_DYNT_CREATE_DATA_SQL, giving it the name ZBC401_##_CREATE_DATA_SQL. 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. Define a reference for the internal table that will be generated (we suggest the name ref_itab). 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-2

2-3

2-4

SAP AG

TAW10

14-22

2-5

Assign a generically-typed field symbol to the generated internal table (suggested name: <fs_itab>), so that its contents can be accessed. 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. 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-6

2-7

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.

SAP AG

TAW10

14-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) day(2) TYPE n, TYPE n, month(2) TYPE n, END OF st_date.

CONSTANTS c_number TYPE i VALUE 30. DATA: datastring set_string TYPE string, TYPE string,

wa_flight_c TYPE st_flight_c, wa_flight DATA: it_sets TYPE STANDARD TABLE OF string WITH NON-UNIQUE DEFAULT KEY
SAP AG TAW10 14-24

TYPE st_flight.

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,

it_col_flights TYPE bc401_t_flights_color, it_col_doubles LIKE it_col_flights, wa_col_flight LIKE LINE OF it_col_flights.

FIELD-SYMBOLS <fs_date> TYPE st_date. PARAMETERS: pa_date LIKE sy-datum, pa_alv AS CHECKBOX DEFAULT 'X'.

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. AT SELECTION-SCREEN. IF pa_date < sy-datum. MESSAGE e085(bc401). ENDIF. " date in the past

START-OF-SELECTION. ...
SAP AG TAW10 14-25

Solution 2
Unit: Dynamic Programming

Topic: Dynamic Open SQL Statements and Generate Data Objects at Runtime
2-1 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. 2
REPORT

Model solution: SAPBC401_DYNS_CREATE_DATA_SQL


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'.

SAP AG

TAW10

14-26

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. CREATE OBJECT ref_docking EXPORTING SIDE extension EXCEPTIONS OTHERS . IF sy-subrc <> 0. MESSAGE a015(rfw). ENDIF. CREATE OBJECT ref_alv EXPORTING i_parent EXCEPTIONS error_cntl_create error_cntl_init error_cntl_link error_dp_create OTHERS .
SAP AG

= DOCK_AT_LEFT = 2000 = 6

= ref_docking = = = = = 1 2 3 4 5

TAW10

14-27

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 * *&--------------------------------------------------------* MODULE user_command_0100 INPUT. CASE ok_code. WHEN 'BACK'. CLEAR popans. CALL FUNCTION 'POPUP_TO_CONFIRM_STEP' EXPORTING textline1 = text-dml textline2 = text-rbk
SAP AG TAW10 14-28

titel = text-bak cancel_display = ' ' IMPORTING answer = popans. CASE popans. WHEN 'J'. LEAVE TO SCREEN 0. WHEN 'N'. ENDCASE. WHEN OTHERS. ENDCASE.

SAP AG

TAW10

14-29

Case Study

SAP AG 2003

SAP AG

TAW10

15-1

Exercises
Unit: Case Study Topic: Case Study
At the conclusion of these exercises, you will be able to: Convert a technical specification into a program Create and implement a UML class diagram for the program implementation Define and implement global classes Create exception classes and use them for error handling Define, trigger and handle events and register events Perform operations on internal tables A travel agency wants to provide an extra service to its customers. If a customer wants to book a flight that is already overbooked, that customer can be placed on a waiting list for this flight. If a seat subsequently becomes available, the customer can move up the waiting list. Write a program that the travel agency can use to maintain the waiting lists for the individual flights. Template: TAW10_CST_WAITLIST Model solution: TAW10_CSS1_WAITLIST
(with classes in a table)

TAW10_CSS2_WAITLIST
(with global classes)

Program TAW10_CST_WAITLIST can be used as a template for your own program. It contains a screen on which all of the required functions are already available using the corresponding pushbuttons. However, apart from the icons in the standard toolbar, these functions have not yet been implemented. The following selection options must also be possible.

SAP AG

TAW10

15-2

Pushbutton Display Create Delete Move up Waiting list status Add Delete Position Customer status

Function code SHOW CREATE DELETE FIRST STATWL ADD DEL POS STATCU

Function Displays a list of all customers on the waiting list for the selected flight Creates a waiting list for the selected flight Deletes the waiting list for the selected flight Deletes the first person on the waiting list for the selected flight Displays the number of persons on the waiting list for the selected flight Adds the selected customer to the waiting list for the selected flight Deletes the selected customer from the waiting list for the selected flight Displays the position of the selected customer in the waiting list for the selected flight Displays whether the selected customer is a private or business customer (you can find the corresponding information in the custtype field of table scustom.) Displays all customers who moved up the waiting list for a flight Displays the number of customers who moved up the waiting list for a flight

Display all move-up customers Status log

LOG

STATPR

Hints: You should use an object-oriented approach for the program. The focus of this exercise is to create a workable model, for which you should carefully study components that already exist. The focus is therefore placed less on implementing all of the program's details and more on cleverly selecting its design. You can use the global class CL_TAW10_DISPLAY_LOG to display the log. To display the waiting list entries you can use function module TAW10_DISPLAY_DATA. To simplify the scenario, the waiting list is not stored persistently. This means that the data should be not stored in the database, but kept in the program. 1-1 Copy program TAW10_CST_WAITLIST as ZTAW10_WAITLIST_## (## = group name) and familiarize yourself with the existing parts of the program. Create a UML class diagram that you will use later to implement the program. Consider how you can take advantage of the object-oriented approach through the suitable use of inheritance and interfaces:

1-2

SAP AG

TAW10

15-3

for example, how can you integrate the existing class CL_TAW10_DISPLAY_LOG into your model? Are any services offered by several classes?

The event concept should be used for the logging function that is planned. If a customer moves up the waiting list for a flight, this should be recorded using a log class. The idea should be that when you choose the Move up pushbutton, this triggers an event that is handled by the log class. 1-3 Implement the program. Catch any possible errors using exception classes that are to be created globally (for example, if a customer is to be included in a waiting list that does not exist). Suggestion: first create your classes locally and only import them to the Class Builder at the end (Call Transaction SE24 and choose Object type | Import | Local classes in program). Use appropriate names to ensure that names do not conflict with the other groups working on this exercise.

SAP AG

TAW10

15-4

Solutions
Unit: Case Study Topic: Case Study

1-2

UML class diagram

1-3

Program listing

SAP AG

TAW10

15-5

1 --* 2 * 3 * 4 --* 5 * 6 * 7 --* 8 9 10 11 -* 12 13 -* 14 15 -* 16 17 18 19 20 21 -* 22 23 -* 24 25 -* 26 27 28 29 30 31 32 33 34

*&------------------------------------------------------------------*& Report *& *&------------------------------------------------------------------*& *& *&------------------------------------------------------------------TAW10_CSS1_WAITLIST

REPORT

taw10_css1_waitlist

*-------------------------------------------------------------------* INTERFACE if_taw10_status

*-------------------------------------------------------------------* *-------------------------------------------------------------------INTERFACE if_taw10_status. METHODS display_status. ENDINTERFACE. "if_taw10_status

*-------------------------------------------------------------------* CLASS cl_taw10_customer DEFINITION

*-------------------------------------------------------------------* *-------------------------------------------------------------------CLASS cl_taw10_customer DEFINITION.

PUBLIC SECTION. METHODS constructor IMPORTING im_id TYPE s_customer im_name TYPE s_custname im_street TYPE s_street im_city TYPE city im_app_date TYPE d.

SAP AG

TAW10

15-6

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 -* 51 52 -* 53 54 -* 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 SAP AG * *

METHODS get_attributes EXPORTING ex_cust TYPE taw10_typd_cust.

DATA:

id

TYPE s_customer READ-ONLY.

INTERFACES if_taw10_status.

PRIVATE SECTION. DATA: name street city TYPE s_custname, TYPE s_street, TYPE city,

app_date TYPE d.

ENDCLASS.

"cl_taw10_customer DEFINITION

*-------------------------------------------------------------------CLASS cl_taw10_customer IMPLEMENTATION

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

*-------------------------------------------------------------------CLASS cl_taw10_customer IMPLEMENTATION. METHOD constructor. id = im_id. name = im_name. street = im_street. city = im_city. app_date = im_app_date. ENDMETHOD. "constructor

METHOD get_attributes. ex_cust-id = id. ex_cust-name = name. ex_cust-street = street. ex_cust-city = city. ex_cust-app_date = app_date. ENDMETHOD. "get_attributes

METHOD if_taw10_status~display_status. DATA custtype TYPE s_custtype. CONSTANTS: bcust(1) TYPE c VALUE 'B', TAW10 15-7

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 -* 100 101 -* 102 103 -* 104 105 106 107 108 DEFAULT 109 110 111 112 113 114 SAP AG * * ENDCLASS. ENDMETHOD. * *

pcust(1) TYPE c VALUE 'P'.

SELECT SINGLE custtype FROM scustom INTO (custtype) WHERE id = id.

IF sy-subrc = 0. CASE custtype. WHEN bcust. MESSAGE i015(taw10) WITH id 'Business customer'(001). Customer &1 is &2. WHEN pcust. MESSAGE i015(taw10) WITH id 'Private customer'(002). Customer &1 is &2. ENDCASE. ENDIF.

"if_taw10_status~display_status

"cl_taw10_customer IMPLEMENTATION

*-------------------------------------------------------------------CLASS cl_taw10_waitlist DEFINITION

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

*-------------------------------------------------------------------CLASS cl_taw10_waitlist DEFINITION. PUBLIC SECTION.

TYPES itt_wait_list TYPE STANDARD TABLE OF REF TO cl_taw10_customer WITH KEY.

METHODS constructor IMPORTING im_carrid TYPE sflight-carrid im_connid TYPE sflight-connid im_fldate TYPE sflight-fldate.

TAW10

15-8

115 116 117

METHODS add IMPORTING im_customer TYPE REF TO cl_taw10_customer RAISING cx_taw10_cust_in_list.

118 METHODS delete IMPORTING im_customer TYPE REF TO cl_taw10_customer 119 120 121 METHODS get_pos IMPORTING im_customer TYPE REF TO cl_taw10_customer 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 -* 147 148 -* 149 150 -* 151 152 153 SAP AG CLASS cl_taw10_waitlist IMPLEMENTATION. METHOD constructor. carrid = im_carrid. TAW10 15-9 * *-------------------------------------------------------------------* CLASS cl_taw10_waitlist IMPLEMENTATION *-------------------------------------------------------------------ENDCLASS. "cl_taw10_waitlist DEFINITION DATA wait_list TYPE itt_wait_list. PRIVATE SECTION. INTERFACES if_taw10_status. EVENTS first_got EXPORTING value(ex_cust) TYPE REF TO cl_taw10_customer. DATA: carrid TYPE sflight-carrid READ-ONLY, carrid TYPE sflight-carrid READ-ONLY, fldate TYPE sflight-fldate READ-ONLY. METHODS get_wait_list EXPORTING ex_wait_list TYPE itt_wait_list. METHODS get_first RAISING cx_taw10_empty_list. EXPORTING ex_pos LIKE sy-tabix RAISING cx_taw10_cust_not_in_list. RAISING cx_taw10_cust_not_in_list.

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

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 SAP AG * * * *

connid = im_connid. fldate = im_fldate. ENDMETHOD. "constructor

METHOD get_wait_list. ex_wait_list = wait_list. ENDMETHOD. "get_wait_list

METHOD add. READ TABLE wait_list WITH KEY

table_line->id = im_customer->id TRANSPORTING NO FIELDS.

IF sy-subrc <> 0. INSERT im_customer INTO TABLE wait_list. ELSE.

RAISE EXCEPTION TYPE cx_taw10_cust_in_list EXPORTING TEXTID = PREVIOUS = customer = im_customer->id carrid = carrid connid = connid fldate = fldate.

ENDIF. ENDMETHOD. "add

METHOD get_first. DATA r_cust TYPE REF TO cl_taw10_customer.

READ TABLE wait_list INTO r_cust INDEX 1. IF sy-subrc <> 0.

RAISE EXCEPTION TYPE cx_taw10_empty_list EXPORTING TEXTID = PREVIOUS = carrid = carrid connid = connid fldate = fldate. TAW10 15-10

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 SAP AG * * RAISE EXCEPTION TYPE cx_taw10_cust_not_in_list EXPORTING TEXTID = PREVIOUS = customer = im_customer->id carrid = carrid connid = connid TAW10 15-11 IF sy-subrc = 0. ex_pos = sy-tabix. ELSE. METHOD get_pos. READ TABLE wait_list WITH KEY table_line->id = im_customer->id TRANSPORTING NO FIELDS. ENDIF. ENDMETHOD. "delete * * RAISE EXCEPTION TYPE cx_taw10_cust_not_in_list EXPORTING TEXTID = PREVIOUS = customer = im_customer->id carrid = carrid connid = connid fldate = fldate. METHOD delete. DELETE wait_list WHERE table_line->id = im_customer->id. IF sy-subrc <> 0. ELSE. DELETE wait_list INDEX 1. RAISE EVENT first_got EXPORTING ex_cust = r_cust. ENDIF. ENDMETHOD. "get_first

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 -* 258 259 -* 260 261 -* 262 263 264 265 266 267 268 269 270 271 272 -* 273 274 -* 275 * * ENDCLASS. * * ENDCLASS. * ENDIF.

fldate = fldate.

ENDMETHOD.

"get_pos

METHOD if_taw10_status~display_status. DATA n_o_lines LIKE sy-tabix. n_o_lines = lines( wait_list ).

MESSAGE i014(taw10) WITH carrid connid fldate n_o_lines. The waiting list for flight &1 &2 &3 contains &4 entries. ENDMETHOD. "if_taw10_status~display_status

"cl_taw10_waitlist IMPLEMENTATION

*-------------------------------------------------------------------CLASS cl_taw10_display_log DEFINITION

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

*-------------------------------------------------------------------CLASS cl_taw10_display_log DEFINITION. PUBLIC SECTION. METHODS display_log.

PROTECTED SECTION. DATA: it_log TYPE taw10_typd_cust_list.

"cl_taw10_display_log DEFINITION

*-------------------------------------------------------------------CLASS cl_taw10_display_log IMPLEMENTATION

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

SAP AG

TAW10

15-12

276 -* 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 'I'. 292 293 294 295 296 297 298 -* 299 300 -* 301 302 -* 303 304 305 306 307 308 309 310 311 312 -* 313

*-------------------------------------------------------------------CLASS cl_taw10_display_log IMPLEMENTATION.

METHOD display_log. DATA n_o_lines LIKE sy-tabix.

n_o_lines = lines( it_log ).

IF n_o_lines > 0. SORT it_log BY id. DELETE ADJACENT DUPLICATES FROM it_log COMPARING id. CALL FUNCTION 'TAW10_DISPLAY_DATA' EXPORTING im_list = it_log. ELSE. MESSAGE 'There are no move-up customers available.'(003) TYPE ENDIF. ENDMETHOD. "display_log

ENDCLASS.

"cl_taw10_display_log IMPLEMENTATION

*-------------------------------------------------------------------* CLASS cl_taw10_log DEFINITION

*-------------------------------------------------------------------* *-------------------------------------------------------------------CLASS cl_taw10_log DEFINITION INHERITING FROM cl_taw10_display_log. PUBLIC SECTION. METHODS get_cust FOR EVENT first_got OF cl_taw10_waitlist IMPORTING ex_cust.

INTERFACES if_taw10_status.

ENDCLASS.

"cl_taw10_log DEFINITION

*-------------------------------------------------------------------* CLASS cl_taw10_log IMPLEMENTATION TAW10 15-13

SAP AG

314 -* 315 316 -* 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354

*-------------------------------------------------------------------* *-------------------------------------------------------------------CLASS cl_taw10_log IMPLEMENTATION. METHOD get_cust. DATA wa_cust TYPE taw10_typd_cust.

ex_cust->get_attributes( IMPORTING ex_cust = wa_cust ). INSERT wa_cust INTO TABLE it_log. ENDMETHOD. "get_cust

METHOD if_taw10_status~display_status. DATA: n_o_lines LIKE sy-tabix, c_n_o_lines TYPE string, text TYPE string.

SORT it_log BY id. DELETE ADJACENT DUPLICATES FROM it_log COMPARING id.

n_o_lines = lines( it_log ). c_n_o_lines = n_o_lines. CONCATENATE 'Number of move-up customers:'(004) c_n_o_lines INTO text SEPARATED BY space.

MESSAGE

text TYPE 'I'.

ENDMETHOD.

"if_taw10_status~display_status

ENDCLASS.

"cl_taw10_log IMPLEMENTATION

DATA

ok_code LIKE sy-ucomm.

TABLES: sdyn_conn, scustom.

DATA: r_customer TYPE REF TO cl_taw10_customer, r_cust TYPE REF TO cl_taw10_customer,

r_waitlist TYPE REF TO cl_taw10_waitlist, r_log r_exc TYPE REF TO cl_taw10_log, TYPE REF TO cx_root. TAW10 15-14

SAP AG

355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 INCLUDE taw10_css1_waitlist_o01. INCLUDE taw10_css1_waitlist_i01. CALL SCREEN 100. START-OF-SELECTION. LOAD-OF-PROGRAM. CREATE OBJECT r_log. SET HANDLER r_log->get_cust FOR ALL INSTANCES. DATA: n_o_lines TYPE i, wa_sflight TYPE sflight, text TYPE string. DATA: wa_cust TYPE taw10_typd_cust, DATA: waitlist_buffer TYPE TABLE OF REF TO cl_taw10_waitlist, waitlist TYPE TABLE OF REF TO cl_taw10_customer. DATA r_if_status TYPE REF TO if_taw10_status.

it_wait_list TYPE taw10_typd_cust_list.

SAP AG

TAW10

15-15

1 --* 2 3 4 --* 5 6 7 --* 8 9 --* 10 11 --* 12 13 14 15 16 17 18 19 20 --* 21 22 --* 23 24 --* 25 26 27

*&------------------------------------------------------------------*& * *&------------------------------------------------------------------Include TAW10_CSS1_WAITLIST_O01

*&------------------------------------------------------------------*& Module STATUS_0100 OUTPUT

*&------------------------------------------------------------------* text

*-------------------------------------------------------------------MODULE status_0100 OUTPUT. SET PF-STATUS 'DYNPRO_100'. SET TITLEBAR 'TITLE_100'.

ENDMODULE.

" STATUS_0100

OUTPUT

*&------------------------------------------------------------------*& Module clear_ok_code OUTPUT

*&------------------------------------------------------------------* text

*-------------------------------------------------------------------MODULE clear_ok_code OUTPUT. CLEAR ok_code. ENDMODULE. " clear_ok_code OUTPUT

SAP AG

TAW10

15-16

1 --* 2 3 --* 4 5 6 --* 7 8 --* 9 10 --* 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 --* 30 31 --* 32 33 --* 34 35 36 37

*-------------------------------------------------------------------***INCLUDE TAW10_CSS1_WAITLIST_I01 . *--------------------------------------------------------------------

*&------------------------------------------------------------------*& Module check_and_create_cust INPUT

*&------------------------------------------------------------------* text

*-------------------------------------------------------------------MODULE check_and_create_cust INPUT. SELECT SINGLE name street city FROM scustom INTO CORRESPONDING FIELDS OF scustom WHERE id = scustom-id. IF sy-subrc = 0. CREATE OBJECT r_customer EXPORTING im_id = scustom-id im_name = scustom-name im_street = scustom-street im_city = scustom-city im_app_date = sy-datum. ELSE. CLEAR: scustom-name, scustom-city. MESSAGE e000(taw10) WITH scustom-id. * Customer number & does not exist. Correct your entry! ENDIF. ENDMODULE. " check_and_create_cust INPUT

*&------------------------------------------------------------------*& Module user_command_0100 INPUT

*&------------------------------------------------------------------* text

*-------------------------------------------------------------------MODULE user_command_0100 INPUT.

CASE ok_code. WHEN 'BACK'. TAW10 15-17

SAP AG

38 39 40 41 42 43 44 45 46 47 carrid 48 connid 49 fldate. 50 51

LEAVE TO SCREEN 0.

WHEN 'CREATE'. READ TABLE waitlist_buffer INTO r_waitlist WITH KEY table_line->carrid = sdyn_conn-carrid table_line->connid = sdyn_conn-connid table_line->fldate = sdyn_conn-fldate.

IF sy-subrc <> 0. CREATE OBJECT r_waitlist EXPORTING im_carrid = sdyn_connim_connid = sdyn_connim_fldate = sdyn_connINSERT r_waitlist INTO TABLE waitlist_buffer. MESSAGE s005(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate.

52 53 54

Waiting list for flight &1 &2 &3 created successfully! ELSE. MESSAGE s001(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate.

55 56 57 58 59 60 61 62 63 64 65 66 ). 67 68 69 70 71 72 73 74 75

Waiting list for flight &1 &2 &3 already exists! ENDIF.

WHEN 'SHOW'. CLEAR it_wait_list. READ TABLE waitlist_buffer INTO r_waitlist WITH KEY table_line->carrid = sdyn_conn-carrid table_line->connid = sdyn_conn-connid table_line->fldate = sdyn_conn-fldate.

IF sy-subrc = 0. r_waitlist->get_wait_list( IMPORTING ex_wait_list = waitlist n_o_lines = lines( waitlist ).

IF n_o_lines > 0. LOOP AT waitlist INTO r_cust. r_cust->get_attributes( IMPORTING ex_cust = wa_cust ). INSERT wa_cust INTO TABLE it_wait_list. ENDLOOP.

CALL FUNCTION 'TAW10_DISPLAY_DATA' TAW10 15-18

SAP AG

76 77 78 79 80 81

EXPORTING im_list = it_wait_list.

ELSE. MESSAGE s003(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate.

82 * entries. 83 84 85 86 ELSE. ENDIF.

The waiting list for flight &1 &2 &3 does not contain any

MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate. 87 88 89 90 91 92 93 94 95 96 97 IF sy-subrc = 0. MESSAGE s006(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate. 99 100 * Waiting list for flight &1 &2 &3 deleted successfully! ELSE. MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate. 102 103 104 105 106 107 108 109 110 111 112 113 IF sy-subrc = 0. TRY. TAW10 15-19 WHEN 'FIRST'. READ TABLE waitlist_buffer INTO r_waitlist WITH KEY table_line->carrid = sdyn_conn-carrid table_line->connid = sdyn_conn-connid table_line->fldate = sdyn_conn-fldate. * No waiting list exists for flight &1 &2 &3! ENDIF. WHEN 'DELETE'. DELETE waitlist_buffer WHERE AND AND table_line->carrid = sdyn_conn-carrid table_line->connid = sdyn_conn-connid table_line->fldate = sdyn_conn-fldate. * No waiting list exists for flight &1 &2 &3! ENDIF.

98

101

SAP AG

114 115 116 117 &3 118 119 120 121 122 123 124 125 126 ELSE. MESSAGE * *

r_waitlist->get_first( ). MESSAGE s007(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate. The first wait end from the waiting list for flight &1 &2 was deleted.

CATCH cx_taw10_empty_list INTO r_exc. text = r_exc->get_text( ). text TYPE 'I'.

ENDTRY.

MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate.

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147

No waiting list exists for flight &1 &2 &3!

ENDIF.

WHEN 'ADD'. IF scustom-id IS INITIAL. MESSAGE s008(taw10). * Please select a valid customer number! EXIT. ENDIF.

READ TABLE waitlist_buffer INTO r_waitlist WITH KEY table_line->carrid = sdyn_conn-carrid table_line->connid = sdyn_conn-connid table_line->fldate = sdyn_conn-fldate. IF sy-subrc = 0. TRY. r_waitlist->add( r_customer ). MESSAGE s010(taw10) WITH scustom-id sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate.

148 149 150 151 152 153

Customer &1 added to the waiting list for flight &2 &3 &4

CATCH cx_taw10_cust_in_list INTO r_exc. text = r_exc->get_text( ). MESSAGE text TYPE 'I'.

ENDTRY. TAW10 15-20

SAP AG

154 155 156 ELSE. MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate. 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 TRY. r_waitlist->delete( r_customer ). MESSAGE s012(taw10) WITH scustom-id sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate. 178 * &2 &3 &4! 179 180 181 182 183 184 185 186 ELSE. MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate. 187 188 189 190 191 192 SAP AG TAW10 15-21 WHEN 'POS'. * No waiting list exists for flight &1 &2 &3! ENDIF. MESSAGE CATCH cx_taw10_cust_not_in_list INTO r_exc. text = r_exc->get_text( ). text TYPE 'I'. Customer &1 was deleted from the waiting list for flight READ TABLE waitlist_buffer INTO r_waitlist WITH KEY table_line->carrid = sdyn_conn-carrid table_line->connid = sdyn_conn-connid table_line->fldate = sdyn_conn-fldate. IF sy-subrc = 0. * WHEN 'DEL'. IF scustom-id IS INITIAL. MESSAGE s008(taw10). Please select a valid customer number! EXIT. ENDIF. * No waiting list exists for flight &1 &2 &3! ENDIF.

ENDTRY.

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 * position &3 218 219 220 221 222 223 224 225 *

DATA pos LIKE sy-tabix. DATA flight TYPE string. DATA fldate(10) TYPE c.

IF scustom-id IS INITIAL. MESSAGE s008(taw10). Please select a valid customer number! EXIT. ENDIF.

READ TABLE waitlist_buffer INTO r_waitlist WITH KEY table_line->carrid = sdyn_conn-carrid table_line->connid = sdyn_conn-connid table_line->fldate = sdyn_conn-fldate. IF sy-subrc = 0.

TRY. r_waitlist->get_pos( EXPORTING IMPORTING im_customer = r_customer ex_pos = pos ).

WRITE sdyn_conn-fldate TO fldate. CONCATENATE sdyn_conn-carrid sdyn_conn-connid fldate INTO flight SEPARATED BY space. MESSAGE i013(taw10) WITH scustom-id flight pos. Customer &1 is on the waiting list for flight &2 at

CATCH cx_taw10_cust_not_in_list INTO r_exc. text = r_exc->get_text( ). MESSAGE text TYPE 'I'.

ENDTRY.

ELSE. MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate.

226 227 228 229 230 231 232 233

No waiting list exists for flight &1 &2 &3! ENDIF.

WHEN 'STATWL' OR 'STATCU' OR 'STATPR'. IF ok_code = 'STATWL'. READ TABLE waitlist_buffer INTO r_waitlist WITH KEY table_line->carrid = sdyn_conn-carrid TAW10 15-22

SAP AG

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 --* 274 ENDMODULE. ENDIF. * * ELSE.

table_line->connid = sdyn_conn-connid table_line->fldate = sdyn_conn-fldate.

IF sy-subrc = 0. r_if_status = r_waitlist.

MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate. No waiting list exists for flight &1 &2 &3! EXIT. ENDIF. ENDIF.

IF ok_code = 'STATCU'. IF scustom-id IS INITIAL. MESSAGE s008(taw10). Please select a valid customer number! EXIT. ENDIF.

r_if_status = r_customer.

IF ok_code = 'STATPR'. r_if_status = r_log. ENDIF.

r_if_status->display_status( ).

WHEN 'LOG'. r_log->display_log( ).

ENDCASE.

" user_command_0100

INPUT

*&------------------------------------------------------------------*& Module check_flight INPUT

SAP AG

TAW10

15-23

275 --* 276 277 --* 278 279 280 281 282 283 284 285 286 287 288 289 290 291 --* 292 293 --* 294 295 --* 296 297 298 299 300 301 302 303 304 305 306 307

*&------------------------------------------------------------------* text

*-------------------------------------------------------------------MODULE check_flight INPUT. SELECT SINGLE * FROM sflight INTO wa_sflight WHERE AND AND carrid = sdyn_conn-carrid connid = sdyn_conn-connid fldate = sdyn_conn-fldate.

IF sy-subrc <> 0. MESSAGE e004(taw10). * Please select a valid flight ENDIF. ENDMODULE. " check_flight INPUT

*&------------------------------------------------------------------*& Module exit INPUT

*&------------------------------------------------------------------* text

*-------------------------------------------------------------------MODULE exit INPUT.

CASE ok_code. WHEN 'CANCEL'. CLEAR: scustom, sdyn_conn. LEAVE TO SCREEN 100. WHEN 'EXIT'. LEAVE PROGRAM.

ENDCASE.

ENDMODULE.

" exit

INPUT

SAP AG

TAW10

15-24

Preparation for Certification

Contents:
l Description of Certification l Example Questions

SAP AG 2003

SAP AG

TAW10

16-1

SAP Consultant Certification


Development Consultant mySAP Technology ABAP Workbench (2003)
Software components: SAP Web Application Server 6.20 Duration of certification: 3 hours Number of certification questions: 80 multiple choice questions Certificates for participants in this certification test: none

Please note that auxiliary materials are not permitted during the certification test (no access to the online documentation and no access to an SAP system).

The Development Consultant mySAP Technology ABAP Workbench (2003) certification test verifies the participants knowledge in the field of the ABAP Workbench consultant profile within mySAP Technology. Participants can use this certificate to prove their basic knowledge in this consultant profile and to implement this knowledge in projects. The certification test contains questions from the following content areas:

Content Areas

1.

mySAP.com technologies (+) mySAP.com Navigation (handling the system) Technical Structure of an SAP System Cross-System Concepts

2. ABAP Workbench Fundamentals (++) Data Types and Data Objects Internal Tables Data Retrieval (Authorization Check) Subroutines The ABAP Runtime System Creating and Calling Function Groups and Function Modules Program Calls and Data Transfer 3. ABAP Objects (++) Classes and Objects Inheritance Casting Interfaces Events Global Classes and Interfaces SAP AG TAW10 16-2

Exception Handling Dynamic Programming

4.

ABAP Dictionary (++) Database Tables: Performance with table accesses Consistency Through Input Check (Foreign Key Dependency) Dependencies with ABAP Dictionary Objects Views Search Help

5.

Techniques of List Processing (++) Outputting Data to Lists Selection Screen Logical Database Internal Data Collection Data Formatting and Control Level Processing Saving Lists and Background Processing Interactive Lists

6.

Dialog Programming (++) Screen (Fundamentals) The Program Interface (GUI Title, GUI Status) Screen Elements for Output (Text Fields, Status Icons and Group Boxes) Input/Output Screen Elements Subscreen and Tabstrip Control Table Control Context Menu Lists in Dialog Programming

7.

Database Updates (+) Database Updates with Open SQL LUWs and Client/Server Architecture SAP Lock Concept Organizing Database Updates Complex LUW Processing Number Assignment Creating Change Documents

8.

Enhancements and Modifications (+) Changing the SAP Standard Personalization Enhancing Dictionary Elements Enhancements Using Customer Exits

SAP AG

TAW10

16-3

Business Transaction Events Business Add-Ins Modifications

Key for certification weighting:

= 1 - 10%

++ = 11 - 20% +++ = More than 20%

SAP AG

TAW10

16-4

Example Questions Exercises


Example questions for the Certification Test Using the Contents of Training Course TAW10 mySAP Technology ABAP Workbench Fundamentals

At the end of this training course you will have an overview of the structure of the Certification Test

Topic: ABAP Fundamentals

Question 1
Which of the following statements enable you to insert an executable program?

Answer 1:
SUBMIT <report>.

Answer 2:
CALL TRANSACTION '<transaction_code>'.

Answer 3:
LEAVE TO TRANSACTION '<transaction_code>'.

Answer 4:
SUBMIT <report> AND RETURN.

Answer 5:
SUBMIT <report> VIA SELECTION-SCREEN.

Answer 1: Incorrect
SAP AG TAW10 16-5

Answer 2: Correct Answer 3: Incorrect Answer 4: Correct Answer 5: Incorrect

SAP AG

TAW10

16-6

Question 2
Which of the following statements about the authorization check in programs are correct?

Answer 1:
The authorization check is performed using the SELECT statement.

Answer 2:
The authorization check is performed using the AUTHORITY-CHECK statement.

Answer 3:
The authorization check checks whether the necessary authorizations are present in the users master record.

Answer 4:
An authorization profile must be specified during the authorization check.

Answer 5:
The system administrator determines which authorization checks are executed.

Answer 1: Incorrect
SAP AG TAW10 16-7

Answer2: Correct Answer3: Correct Answer4: Incorrect Answer5: Incorrect

SAP AG

TAW10

16-8

Question 3
Who triggers (ABAP) events such as START-OF-SELECTION?

Answer 1: Correct
The developer

Answer 2: Correct
The user

Answer 3: Incorrect
The runtime system

SAP AG

TAW10

16-9

Answer 1: Incorrect Answer 2: Incorrect Answer 3: Correct

SAP AG

TAW10

16-10

Topic: ABAP Objects

Question 1
Which classes can be instantiated?

Answer 1:
An abstract class

Answer 2:
A final class

Answer 3:
A class with private attributes

Answer 4:
A class with public attributes

SAP AG

TAW10

16-11

Answer 1: Incorrect Answer 2: Correct Answer 3: Correct Answer 4: Correct

SAP AG

TAW10

16-12

Question 2
Which of the following statements apply in connection with inheritance and visibility?

Answer 1:
Protected components of a class can also be addressed directly by subclasses of this class.

Answer 2:
Private attributes of a class can also be addressed directly by subclasses of this class.

Answer 3:
Private methods of a class can also be called directly by subclasses of this class.

Answer 1: Correct Answer2: Incorrect Answer3: Incorrect


SAP AG TAW10 16-13

Question 3
Which of the following points belong to the event concept in ABAP Objects?

Answer 1:
Trigger event

Answer 2:
Write handling method for the event

Answer 3:
Register the event

Answer 4:
Activate the event

Answer 5:
Define the event

Answer 1: Correct Answer2: Correct Answer3: Correct Answer4: Incorrect Answer5: Correct
SAP AG TAW10 16-14

Das könnte Ihnen auch gefallen