Top Banner
© SAP AG TAW10 0-1 SAP AG 2003 TAW10 Introduction to the ABAP Workbench (2/2) SAP AG TAW10 2/2 TAW10 2/2 ABAP Workbench Fundamentals ABAP Workbench Fundamentals n R/3 System n Release 4.6D or above n 2003/Q2 n Material number 5006 0990
433
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: TAW 10 part 2 of 2

© SAP AG TAW10 0-1

SAP AG 2003

TAW10 Introduction to the ABAP Workbench (2/2)

SAP AG

TAW10 2/2 TAW10 2/2 ABAP Workbench

Fundamentals

ABAP Workbench

Fundamentals

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

Page 2: TAW 10 part 2 of 2

© SAP AG TAW10 0-2

SAP AG 2003

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.

Copyright

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

Page 3: TAW 10 part 2 of 2

© SAP AG TAW10 0-3

SAP AG 2003

Development Consultant mySAP Technology –ABAP Workbench

mySAP Technology- ABAP Workbench Concepts

TAW12 15 days Development consultantcertification –mySAP Technology – ABAP Workbench

TAW10 10 days

mySAP Technology -ABAP Workbench Fundamentals

Page 4: TAW 10 part 2 of 2

© SAP AG TAW10 0-4

SAP AG 2003

Course Prerequisites

Required

l Solid EDP basic knowledge

l Good programming experience in a different programming language

Page 5: TAW 10 part 2 of 2

© SAP AG TAW10 0-5

SAP AG 2003

Target group

??

Target group

Duration

l 10 days

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

Page 6: TAW 10 part 2 of 2

© SAP AG TAW10 0-6

SAP AG 2003

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

Course Goals

Page 7: TAW 10 part 2 of 2

© SAP AG TAW10 0-7

SAP AG 2003

Complex mySAP.com Technologies

Complex ABAP Workbench - Fundamentals

Complex ABAP Objects

Case Study

Course Content: mySAP Technology – ABAP Workbench Fundamentals

Preface

n This SAP Consultant Education training course contains different individual courses (sections), each of which deals with a separate topic

n Each individual course (section) is divided into different units.

Page 8: TAW 10 part 2 of 2

© SAP AG TAW10 1-1

SAP AG 2003

Complex ABAP Objects

Page 9: TAW 10 part 2 of 2

© SAP AG TAW10 1-2

SAP AG 2003

Course Content: ABAP Objects (1)

Unit Data Types and Data Objects in Detail

Unit Using Internal Tables

Unit Introduction to Object-Oriented Programming

Unit Analysis and Design

Unit Principles of Object-Oriented Programming

Unit Inheritance

Unit Casting

Unit Interfaces

Unit Events

Page 10: TAW 10 part 2 of 2

© SAP AG TAW10 1-3

SAP AG 2003

Course Content: ABAP Objects (2)

Unit Global Classes and Interfaces

Unit Special Techniques

Unit Exception Handling

Unit Dynamic Programming

Page 11: TAW 10 part 2 of 2

© SAP AG TAW10 2-1

SAP AG 2002

l Data objects in programs

l Elementary data objects

l Structures

l Character string processing in Unicode

Contents:

Data Types and Data Objects in Detail

Page 12: TAW 10 part 2 of 2

© SAP AG TAW10 2-2

SAP AG 2002

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

At the conclusion of this unit, you will be able to:

Data Types and Data Objects in Detail: Unit Objectives

Page 13: TAW 10 part 2 of 2

© SAP AG TAW10 2-3

SAP AG 2002

Special Features in UnicodeSpecial Features in Unicode

Elementary Data ObjectsElementary Data Objects

StructuresStructures

Data Types and Data Objects in Detail (1)

IntroductionIntroduction

Page 14: TAW 10 part 2 of 2

© SAP AG TAW10 2-4

SAP AG 2002

Revision: Defining Data Objects

Predefined ABAP types

x

Local types

ifstringxstring

td

Global types

cnp

TYPES type_name TYPE ...

DATA do_name TYPE type_name.DATADATA

DATA do_name_new LIKE do_name.DATADATA

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.

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

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

n You can create complex structured types of any level of complexity, based on elementary types. n 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.

Page 15: TAW 10 part 2 of 2

© SAP AG TAW10 2-5

SAP AG 2002

string

Predefined ABAP Types

p

if

ncdt

x

xstring

Data typeNumeric

4

81 .. 16

Integer

Float. point numberPacked number

Character string type / hexadecimal

Fixe

d le

ngth

Description Length in bytes

Number sequence

Character sequenceDate

Time

Hexadecimal code

Character sequence

Hexadecimal code

1 .. 65535

1 .. 65535 8

6

1 .. 65535

Differ in:

• Rules for storage

• Value range• Arithmetic used

Bit operations

Character string type

Hexadecimal

Runtime system adjusts length dynamically

Character string operations (allowed for all types)

+ date calculations+ time calculations

Attributes

Var

iab

le

len

gth

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

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

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

Page 16: TAW 10 part 2 of 2

© SAP AG TAW10 2-6

SAP AG 2002

Type Groups in the ABAP Dictionary

Type group zmytp

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

Using a constant:

TYPE-POOLS: zmytp.

[ DATA var TYPE zmytp_type1. ]

IF var = zmytp_const_name....

ENDIF.

zmytpzmytpzmytpzmytp

zmytpzmytpzmytpzmytp

zmytpzmytp

zmytpzmytp

Name of type group: Up to 5 characters;

each type name andconstant name

starts with the name ofthe type group.

TYPETYPE--POOLSPOOLS

Each type group, whosetypes and constants you

want to use, must be specified in the ABAP program

ABAP program

zmytpzmytp

n You must use a type group to define global constants. The name of the type group can contain up to 5 characters.

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

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

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

Page 17: TAW 10 part 2 of 2

© SAP AG TAW10 2-7

SAP AG 2002

Data Types and Data Objects in Detail (2)

Special Features in UnicodeSpecial Features in Unicode

Elementary Data ObjectsElementary Data Objects

StructuresStructures

IntroductionIntroduction

Page 18: TAW 10 part 2 of 2

© SAP AG TAW10 2-8

SAP AG 2002

Integer auxiliary variable

1

int2 = 4 int3 = 3 int4 = 2

24 3 += /

2+ 3= =

int1

Integers and Integer Arithmetic

+-*/DIVMOD**

AdditionSubtractionMultiplicationDivisionInteger divisionRemainder integer div.Power

Arithmetic operations for integers:

int1 = int2 / int3 + int4.

DATA: counter TYPE i VALUE 1. l Length: 4 bytes

l Value range [-2147483648; 2147483647]

l Integer Arithmetic

§ All internal auxiliary fields are integers

§ Interim results are rounded

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

n Calculations performed using integer arithmetic are faster than calculations using fixed point or floating point arithmetic.

n For further information on calculations performed on integers, refer to the keyword documentation for the COMPUTE statement.

Page 19: TAW 10 part 2 of 2

© SAP AG TAW10 2-9

SAP AG 2002

Packed Numbers and Fixed Point Arithmetic

0 1 2 3 4 +

1 digit per half-byte

Sign

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

Length in bytes:n bytes correspond to

2n - 1 digits

Number of decimal places

12,34Number

Fixed point arithmetic: "like using paper and pencil"

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]

Internal representation

1234,56+ 78,5

1313,06

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.

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

n In user dialogs, decimal numbers are formatted according to the settings in the user master record. n 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".

n The system always uses packed numbers of maximum length for interim results. n 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.

Page 20: TAW 10 part 2 of 2

© SAP AG TAW10 2-10

SAP AG 2002

Λ

Λ

Λ

Λ

Λ

Λ

Λ

1499023437,0

1494140625,0

1484375,0

140625,0

125,0

20481

10241

1281

641

81

212 121212115,0

21

21215,1

1110763

10

1

=

+=

+=

+=

+=

+++++=

+×+×+×+×+×=

+=

×+×=

-----

-

Floating Point Arithmetic

| |

| | | | |0 0 0 0 . . .

Only 53 bits available

Only forapproximations

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

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

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

Page 21: TAW 10 part 2 of 2

© SAP AG TAW10 2-11

SAP AG 2002

Summary: Recommendations for Using Numeric Data Types

Required:Required: Recommended predefined ABAP data type:Recommended predefined ABAP data type:

Integers onlyType i,

since calculations using integer arithmetic are fastest

Decimal numbers for business calculations Type p

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

Type F

n 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

Page 22: TAW 10 part 2 of 2

© SAP AG TAW10 2-12

SAP AG 2002

Arithmetic and Mixed Expressions

ca br = / +

p DECIMALS 3 i i f

0.0000...E+000201 200/ +

→ Float. point arithmetic�

↓Conversion after f

and calculation

0.0000...E+0001.004999...E+000

Interim result:

+ = 1.004999...E+000

↓Conversion after p DECIMALS 3

�1.005

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:

n An arithmetic expression may contain any data types that are convertible into each other and into the type of the result field.

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

n This may mean that the same arithmetic expression leads to different results when performed on different combinations of data types.

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

n 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

Page 23: TAW 10 part 2 of 2

© SAP AG TAW10 2-13

SAP AG 2002

Predefined ABAP Types for Character Strings

Description

Length

Value range

Calculations

Formatting options

1 .. 1 .. 65535 65535 characterscharacters

1 .. 65535 characters

8 digitsYYYYMMDD

6 digitsHHMMSS

Depends onDepends on codepagecodepageBy GregoriancalendarBy clock

Type Type ccType nType dType t

Time Date Sequence of digits

FixedFixed--length length char. stringchar. string

Date arithmetic

Time arithmetic

Based on user default values

HH:MM:SS

Digits

VariableVariable

Type Type stringstring

Char. string Char. string of variable of variable lengthlength

Conversion Conversion ConversionConversion

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.

n The initial value of each character string with fixed length is a space character. n 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.

n The initial value of each character in a numeric string is a zero. n 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.

n The initial value of a date is '000000'. The formatting options are determined by the user settings. n 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. n The initial value of a time is '000000'.

Page 24: TAW 10 part 2 of 2

© SAP AG TAW10 2-14

SAP AG 2002

Overview: Character String Processing

REPLACEREPLACE

TRANSLATETRANSLATE

SHIFTSHIFT

CONDENSECONDENSE

FINDFIND

SPLITSPLIT

CONCATENATECONCATENATE +

OVERLAYOVERLAY

Description and notes

Search in a character string

Replace

Move

Remove space characters

Overwrite : Spaces are overwritten by characters from the second character string

Concatenate several character strings

Split a character string

A B A P

A B A P a b a p

A B A P B A P

B B A P

A P A P

A B A B A PA P

A B PA B A P

A B A P

A A A A

Search in a character stringSearch in a character string

Replace first occurrenceReplace first occurrence

MoveMove

RemoveRemove

Overwrite Overwrite

ConcatenateConcatenate

SplitSplit

Replace all occurrencesReplace all occurrences

A B C A P

A B A PB ?Found: sy-subrc = 0

Position of search stringusing MATCH OFFSET off addition

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.

n For every statement, the operands are treated like type c fields, regardless of their actual field type. No internal type conversions take place.

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

n All of the statements apart from SEARCH are case-sensitive. n To find out the occupied length of a string, use the standard function STRLEN(). n 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.

Page 25: TAW 10 part 2 of 2

© SAP AG TAW10 2-15

SAP AG 2002

Accessing Parts of Fields

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

REPORT ...

PARAMETERS:pa_str(40) LOWER CASE,pa_pos TYPE i,pa_len TYPE i.

WRITE pa_str+pa_pos(pa_len). 19991231ttA235959

000000

Possible with anycharacter-type field

++papa__pospos((papa__lenlen))

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

Page 26: TAW 10 part 2 of 2

© SAP AG TAW10 2-16

SAP AG 2002

Special Features in UnicodeSpecial Features in Unicode

Elementary Data ObjectsElementary Data Objects

StructuresStructures

Data Types and Data Objects in Detail (3)

IntroductionIntroduction

Page 27: TAW 10 part 2 of 2

© SAP AG TAW10 2-17

SAP AG 2002

Defining Structures with Local Types

TYPES:BEGIN OF s_name_type,prename(25) TYPE c,surname(25) TYPE c,title(5) TYPE c,

END OF s_name_type.

DATA:s_name TYPE s_name_type .

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

DATA:DATA:

TYPES:TYPES:

BEGIN OFBEGIN OF

END OFEND OF

BEGIN OFBEGIN OF

END OFEND OF

DATA:DATA:

START-OF-SELECTION.s_name-prename = 'Smith'.s_name-surname = 'John'.

s_name

s_name

s_name

s_name

Alternatives

s_name_type

s_name_type

s_name--

Definition of a structure type

Definition of a structure with reference to a user-defined type

Definition of a structure with implicit type construction

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.

n In both cases, the type is defined locally. Bear in mind that you can also use globally defined types instead.

n You address components of structures using: structure_name-comp_name. For this reason, you should avoid using hyphens in variable names.

Page 28: TAW 10 part 2 of 2

© SAP AG TAW10 2-18

SAP AG 2002

Defining Nested Structures with Local Types

Nested structureNested structure

Structure typeStructure type

name

streetcity

prenamesurnametitle

s_address

s_name_typeprenamesurnametitle

TYPES:BEGIN OF 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,street(15) TYPE c,city(25) TYPE c,

END OF s_address.

s_address-name-surname = 'Smith'.

s_address-city = 'London'.

s_name_type

-- --

--

s_name_type

Application: Logical subgrouping

of data

n You can define nested structures by assigning a structure type to a component within a structure type. n You can address this substructure as a whole using the component name: structure_name-substructure_name.

n You can also address individual components in the substructure: structure_name-substructure_name-comp_name.

n Structures can be nested to any level you wish. n 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.

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

Page 29: TAW 10 part 2 of 2

© SAP AG TAW10 2-19

SAP AG 2002

Using Named Includes

DATA:BEGIN OF t_linetype,

prename(25) TYPE c,surname(25) TYPE c,title(5) TYPE c,

END OF s_name_type.

DATABEGIN OF s_address.

INCLUDE STRUCTURE s_name_typeAS name.

DATA:street(15) TYPE c,city(25) TYPE c,

END OF s_address.

s_address-name-surname = 'Smith'.* or: s_address-surname = 'Smith'.

s_name_type

s_name_typeINCLUDE STRUCTUREINCLUDE STRUCTUREASAS

Structure with named includeStructure with named include

Structure typeStructure type

streetcity

prenamesurnametitle

s_address

s_name_typeprenamesurnametitle

name

-- --

--Use:

Logical subgroup desired, but nested structures not technically possible

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

Page 30: TAW 10 part 2 of 2

© SAP AG TAW10 2-20

SAP AG 2002

Special Features in UnicodeSpecial Features in Unicode

Elementary Data ObjectsElementary Data Objects

StructuresStructures

Data Types and Data Objects in Detail (4)

IntroductionIntroduction

Page 31: TAW 10 part 2 of 2

© SAP AG TAW10 2-21

SAP AG 2002

Unicode: Overview

Solution: Unicode

l ONE codepage that comprises all known characters

l Every character is generally displayed by two bytes

a

??

?

S

aUnicodeUnicode

Previous problems

l Mixture of different incompatible character sets in one central system

l Data exchange between systems with incompatible character sets

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

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

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

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

Page 32: TAW 10 part 2 of 2

© SAP AG TAW10 2-22

SAP AG 2002

Character-Type and Byte-Type Types

Character-type types in Unicode programs

d

tstring

xstring

x

c nCharacter-typestructure types

Difference between byte processing and character processing

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.

c_field x_field

H U G O

E391B9A2

B9A20000

G O _ _

Only components with the types c, n, d, and t

byte-typebyte-type

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.

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

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

n The X variants of the string statement are distinguished from the character string commands by the IN BYTE MODE addition. For the character string variants, 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.

Page 33: TAW 10 part 2 of 2

© SAP AG TAW10 2-23

SAP AG 2002

Functions and Comparison Operators

Functions

Character-type type

XSTRLEN

Byte-type type

Comparison operators

Functions STRLEN

CO, CA, CS, CP,

CN, NA, NS, NP

BYTE-CO, BYTE-CA,

BYTE-CS, BYTE-CN,

BYTE-NA, BYTE-NS

STRLEN

DATA: c_fld1(4) TYPE c VALUE 'HUGO',c_fld2(1) TYPE c VALUE 'G'.

IF c_fld1 CA c_fld2....

ENDIF.

DATA: x_field(4) TYPE xVALUE 'E391B9A2',

len TYPE i.

len = XSTRLEN( x_field ).

Length in bytes

Examples:

Length in characters

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

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

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

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

Page 34: TAW 10 part 2 of 2

© SAP AG TAW10 2-24

SAP AG 2002

Compatibility and Conversion

l No conversion takes place if type-compatible data objects are assigned

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

When are two types compatible?

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

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

typetype lengthlength

decimal placesdecimal places

same structuresame structure components are compatiblecomponents are compatible

row typesrow typeskey definitionskey definitions table typestable types

are the same.are the same.

MOVE a TO b.b = a.

compatiblecompatiblecompatiblecompatible

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.

n For a full list of all conversion rules, refer to the ABAP syntax documentation for the MOVE statement.

n If there is no conversion rule defined for a particular assignment, the way in which the system reacts depends on the program context.

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

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

Page 35: TAW 10 part 2 of 2

© SAP AG TAW10 2-25

SAP AG 2002

Conversion Under Unicode (1)

Conversion between flat structures

struc2

MOVE struc1 TO struc2.

Decisive criterion: Fragment view

IX(3)C(3)C(4) C(3) C(4)

struc1C(6) N(4) X(3) N(4) I P(8)

struc1

struc2

P(8)IC(4)X(3)C(10)

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.

Under what condition is this assignment possible?

Assignment is possible ⇐

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

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

n To check whether the conversion is even permitted, the system first creates the Unicode fragment view of the structures by grouping adjacent components and alignment gaps (one group each for character-type types [c, n, d, t], byte-type types, and types i, f, and p).

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

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

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

Page 36: TAW 10 part 2 of 2

© SAP AG TAW10 2-26

SAP AG 2002

Conversion Under Unicode (2)

Conversion between structures and single fields

struc

MOVE c_field TO struc.

X(3)N(4)C(6) C(4)

c_field

C(9)

c_field

struc

.

Under what condition is this assignment possible?

Assignment is possible ⇐

Decisive criterion: Fragment view

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.

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.

Page 37: TAW 10 part 2 of 2

© SAP AG TAW10 2-27

SAP AG 2002

Example of Using the Conversion Rules

PARAMETERS p_date LIKE sy-datum.DATA: BEGIN OF s_date,

year(4) TYPE n,month(2) TYPE n,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 s_date

Character-typesingle field

Character-typestructure

l Since the structure s_date is purely character-type, it is treated like a type c data object during conversion.

l This means it is transferred left-aligned, character by character.

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

Page 38: TAW 10 part 2 of 2

© SAP AG TAW10 2-28

SAP AG 2002

Offset and Length Accesses and Elementary Data Objects

Access to single fields specifying offset and length

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

.

l For character-type fields, offset and length are interpreted character by character.

l In the case of byte-type fields, the values for offset and length are taken in bytes.

DATA: c_field(6) TYPE c VALUE '*ABAP#',

x_field(6) TYPE x VALUE 'E391B9A203F6'.

WRITE: c_field+1(4),

x_field+3(2).

x_field

E391B9A203F6

c_field

* A B A P #

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.

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

Page 39: TAW 10 part 2 of 2

© SAP AG TAW10 2-29

SAP AG 2002

Offset and Length Accesses and Structures

Accessing structures by specifying offset and length

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

l Structure must start with a character-type fragment.

l Access is only allowed within the character-type initial part.

l Offset and length specifications are interpreted as characters.

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

END OF member.

PERFORM use_name USING member+5(30).

memberC(5) C(15) C(15) I C(20)

+off(len)

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.

n If an offset/length access is allowed in a Unicode program, both offset and length specifications are interpreted as characters.

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

Page 40: TAW 10 part 2 of 2

© SAP AG TAW10 2-30

SAP AG 2002

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

You are now able to:

Data Types and Data Objects in Detail: Summary

Page 41: TAW 10 part 2 of 2

© SAP AG TAW10 2-31

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: ZBC401_##_SPLIT_STRING

Template: SAPBC401_DTOT_SPLIT_STRING

Model solution: SAPBC401_DTOS_SPLIT_STRING ## is your two-digit group number

1-1 Copy the program, SAPBC401_DTOT_SPLIT_STRING and give it the new name ZBC401_##_SPLIT_STRING.

1-2 Familiarize yourself with the main body of the program. Pay special attention to the content of the data object datastring after the function module call. Use the Debugger to do this, and/or display the character string in a list. (The function module itself is here seen as a black box. For this exercise, it is not necessary to understand its construction.)

1-3 To be able to split the character string into its components you must first remove the ## characters. Remove the two leading separators from the character string first. Then copy the initial part up to the closing separators to the auxiliary variable set_string. For this, set_string has to be defined appropriately.

Page 42: TAW 10 part 2 of 2

© SAP AG TAW10 2-32

1-4 Now use the separators to split the contents of the auxiliary variable set_string into the structure wa_flight_c. The latter is typed with the local program structure type st_flight_c. You still have to comment out the components of this structure type and assign them an appropriate type.

1-5 As a test, display the fields of the structure, wa_flight_c in a list.

1-6 In the list displayed in exercise 1-5, you should have observed that some of the fields were displayed without formatting – for example, the PRICE field. Your next step is to change this. To do this, convert the data you have extracted by copying it to data objects with suitable types. Also, not all components of wa_flight_c are to be displayed. For this purpose, a structure wa_flight has already been defined. It is typed with the structure type st_flight. You must comment out the components of st_flight and find appropriate types for these components for the formatting. Then copy the identically-named components of the character-type structure wa_flight_c to the fields of the structure wa_flight. Display the contents of the structure wa_flight in a list. Use the appropriate formatting options for the WRITE statement for the fldate and price components.

Page 43: TAW 10 part 2 of 2

© SAP AG TAW10 2-33

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

TYPES:

BEGIN OF st_flight_c,

mandt(3) TYPE c,

carrid(3) TYPE c,

connid(4) TYPE n,

fldate(8) TYPE n,

price(20) TYPE c,

currency(5) TYPE c,

planetype(10) TYPE c,

seatsmax(10) TYPE n,

seatsocc(10) TYPE n,

paymentsum(22) TYPE c,

seatsmax_b(10) TYPE n,

seatsocc_b(10) TYPE n,

seatsmax_f(10) TYPE n,

seatsocc_f(10) TYPE n,

END OF st_flight_c,

BEGIN OF st_flight,

carrid(3) TYPE c,

connid(4) TYPE n,

fldate TYPE d,

price(9) TYPE p DECIMALS 2,

currency(5) TYPE c,

planetype(10) TYPE c,

seatsmax TYPE i,

seatsocc TYPE i,

END OF st_flight.

DATA:

datastring TYPE string,

Page 44: TAW 10 part 2 of 2

© SAP AG TAW10 2-34

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 = '1'

* IM_TABLE_NAME = 'SFLIGHT'

* IM_SEPARATOR = '#'

* IM_UNIQUE = 'X'

IMPORTING

ex_string = datastring

EXCEPTIONS

no_data = 1

OTHERS = 2.

IF sy-subrc <> 0.

MESSAGE a038(bc401).

ENDIF.

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

Page 45: TAW 10 part 2 of 2

© SAP AG TAW10 2-35

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.

Page 46: TAW 10 part 2 of 2

© SAP AG TAW10 3-1

SAP AG 2002

l Introduction and advantages of internal tables

l Defining internal tables

l Internal table operations

l Notes on performance

l Special internal tables

Contents:

Using Internal Tables

Page 47: TAW 10 part 2 of 2

© SAP AG TAW10 3-2

SAP AG 2002

Using Internal Tables: Unit Objectives

l Define internal tables

l Perform operations on internal tables

l Identify table kinds and use them appropriately in different situations

At the conclusion of this unit, you will be able to:

Page 48: TAW 10 part 2 of 2

© SAP AG TAW10 3-3

SAP AG 2002

Using Internal Tables (1)

Introduction and advantages of internal tablesIntroduction and advantages of internal tablesIntroduction and advantages of internal tables

DefinitionDefinition

OperationsOperations

Special situationsSpecial situations

Notes on performanceNotes on performance

Page 49: TAW 10 part 2 of 2

© SAP AG TAW10 3-4

SAP AG 2002

The Internal Table - a Data Object of Variable Length

ABAPprogramElementary data objects

Structures

Internal table

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

Static data objects(except fortypes STRING, XSTRING)

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.

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

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

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

Page 50: TAW 10 part 2 of 2

© SAP AG TAW10 3-5

SAP AG 2002

Attributes of Internal Tables

Line typeLine type

AA 0017 2.572 MI

QF 0005 10.000 MI

UA 0007 2.572 MI

LH 0402 5.136 KM

LH 0400 6.162 KM

Table kindTable kindStandard tableStandard tableSorted tableSorted tableHashed tableHashed table

Key definitionKey definition((Key fieldsKey fields((SequenceSequence((UniquenessUniqueness

CARRIDCARRID CONNIDCONNID DISTANCEDISTANCE DISTIDDISTID

1

Lineindex

Index access2

Key access

SQ 0866SQ 0866SQ 0866 1.625 MI

2

3

4

5

6

n 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 non-unique . 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).

Page 51: TAW 10 part 2 of 2

© SAP AG TAW10 3-6

SAP AG 2002

Link Between Table Kind and Access Type

Index access

Key access

Uniqueness NON- UNIQUE UNIQUE | NON-UNIQUE UNIQUE

Access by Mostly index Mostly key Key only

HASHED TABLEHASHED TABLESTANDARD TABLESTANDARD TABLE SORTED TABLESORTED TABLE

Link Between Table Kind and Access Type

n

Index tables Hashed table

Table kind

Table scanTable scan Binary Binary searchsearch

Hash Hash functionfunction

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.

Page 52: TAW 10 part 2 of 2

© SAP AG TAW10 3-7

SAP AG 2002

Using Internal Tables (2)

Introduction and advantages of internal tablesIntroduction and advantages of internal tables

DefinitionDefinitionDefinition

OperationsOperations

Special situationsSpecial situations

Notes on performanceNotes on performance

Page 53: TAW 10 part 2 of 2

© SAP AG TAW10 3-8

SAP AG 2002

Overview: Types of Definitions for Internal Tables

With local table typeWith local table type Implicit table typeImplicit table type With global table typeWith global table type

TYPES:local_type ...

DATA:t_list TYPE

local_type.

DATA:t_list TYPE ...

DATA:t_list TYPE

global_type.Tableattributes

local_typelocal_type global_typeglobal_type

Local table type

Internal table Internal table Internal table

Tableattributes

Global table type

local_typelocal_type global_typeglobal_type

Tableattributes

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

Page 54: TAW 10 part 2 of 2

© SAP AG TAW10 3-9

SAP AG 2002

The Data Type of an Internal Table

name TYPE table_type

OF line_type

WITH key_def

[ INITIAL SIZE n ].

TYPETYPE table_kindtable_kind

OFOF

WITHWITH key_key_defdef

INITIAL SIZEINITIAL SIZE

( Table kind

( Line type (columns)

( Key

( Initial size (optional)

Local table type/internal tableLocal table type/internal table

TYPES or DATA Attributes

Global table typeGlobal table type

global_type

Input on screen usedto specify attributes

( Table kind

( Line type (columns)

( Key

Attributes

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.

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

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

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

Page 55: TAW 10 part 2 of 2

© SAP AG TAW10 3-10

SAP AG 2002

Table Attribute: Line Type

TYPES:BEGIN OF line_type,...

END OF line_type.

Global structure type

line_typeline_type line_typeline_type

Local structure type

DATA:

structure TYPE ...structurestructure

Local structure

Line typeLine type

... name TYPE table_kind

OF line_type

WITH key_def

[ INITIAL SIZE n ].

TYPETYPE

line_typeline_typeOFOF

... name LIKE table_kind

OF structure

WITH key_def

[ INITIAL SIZE n ].

structurestructure

LIKELIKE

Table typeTable type

DATADATATYPESTYPES

OFOF

n To specify the line type of an internal table, you can use all the local and global data types or data objects.

n Internal tables are most frequently used to display contents of the database tables. Normally, non-nested structured data types are used for this.

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

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

Page 56: TAW 10 part 2 of 2

© SAP AG TAW10 3-11

SAP AG 2002

Table Attribute: Table Kind and Key

TYPES:itabtype TYPE table_kind

OF line_type

WITH key_def

[ INITIAL SIZE n ].DATA: t_name TYPE itabtype.

table_kindtable_kind

WITHWITH key_defkey_def

table_kindtable_kind key_defkey_def

STANDARD TABLE

SORTED TABLEHASHED TABLE

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

{UNIQUE | NON-UNIQUE} KEY col1 ...colnUNIQUE KEY col1 ... coln

n There are three parameters that you use to specify a table kind for your internal table: STANDARD TABLE, SORTED TABLE and HASHED TABLE

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

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

Page 57: TAW 10 part 2 of 2

© SAP AG TAW10 3-12

SAP AG 2002

Example: Standard Table with Local Type

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

TYPES: tt_distance_ty TYPE STANDARD TABLE

OF s_distance_tyWITH NON-UNIQUE KEY distance distid.

DATA:tt_distance TYPE tt_distance_ty.

Line type:

Table type:

Internal table

Internal tableInternal tableof the table kindof the table kindSTANDARD TABLESTANDARD TABLE

s_distance_tys_distance_ty

tttt_distance_distance

tt_distance_tytt_distance_ty

tttt_distance__distance_tyty

s_distance_tys_distance_ty

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

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

n The distance and distid fields are key fields. The key is not unique.

Page 58: TAW 10 part 2 of 2

© SAP AG TAW10 3-13

SAP AG 2002

Example: Sorted and Hashed Table

DATA: distance_rancTYPE SORTED TABLEOF s_distance_tyWITH NON-UNIQUE KEYdistid distance.

Sorted table

distance_rancdistance_ranc

DATA:distance_bufferTYPE HASHED TABLEOF s_distance_tyWITH UNIQUE KEY

carrid connid.

Hashed table:

distance_bufferdistance_buffer

LHLHAA QM

0402040000170005

6.1626.1622.57210.000

KMKMMIMI

carrid connid distance distid

12

1234

LHAAQMLH

0400001700050402

6.1622.57210.0006.162

KMMIMIKM

carrid connid distance distid

1 2

Sequence

Sequence

Sequence

s_distance_tys_distance_ty

s_distance_tys_distance_ty

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.

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

Page 59: TAW 10 part 2 of 2

© SAP AG TAW10 3-14

SAP AG 2002

The Standard Table Type

DATA:t_name TYPE TABLE

OF line_type.

TABLETABLE

DATA:t_name TYPE STANDARD TABLE

OF line_type

WITH DEFAULT KEY .

STANDARD

WITH DEFAULT KEY

TYPETYPE

OFOF

Interpreted bythe system as:

Definition bystandard table type

DATA:

t_sflight TYPE TABLE OF sflight.

Example:

TYPE TABLE OFTYPE TABLE OF

TYPETYPE TABLETABLE

OFOF

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

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

n Incomplete table types are known as generic . You can only use them to assign types to table-type interface parameters.

Page 60: TAW 10 part 2 of 2

© SAP AG TAW10 3-15

SAP AG 2002

Internal Tables with an Unstructured Line Type

DATA:

it_fields TYPE STANDARD TABLE OF dd03l-fieldname

WITH KEY table_line,

wa_field TYPE dd03l-fieldname.

SELECT fieldname FROM dd03l "table of transp. tables

INTO TABLE it_fields

WHERE tabname = 'SPFLI'.

tabletable__lineline

Definition:

Fill:

READ TABLE it_fields INTO wa_field

WITH KEY table_line = 'CITYFROM'.

Key access:

tabletable__lineline

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.

n To declare an explicit key, you must use the pseudo-component table_line. n 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)

n You can use a key access, for example, to ascertain whether a specific entry exists .

Page 61: TAW 10 part 2 of 2

© SAP AG TAW10 3-16

SAP AG 2002

Using Internal Tables (3)

Introduction and advantages of internal tablesIntroduction and advantages of internal tables

DefinitionDefinition

OperationsOperationsOperations

Special situationsSpecial situations

Notes on performanceNotes on performance

Page 62: TAW 10 part 2 of 2

© SAP AG TAW10 3-17

SAP AG 2002

Overview: Types of Operation

Internal tableInternal tableas a data objectas a data object

Operations on one orOperations on one ormore linesmore lines

Editing linesEditing linesin a loopin a loop

or

(Copy ( MOVE )

( Initialize ( CLEAR )Keep memory available

( Initialize ( FREE )Release memory

(Compare using operators

=,<>,><,<=,<=,>,<

(Sort ( SORT )

(Array Fetch ( SELECT ...INTO TABLE )

( Insert ( INSERT )

( Read ( READ )

( Change ( MODIFY )

( Delete ( DELETE )

( Insert summated

( COLLECT )

(Edit linessequentially

LOOP ...* command blockENDLOOP.

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.

Page 63: TAW 10 part 2 of 2

© SAP AG TAW10 3-18

SAP AG 2002

Limiting the Scope of Line Operations: Target Records and Access Type

n

<condition>

[ n1 ... n2 ]

Table key

Line index (for index tables)

Condition applied to any number of columns

Index interval (for index tables)

Work area

Copying processCopying processDirect access byDirect access bydereferenceddereferenced pointerpointer

Field symbol

InsertInsertusing tableusing table

Table

Specify set of target recordsSpecify set of target records

Specify access type / data transfer typeSpecify access type / data transfer type

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.

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

n In particular, when you insert table lines, you can pass the data to be inserted using another internal table.

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

Page 64: TAW 10 part 2 of 2

© SAP AG TAW10 3-19

SAP AG 2002

Preview: Field SymboIs (1)

4var_a

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

Data objects in the ABAP program

FIELDFIELD--SYMBOLSSYMBOLS

ASSIGN var_a TO <fs>.

<fs> = 77.

var_a

<fs>

var_a

<fs>

4

77

Time

ASSIGNASSIGN TOTO

Defining a field symbol:

Assigning a data object to a field symbol:

Assigning a value to a data objectusing a field symbol:

n You can create a pointer to a data object in ABAP using a field symbol. n 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).

n Note that the angle brackets (<>) are part of the name of the field symbol: In this example, the name is <fs>.

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

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

n You can "redirect" a field symbol to a different data object at runtime using the ASSIGN statement.

Page 65: TAW 10 part 2 of 2

© SAP AG TAW10 3-20

SAP AG 2002

Preview: Field SymboIs (2)

DATA: it_sflight TYPE TABLE OF sflight.

FIELD-SYMBOLS: <fs> TYPE sflight.

Data objects in the ABAP programDefining the field symbol:

Accessing the line content using the field symbol:

<fs>

it_sflight

Assigning a line to the field symbol:

* ... to be continued ...

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

<fs>

it_sflight

<fs>

it_sflight

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.

n After a field symbol has been assigned a line, it is also possible to access the individual column values of the assigned line.

n As well as being able to read the data contents, you can also change the contents of the individual components.

Page 66: TAW 10 part 2 of 2

© SAP AG TAW10 3-21

SAP AG 2002

Insert

wa

itab* fill workarea "wa"

INSERT wa INTO TABLE itab.INSERTINSERT INTO TABLEINTO TABLE

wa

itab* fill workarea "wa"

INSERT wa INTO itab INDEX n.INSERTINSERT INTOINTO INDEXINDEXn n

itab1 itab2INSERT LINES OF itab1

[ FROM n1 TO n2 ]target.[n1]

[n2]

Only if itab1 isan index table

INSERT LINES OFINSERT LINES OF

INTO TABLE itab2.

INTO itab2 [ INDEX n ].n

targetn

INTO TABLEINTO TABLE

INTOINTO

Key from "wa" specifies the line

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

Page 67: TAW 10 part 2 of 2

© SAP AG TAW10 3-22

SAP AG 2002

Reading a Single Record into a Work Area Using the Line Number

Indexwa

itab

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

n n

INTOINTO

( f1 ... fm( ALL FIELDS

[ options ]COMPARING comp_list

TRANSPORTING trans_list

COMPARINGCOMPARING

TRANSPORTINGTRANSPORTING

( f1 ... fk( NO FIELDS

comp_list

trans_list

Beliebige FeldlisteAny field list

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

n Use the option TRANSPORTING addition to specify the columns for which you want to transport data: � If you do not want to read any data, but simply want to ascertain whether or not line n exists

(evaluating the return value sy-subrc), use the TRANSPORTING NO FIELDS addition. � If you want to read some of the columns in the line only, specify them after TRANSPORTING.

Separate each column name with a space. n You can use the optional addition COMPARING f1 ... fm to ascertain whether or not the line to

be read n has specific column contents: To do this, copy the value of all columns that point to the records you want to read, into wa and list the columns after the COMPARING addition to the READ statement. If the system was able to read the line and if all the columns listed contain the values stored in wa, it sets the return code sy-subrc to zero. If the system was able to read the line, but if one or more of the columns does not contain the value stored for it in wa, it sets the return code sy-subrc to two. If it could not read the line, it sets the return code to greater than two.

n The COMPARING ALL FIELDS addition provides a shorter syntax for comparing all the columns.

Page 68: TAW 10 part 2 of 2

© SAP AG TAW10 3-23

SAP AG 2002

Reading a Single Record into a Work Area Using the Field Contents

Key

READ TABLE itab search_clause INTO wa [ options ].

wa

itab wa1Table key from wa1

Explicit table key

READ TABLEREAD TABLE

Table key FROM wa1

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

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

Any content from field list

INTOINTO

search_clause

Any fieldcontents

As in index access

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.

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

n You can specify a formulated search condition to be applied to any columns using READ TABLE itab WITH KEY ....

n However, you can only use dynamically formulated read accesses using the key and the READ TABLE itab FROM wa statement.

Page 69: TAW 10 part 2 of 2

© SAP AG TAW10 3-24

SAP AG 2002

Reading a Single Record Using a Field Symbol

Index

Key

n

itab

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

READ TABLE itab ASSIGNING <fs>.

WRITE: / <FS>-field_1, ...

<fs>

n Index

Key

or

ASSIGNINGASSIGNING << >>READ TABLEREAD TABLEINDEX n

key

INDEXINDEX

<fs><fs>--field_1field_1

Same as when reading into a work area

n You can use either a work area or a field symbol to access the individual lines in a table you want to read.

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

n Set the pointer to the correct line using the ASSIGNING <fs> addition instead of INTO. You can use any search criterion you want.

n You can access the components of the structure directly using the component names in the line type: � You can directly address elementary components in the line type using <fs>-field_1. � If the line type contains structured components (a structure or internal table), <fs>-component_name points to the entire structured component. To access the sub-components of this structured component, you need another field symbol.

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

Page 70: TAW 10 part 2 of 2

© SAP AG TAW10 3-25

SAP AG 2002

Changing the Table Using a Work Area

wa

itab * fill workarea "wa"

MODIFY itab FROM wa INDEX n

[ TRANSPORTING f1 ... fn ].

n

wa

itab* fill workarea "wa"

MODIFY TABLE itab FROM wa

[ TRANSPORTING f1 ... fn ].

MODIFYMODIFY FROMFROM INDEXINDEX

TRANSPORTINGTRANSPORTING

MODIFY TABLEMODIFY TABLE FROMFROM

TRANSPORTINGTRANSPORTING

n

MODIFY itab FROM wa

TRANSPORTING f1 f2 ...

WHERE log_expr.

MODIFYMODIFY FROMFROM

TRANSPORTINGTRANSPORTING

WHEREWHERE

wa

itab

WHERElog_expr.

Key from "wa" specifies the line

n The MODIFY TABLE itab FROM wa statement allows you to change the content of one line of the internal table itab. The runtime system specifies the line to be changed using the key values from the work area wa and changes the non-key fields using the other fields. If your table has a non-unique key, the system changes the first entry only (using a linear search algorithm in STANDARD tables, and a binary search algorithm in SORTED tables). If you want to change only some of the fields (that is, columns) in a line, you must specify these after TRANSPORTING.

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

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

Page 71: TAW 10 part 2 of 2

© SAP AG TAW10 3-26

SAP AG 2002

Changing a Single Record Using a Field Symbol

Index

Key

n

itab

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

READ TABLE itab ASSIGNING <fs>.

<FS>-field_1 = ...

<fs>

n Index

Key

or

ASSIGNINGASSIGNINGREAD TABLEREAD TABLEINDEX n

key

<<fsfs>>--field_1field_1

<fs>-field_1 = ...

1

2

1

2

Cannot be key field in sorted or hashed tables

Same as when reading into a work area

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

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

n Note that you cannot change key fields in SORTED or HASHED tables. - trying to do so causes a runtime error.

Page 72: TAW 10 part 2 of 2

© SAP AG TAW10 3-27

SAP AG 2002

Delete

itab

DELETE itab INDEX n.n

itab

* fill workarea "wa"

DELETE TABLE itab key.wa

Explicit

DELETEDELETE INDEXINDEX

DELETE TABLEDELETE TABLE

( FROM wa( WITH TABLE KEY

k1 = f1 ... kn = fn

Table key

DELETE itab WHERE log_expr.DELETEDELETE WHEREWHERE

Delete using a condition

n

WHERElog_expr.

key

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.

n You can delete the nth line from the index table itab using DELETE itab INDEX n 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).

Page 73: TAW 10 part 2 of 2

© SAP AG TAW10 3-28

SAP AG 2002

Loop Processing

LOOP AT itab result[TRANSPORTING NO FIELDS]

{ [ FROM n1 ] [ TO n2 ] |

[ WHERE log_expr ] } .

...

ENDLOOP.

n Index tables only

( INTO wa( ASSIGNING <fs>

LOOP ATLOOP AT

ENDLOOPENDLOOP

FROMFROM TOTO

WHEREWHERE

resultwa itab

<fs>

result

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

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

n Specify the number of lines that the loop is to process using a WHERE clause (condition for any columns).

n In an index table, limit the number of lines processed in the loop by declaring an index interval. n While the loop is being processed, the system field sy-tabix contains the index of the table row of

the current loop pass. The total number of lines is in sy-tfill, the length of the lines in sy-tleng.

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

Page 74: TAW 10 part 2 of 2

© SAP AG TAW10 3-29

SAP AG 2002

Overview of Operations

Standard table Sorted table Hashed table

INSERT

READ TABLE

MODIFY

DELETE

Key access

Index access

LOOP AT

INSERT

READ TABLE

MODIFY

DELETE

LOOP AT

SORT

Sortsequencecould be violated

No indexaccesses to

hashed tables

Append to end of table

nn

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.

n You can use the SORT statement to sort standard and hashed tables. Sorted tables are sorted by the runtime system.

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

Page 75: TAW 10 part 2 of 2

© SAP AG TAW10 3-30

SAP AG 2002

Using Internal Tables (4)

Introduction and advantages of internal tablesIntroduction and advantages of internal tables

DefinitionDefinition

OperationsOperations

Notes on performanceNotes on performance

Special situationsSpecial situationsSpecial situations

Page 76: TAW 10 part 2 of 2

© SAP AG TAW10 3-31

SAP AG 2002

Internal Tables with a Header Line

DATA:

itab TYPE TABLE OF scarr

WITH DEFAULT KEY

WITH HEADER LINE.WITH HEADER LINEWITH HEADER LINEData object itab

DATA:

itab TYPE scarr OCCURS 0

WITH HEADER LINE.WITH HEADER LINEWITH HEADER LINE

DATA:

BEGIN OF itab OCCURS 0,

carrid TYPE s_carr_id,...url TYPE s_carrurl,

END OF itab.

OCCURSOCCURS

OCCURSOCCURS

Syntax variant 1

Syntax variant 2 (obsolete)

Syntax variant 3 (obsolete)

BEGIN OFBEGIN OF

END OFEND OF

itabitab

itabitab

Work area = header

Body

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.

n There are several possible syntax variants used to define internal tables with header lines, some of which are shown in the slide.

n Internal tables with header lines are the oldest form of internal table. n 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.

Page 77: TAW 10 part 2 of 2

© SAP AG TAW10 3-32

SAP AG 2002

Selection Options and Selection Tables

DATA:

carrid TYPE s_carr_id.

SELECT-OPTIONS:

so_carr FOR carrid.

SELECTSELECT--OPTIONSOPTIONS

FORFOR

so_so_carrcarr

DATA: so_carr LIKE

RANGE OF carrid.

( Link to selection screen

( Data object

Identically-typed data object withoutheader or link to selection screen

RANGE OFRANGE OF

sign(1)TYPE c

option(2)TYPE c

low LIKEcarrid

high LIKEcarrid

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

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

Page 78: TAW 10 part 2 of 2

© SAP AG TAW10 3-33

SAP AG 2002

Using Internal Tables (5)

Introduction and advantages of internal tablesIntroduction and advantages of internal tables

DefinitionDefinition

OperationsOperations

Notes on performanceNotes on performanceNotes on performance

Special situationsSpecial situations

Page 79: TAW 10 part 2 of 2

© SAP AG TAW10 3-34

SAP AG 2002

Single Record Access: Completely and Partially Qualified Key

READ TABLE itab INTO waWITH TABLE KEY key.WITH TABLE KEYWITH TABLE KEY

READ TABLE itab INTO waWITH KEY key.WITH KEYWITH KEY

Table scan

STANDARD

Complete/part keyComplete/part keyleftleft--aligned without gapsaligned without gaps

By qualified keyBy qualified key

Any componentAny componentconditioncondition

key

SORTED HASHEDSTANDARDkey

Table kind

Table kind

Binary search

Table scan

SORTED

Table scan

HASHED

Table scanBinary search

Hash algorithm

Must be completelyMust be completelyqualifiedqualified

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

Page 80: TAW 10 part 2 of 2

© SAP AG TAW10 3-35

SAP AG 2002

Loop Processing and Table Kinds

LOOP AT itab INTO waWHERE log_expr....

ENDLOOP.

log_log_exprexpr

Table scan

STANDARD

First n key fields filledFirst n key fields filledwith "=" without gapswith "=" without gaps

Any logical expressionAny logical expressionfor columnsfor columns

log_expr

Table kind

Binary search for starting point, then loop only through group

level

Table scan

SORTED

Table scan

HASHED

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.

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

Page 81: TAW 10 part 2 of 2

© SAP AG TAW10 3-36

SAP AG 2002

Partial Sequential Loop Through Standard Tables

CARRID CONNID CITYFROM ...

AA 64 SAN FRANCISCO ...

LH 400 ...LH 2407 BERLIN ...

UA 941 ...UA 3516 NEW YORK ...

Desired: Loop through data records where CITYFROM = 'FRANKFURT'

FRANKFURT

FRANKFURTCARRID CONNID CITYFROM ...

LH 2407 BERLIN ...

LH 400 ...UA 941 ...

UA 3516 ...AA 64 ...

FRANKFURT

SORT ... BY cityfromSTABLE.

FRANKFURT

NEW YORKSAN FRANCISCO

READ TABLE ...WITH KEY cityfrom = 'FRANKFURT'TRANSPORTING NO FIELDSBINARY SEARCH.

startline = sy-tabix.

Ascertain starting point:

LOOP AT ... INTO ...FROM startline to endline....

ENDLOOP.�

READ TABLE ... INTO ...WITH KEY cityfrom = 'NEW YORK'TRANSPORTING NO FIELDSBINARY SEARCH.

endline = sy-tabix.

Ascertain end point:

Index-controlled loop:

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.

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

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

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

Page 82: TAW 10 part 2 of 2

© SAP AG TAW10 3-37

SAP AG 2002

Access Using Field Symbols

<fs1>

<fs2>

READ TABLE itab ASSIGNING <fs1>WITH TABLE KEY ... .

READ TABLE <fs1>-col3ASSIGNING <fs2>WITH TABLE KEY ... .

wa1

wa2

Copy

Copy

col1 col2 col3 col4 col1 col2 col3 col4itab

READ TABLE itab INTO wa1WITH TABLE KEY ... .

READ TABLE wa1-col3INTO wa2WITH TABLE KEY ... .

ASSIGNINGASSIGNING

ASSIGNINGASSIGNING

INTOINTO

INTOINTO

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.

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

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

n Always assign a type to field symbols, if you know their static type (again, for performance reasons). n 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.

n Note that when using field symbols, you cannot change key fields in SORTED or HASHED tables. Trying to do so causes a runtime error.

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

Page 83: TAW 10 part 2 of 2

© SAP AG TAW10 3-38

SAP AG 2002

l Define an internal table

l Perform operations on internal tables

l Identify table kinds and use them appropriately in different situations

You are now able to:

Using Internal Tables: Unit Summary

Page 84: TAW 10 part 2 of 2

© SAP AG TAW10 3-39

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: ZBC401_##_SPLIT_ITAB

Template: SAPBC401_DTOS_SPLIT_STRING

Model solution: SAPBC401_TABS_SPLIT_ITAB ## 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.

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

1-3 Define a single-column internal table of the type Standard. The column component is to have the data type string (suggested name: it_sets).

1-4 Change the SPLIT statement so that always one partial character string that contains a data record is placed into a row of its internal table.

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

Page 85: TAW 10 part 2 of 2

© SAP AG TAW10 3-40

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: ZBC401_##_TABKIND

Template: SAPBC401_TABS_SPLIT_ITAB

Model solution: SAPBC401_TABS_TABKIND ## 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.

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

2-3 Define an internal table in such a way that it can contain flight data sorted by airline, flight number, and flight date (suggested name it_flights). Insert the separated data records (contents of the structure wa_flight) into this internal table, instead of displaying them. (You can still use the output statement later.) Make use of the return value sy-subrc for the INSERT statement to ascertain whether or not a data record appears twice. For this, you must have defined the key of your internal table accordingly. Define an additional internal table for the data records that appear twice (suggested name it_doubles). Insert the duplicate data records into this internal table.

2-4 Display the contents of both internal tables with the flight data.

Page 86: TAW 10 part 2 of 2

© SAP AG TAW10 3-41

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: ZBC401_##_PROCESS_DATA

Template: SAPBC401_TABS_TABKIND

Model solution: SAPBC401_TABS_PROCESS_DATA ## 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.

3-2 Define a selection screen parameter for entering the key date (suggested name pa_date). Specify the default value of the key date as 30 days in the future. The user must still be able to choose the key date. Error message 085 of the message class bc401 is to be displayed if the selected key date is in the past.

3-3 Make sure that the data is first displayed sorted by flight date.

3-4 Ensure that the individual flight dates of the internal table it_flights are displayed in color according to the following criteria: Use the FORMAT COLOR col_... statement and load the type group col. (You can reverse any color set using the FORMAT RESET statement.)

• Display flights that occurred in the past with the background color col_negative.

• Display flights that occurred between today’s data and the key date with the background color col_total.

Page 87: TAW 10 part 2 of 2

© SAP AG TAW10 3-42

• 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 Color value

fldate < sy-datum col_negative

fldate BETWEEN sy-datum AND p_date

col_total

fldate > p_date col_positive Always use col_background to display it_doubles.

Page 88: TAW 10 part 2 of 2

© SAP AG TAW10 3-43

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) TYPE c,

carrid(3) TYPE c,

connid(4) TYPE n,

fldate(8) TYPE n,

price(20) TYPE c,

currency(5) TYPE c,

planetype(10) TYPE c,

seatsmax(10) TYPE n,

seatsocc(10) TYPE n,

paymentsum(22) TYPE c,

seatsmax_b(10) TYPE n,

seatsocc_b(10) TYPE n,

seatsmax_f(10) TYPE n,

seatsocc_f(10) TYPE n,

END OF st_flight_c,

BEGIN OF st_flight,

carrid(3) TYPE c,

connid(4) TYPE n,

fldate TYPE d,

price(9) TYPE p DECIMALS 2,

currency(5) TYPE c,

planetype(10) TYPE c,

seatsmax TYPE i,

seatsocc TYPE i,

END OF st_flight.

CONSTANTS c_number TYPE i VALUE 30.

Page 89: TAW 10 part 2 of 2

© SAP AG TAW10 3-44

DATA:

datastring TYPE string,

set_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 = c_number

* IM_TABLE_NAME = 'SFLIGHT'

* IM_SEPARATOR = '#'

* IM_UNIQUE = 'X'

IMPORTING

ex_string = datastring

EXCEPTIONS

no_data = 1

OTHERS = 2.

IF sy-subrc <> 0.

MESSAGE a038(bc401).

ENDIF.

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.

Page 90: TAW 10 part 2 of 2

© SAP AG TAW10 3-45

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.

Page 91: TAW 10 part 2 of 2

© SAP AG TAW10 3-46

Solution 2 - Optional

Unit: Using Internal Tables

Topic: Table Types

REPORT sapbc401_tabs_tabkind.

TYPES:

BEGIN OF st_flight_c,

mandt(3) TYPE c,

carrid(3) TYPE c,

connid(4) TYPE n,

fldate(8) TYPE n,

price(20) TYPE c,

currency(5) TYPE c,

planetype(10) TYPE c,

seatsmax(10) TYPE n,

seatsocc(10) TYPE n,

paymentsum(22) TYPE c,

seatsmax_b(10) TYPE n,

seatsocc_b(10) TYPE n,

seatsmax_f(10) TYPE n,

seatsocc_f(10) TYPE n,

END OF st_flight_c,

BEGIN OF st_flight,

carrid(3) TYPE c,

connid(4) TYPE n,

fldate TYPE d,

price(9) TYPE p DECIMALS 2,

currency(5) TYPE c,

planetype(10) TYPE c,

seatsmax TYPE i,

seatsocc TYPE i,

END OF st_flight.

CONSTANTS c_number TYPE i VALUE 30.

Page 92: TAW 10 part 2 of 2

© SAP AG TAW10 3-47

DATA:

datastring TYPE string,

set_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 = c_number

* IM_TABLE_NAME = 'SFLIGHT'

* IM_SEPARATOR = '#'

IM_UNIQUE = space

IMPORTING

ex_string = datastring

EXCEPTIONS

no_data = 1

OTHERS = 2.

IF sy-subrc <> 0.

MESSAGE a038(bc401).

ENDIF.

Page 93: TAW 10 part 2 of 2

© SAP AG TAW10 3-48

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,

Page 94: TAW 10 part 2 of 2

© SAP AG TAW10 3-49

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.

Page 95: TAW 10 part 2 of 2

© SAP AG TAW10 3-50

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) TYPE c,

carrid(3) TYPE c,

connid(4) TYPE n,

fldate(8) TYPE n,

price(20) TYPE c,

currency(5) TYPE c,

planetype(10) TYPE c,

seatsmax(10) TYPE n,

seatsocc(10) TYPE n,

paymentsum(22) TYPE c,

seatsmax_b(10) TYPE n,

seatsocc_b(10) TYPE n,

seatsmax_f(10) TYPE n,

seatsocc_f(10) TYPE n,

END OF st_flight_c,

BEGIN OF st_flight,

carrid(3) TYPE c,

connid(4) TYPE n,

fldate TYPE d,

price(9) TYPE p DECIMALS 2,

currency(5) TYPE c,

planetype(10) TYPE c,

seatsmax TYPE i,

seatsocc TYPE i,

END OF st_flight.

Page 96: TAW 10 part 2 of 2

© SAP AG TAW10 3-51

CONSTANTS c_number TYPE i VALUE 30.

DATA:

datastring TYPE string,

set_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). " date in the past

ENDIF.

Page 97: TAW 10 part 2 of 2

© SAP AG TAW10 3-52

START-OF-SELECTION.

CALL FUNCTION 'BC401_GET_SEP_STRING'

EXPORTING

im_number = c_number

* IM_TABLE_NAME = 'SFLIGHT'

* IM_SEPARATOR = '#'

im_unique = space

IMPORTING

ex_string = datastring

EXCEPTIONS

no_data = 1

OTHERS = 2.

IF sy-subrc <> 0.

MESSAGE a038(bc401).

ENDIF.

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.

Page 98: TAW 10 part 2 of 2

© SAP AG TAW10 3-53

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_col_flights

it_list2 = it_col_doubles

EXCEPTIONS

control_error = 1

OTHERS = 2.

IF sy-subrc <> 0.

MESSAGE a702(bc401).

ENDIF.

Page 99: TAW 10 part 2 of 2

© SAP AG TAW10 3-54

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.

Page 100: TAW 10 part 2 of 2

© SAP AG TAW10 4-1

SAP AG 2002

l Procedural programming

l Object-oriented programming

l Aims of the ABAP Objects programming language

Contents:

Introduction to Object-Oriented Programming

Page 101: TAW 10 part 2 of 2

© SAP AG TAW10 4-2

SAP AG 2002

l Name the most significant differences between procedural and object-oriented programming

l State the aims behind developing the ABAP Objects programming language

At the conclusion of this unit, you will be able to:

Introduction to Object-Oriented Programming: Unit Objectives

Page 102: TAW 10 part 2 of 2

© SAP AG TAW10 4-3

SAP AG 2002

History of Programming Languages

Machine language

Assembler

Java

C++

ABAP Objects

ABAP

n Before ABAP, SAP used a macro assembler. n 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.

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

Page 103: TAW 10 part 2 of 2

© SAP AG TAW10 4-4

SAP AG 2002

Introduction: Programming Models (1)

Procedural programmingProcedural programming

Object-oriented programmingObject-oriented programming

Page 104: TAW 10 part 2 of 2

© SAP AG TAW10 4-5

SAP AG 2002

Characteristics of Procedural Programming

Characteristics:

l Separation of functions and data

l Possibility of encapsulating functions using modularization

l Direct access to data possible -visibility?

DataData DataData

DataDataDataData

DataData

FunctionFunction

FunctionFunctionFunctionFunctionFunctionFunction

FunctionFunctionFunctionFunctionFunctionFunctionFunctionFunction

n Information systems were previously defined primarily by their functions: Data and functions were stored separately and linked using input-output relationships.

Page 105: TAW 10 part 2 of 2

© SAP AG TAW10 4-6

SAP AG 2002

REPORT ZABAP_DEMO.*----------------------TYPES: ...

DATA: ...

...

PERFORM form1 ...

CALL FUNCTION 'FB1'...CALL FUNCTION 'FB2'...

*----------------------FORM f1 ...

...ENDFORM.

REPORT ZABAP_DEMO.*----------------------TYPES: ...

DATA: ...

...

PERFORM form1 ...

CALL FUNCTION 'FB1'...CALL FUNCTION 'FB2'...

*----------------------FORM f1 ...

...ENDFORM.

Typical ABAP Program

l Type definitions

l Data declarations

l Main program

§ Calling subroutines

§ Calling function modules

l Definition of subroutines

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.

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

Page 106: TAW 10 part 2 of 2

© SAP AG TAW10 4-7

SAP AG 2002

ABAP Main Memory and Function Groups

Internal sessionInternal session

Global data objects in main program

Subroutines

Function groups

Function group 2

Function module 1

Function module 2

Function group 1

Function module 1

Function module 2

Function module ...

Global data

Global data

InterfaceInterface

InterfaceInterface

n This slide provides an overview of the main program components during program execution in an internal session (main memory area on application server).

n The loaded main program and the two function groups with their encapsulated modules (the function modules) are both in separate memory areas.

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

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

Page 107: TAW 10 part 2 of 2

© SAP AG TAW10 4-8

SAP AG 2002

Function Group Example

FUNCTION-POOL s_vehicle.

* speed is a global variable* used in the funtion-poolDATA: speed TYPE I.

... FUNCTION INC_SPEED....ADD imp_speed TO speed.

ENDFUNCTION.

FUNCTION DEC_SPEED....SUBTRACT IMP_SPEED from speed.

ENDFUNCTION.

FUNCTION GET_SPEED.exp_speed = speed.

ENDFUNCTION.

...

FUNCTION-POOL s_vehicle.

* speed is a global variable* used in the funtion-poolDATA: speed TYPE I.

... FUNCTION INC_SPEED.

...ADD imp_speed TO speed.

ENDFUNCTION.

FUNCTION DEC_SPEED....SUBTRACT IMP_SPEED from speed.

ENDFUNCTION.

FUNCTION GET_SPEED.exp_speed = speed.

ENDFUNCTION.

...

Function group with functions for controlling

the speed of a car

S_VEHICLE

inc_speed

dec_speed

get_speed

stop

speed

n The function group s_vehicle provides a user or client with the services inc_speed, dec_speed, and get_speed.

n These services make up the function group interface and access the internally encapsulated component speed.

Page 108: TAW 10 part 2 of 2

© SAP AG TAW10 4-9

SAP AG 2002

REPORT zvehicledemo.

TYPES: ...

DATA: wa_car TYPE ...

* no direct access to speed

* use functions of pool

CALL FUNCTION 'INC_SPEED'...

CALL FUNCTION 'GET_SPEED'...

CALL FUNCTION 'STOP'...

REPORT zvehicledemo.

TYPES: ...

DATA: wa_car TYPE ...

* no direct access to speed

* use functions of pool

CALL FUNCTION 'INC_SPEED'...

CALL FUNCTION 'GET_SPEED'...

CALL FUNCTION 'STOP'...

Use of Function Group

inc_speed

dec_speed

get_speed

stop

Main program that uses function modules of this

function group

S_VEHICLE

speed

n The main program cannot access speed directly.

Page 109: TAW 10 part 2 of 2

© SAP AG TAW10 4-10

SAP AG 2002

Several Instances of One Function Group

S_VEHICLE

inc_speed

dec_speed

get_speed

stop

speed

?

Displaying a number of vehicles and their speed is

only possible with additional administration

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

Page 110: TAW 10 part 2 of 2

© SAP AG TAW10 4-11

SAP AG 2002

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

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

Page 111: TAW 10 part 2 of 2

© SAP AG TAW10 4-12

SAP AG 2002

Introduction: Programming Models (2)

Procedural programmingProcedural programming

Object-oriented programmingObject-oriented programming

Page 112: TAW 10 part 2 of 2

© SAP AG TAW10 4-13

SAP AG 2002

Programming Models

Data and functions Object model as abstraction of real

world

Real worldData Data

DataData

Data

FunctionFunction

FunctionFunctionFunctionFunctionFunctionFunction

FunctionFunctionFunctionFunctionFunctionFunctionFunctionFunction

DataFunctions

FunctionsFunctions

DataFunctions

FunctionsFunctions

DataFunctions

FunctionsFunctions

n 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

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

Page 113: TAW 10 part 2 of 2

© SAP AG TAW10 4-14

SAP AG 2002

Characteristics of the Object-Oriented Approach

l Objects are an abstraction of the real world

l Processes can be implemented realistically

l Objects are units made up of data and the functions belonging to that data

l Improves software structure and consistency in the development process

l Maintenance requirements are reduced

l Modeler, end user, and developer are all included in analysis and design process

Real world

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

n The behavior of objects is described through methods (functions) and events. n 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.

n 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

Page 114: TAW 10 part 2 of 2

© SAP AG TAW10 4-15

SAP AG 2002

Technical Implementation of the Object-Oriented Approach

Code 4

Code 1

Code 2

Code 3display_data

DataDataFunctionsFunctions

FunctionsFunctionsl Encapsulation of data and functions

l Polymorphism for support of generic programming

l Inheritance

l Improved structuring and consistency in the software development process

Superclass

Subclass 1 Subclass 2

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

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

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

Page 115: TAW 10 part 2 of 2

© SAP AG TAW10 4-16

SAP AG 2002

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

ServerClient

DataData

MethodsMethods

DataData

MethodsMethods CALL METHOD server->do_it

do_itcall_it

n 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

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

n Establishing logical business and software/technical responsibilities between classes results in a true client/server software system in which redundancy is avoided.

Page 116: TAW 10 part 2 of 2

© SAP AG TAW10 4-17

SAP AG 2002

Compatibility and Design Aims

Compatibility:

l ABAP Objects is a true, compatible extension of ABAP

l ABAP Objects statements can be used in procedural ABAP programs

l Objects (classes) themselves contain classic ABAP statements

Design aims were:

l As simple as possible

l Only object-oriented concepts that have proved useful

l Increased use of type checks

* ABAP Objects Programm

DATA: counter TYPE i,wa type KNA1.

...

CLASS lcl_car DEFINITION....

ENDCLASS.

*--- main program ---------

CREATE OBJECT ...

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

* ABAP Objects Programm

DATA: counter TYPE i,wa type KNA1.

...

CLASS lcl_car DEFINITION....

ENDCLASS.

*--- main program ---------

CREATE OBJECT ...

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

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

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

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

Page 117: TAW 10 part 2 of 2

© SAP AG TAW10 4-18

SAP AG 2002

ABAP Main Memory and Encapsulation

Internal sessionInternal session

Internal sessionInternal session

DataData

FunctionsFunctions

Global data objects

Global data objects

DataData

FunctionsFunctions

l Data and business functions are encapsulated in objects

Modularization unitsl Modularization units for

encapsulating functions

l Working with global data of the main program

n One feature and design aim of object-oriented languages is that business functions are held separately.

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

Page 118: TAW 10 part 2 of 2

© SAP AG TAW10 4-19

SAP AG 2002

The Software Development Process

Implementation(ABAP Objects)

Analysis anddesign

Requirement,idea Test

Iteration

Already specified for the purposes of this course

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

Page 119: TAW 10 part 2 of 2

© SAP AG TAW10 4-20

SAP AG 2002

l Name the most significant differences between procedural and object-oriented programming

l State the aims behind developing the ABAP Objects programming language

You are now able to:

Introduction to Object-Oriented Programming: Summary

Page 120: TAW 10 part 2 of 2

© SAP AG TAW10 5-1

SAP AG 2002

l Classification of objects

l UML

l Class diagrams

l Sequence diagrams

Contents:

Analysis and Design

Page 121: TAW 10 part 2 of 2

© SAP AG TAW10 5-2

SAP AG 2002

l List some important diagram types in UML

l Create a class diagram

l Create a sequence diagram

At the conclusion of this unit, you will be able to:

Analysis and Design: Unit Objectives

Page 122: TAW 10 part 2 of 2

© SAP AG TAW10 5-3

SAP AG 2002

Analysis and Design (1)

ClassificationClassification

UML - the modeling standardUML - the modeling standard

Page 123: TAW 10 part 2 of 2

© SAP AG TAW10 5-4

SAP AG 2002

Classification of Objects

Real world

lcl_vehicle lcl_people

Class creation / modeling

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

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

Page 124: TAW 10 part 2 of 2

© SAP AG TAW10 5-5

SAP AG 2002

Different Abstractions of a Class

Car enthusiast Scrap merchant

Makemake

Type model

PS

Doors doors

Colorcolor

Equipping equipping

Weightweight

Wheelswheels

Scrap value scrapvalue

Priceprice

lcl_vehicle

- make

- ...

- price

- equipping

- color

lcl_vehicle

- make

- ...

- weight

- scrapvalue

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.

n This example concerns cars. Software for a car enthusiast and software for a scrap merchant contain different abstractions (classes) for these objects.

n A class can contain very different objects depending on the abstraction. n 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.

n In our examples, the class lcl_vehicle describes all motorized vehicles with 4 wheels.

Page 125: TAW 10 part 2 of 2

© SAP AG TAW10 5-6

SAP AG 2002

Representation of a Class

lcl_vehiclemake

modell

...

price

color

set_make

display_attributes

increase_speed

...

Attributes

Class name

Methods (functions)

Assoziationsme

Optional, does not have to be

specified

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.

n Attributes describe the data that can be stored in the objects in a class. They define the state of an object.

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

n ABAP Objects events are not included in class diagrams.

Page 126: TAW 10 part 2 of 2

© SAP AG TAW10 5-7

SAP AG 2002

Classes and Objects

lcl_vehicle

Class:

l General description of objects (blueprint)

l Specifies status data (attributes) and behavior (methods)

Object (instance):

l Representation of real world

l Specific instance of a class

Represented in course by:

lcl_vehicle

(5) lcl_vehicle

or

or

...

...

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.

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

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

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

Page 127: TAW 10 part 2 of 2

© SAP AG TAW10 5-8

SAP AG 2002

Analysis and Design (2)

ClassificationClassification

UML - the modeling standardUML - the modeling standard

Page 128: TAW 10 part 2 of 2

© SAP AG TAW10 5-9

SAP AG 2002

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 modelsfor software systems

n Diagram types:

w Class diagram

w Behavior diagram, such as a sequence diagram

w Component diagram

w Distribution diagram

w ...

Modeling with UML

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.

n UML is an industry standard and has been standardized by the OMG (Object Management Group) since September 1997 as UML Version 1.1. The members of the OMG are continuously developing it further. SAP uses UML as the company-wide standard for object-oriented modeling.

n You can find the UML specifications on the OMG homepage at: http://www.omg.org

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

n Behavior diagrams demonstrate the relationships and method calls between objects. They emphasize the timing sequence of method calls.

n Component diagrams show the organization and dependencies of components. n Distribution diagrams represent the dependencies of software and hardware.

Page 129: TAW 10 part 2 of 2

© SAP AG TAW10 5-10

SAP AG 2002

Example of a Class Diagram

lcl_rental

lcl_vehicle

lcl_car lcl_truck lcl_bus

lcl_booking lcl_customer

lcl_wheel

10..*0..*1

1

1..*11..*

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

n In class diagrams, classes can also be shown with their attributes and methods.

Page 130: TAW 10 part 2 of 2

© SAP AG TAW10 5-11

SAP AG 2002

Association

A customer can rent several cars

Common cardinalities

books

Association name

* or 0..* Many1 Exactly one1..* One or more0..1 Zero or one

10..*lcl_booking lcl_customer

A booking refers to a customer

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

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

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

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

Page 131: TAW 10 part 2 of 2

© SAP AG TAW10 5-12

SAP AG 2002

Aggregation and Composition

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

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

Composition symbol

Aggregation symbol

lcl_rental lcl_booking1..*1

lcl_vehicle lcl_wheel1 0..*

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

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

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

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

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

Page 132: TAW 10 part 2 of 2

© SAP AG TAW10 5-13

SAP AG 2002

Generalization and Specialization

or

Gen

eral

izat

ion

Spe

cial

izat

ion

Gen

eral

izat

ion

Spe

cial

izat

ion

lcl_vehicle

lcl_car lcl_truck

lcl_vehicle

lcl_car lcl_truck

Inheritance arrow

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

Page 133: TAW 10 part 2 of 2

© SAP AG TAW10 5-14

SAP AG 2002

Sequence Diagrams: Example

Life lineof object

Control focus

Return value

1:Method (parameter)

Time

lcl_driver lcl_car

Process description(optional)

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

n Sequence diagrams have no notation for representing static methods. n The object life line is represented by vertical dotted lines. n 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.

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

n You can also include a description of the process and add comments to the object life line as required.

Page 134: TAW 10 part 2 of 2

© SAP AG TAW10 5-15

SAP AG 2002

1: get_fuel_level( )2: get_fuel_level( )

re_level

re_level

lcl_driver lcl_car lcl_tank

re_level = fuel / fuel_max * 100.

re_level = tank->get_fuel_level( ).

Sequence Diagram: Delegation

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.

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

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

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

Page 135: TAW 10 part 2 of 2

© SAP AG TAW10 5-16

SAP AG 2002

l List some diagram types in UML

l Create a class diagram

l Create a sequence diagram

You are now able to:

Analysis and Design: Summary

Page 136: TAW 10 part 2 of 2

© SAP AG TAW10 5-17

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.

Page 137: TAW 10 part 2 of 2

© SAP AG TAW10 5-18

Analysis and Design Solutions

Unit: Analysis and Design

Topic: UML Class Diagrams

Page 138: TAW 10 part 2 of 2

© SAP AG TAW10 6-1

SAP AG 2002

l Classes

l Objects

l Attributes

l Methods

l Visibility/encapsulation

l Instantiation

l Constructor

l Garbage collector

Contents:

Principles of Object-Oriented Programming

Page 139: TAW 10 part 2 of 2

© SAP AG TAW10 6-2

SAP AG 2002

l Create classes

l Create objects

l Call methods

l Explain how the garbage collector works

At the conclusion of this unit, you will be able to:

Principles of Object-Oriented Programming: Unit Objectives

Page 140: TAW 10 part 2 of 2

© SAP AG TAW10 6-3

SAP AG 2002

Principles (1)

Classes, attributes, and methodsClasses, attributes, and methods

Objects, instances of classesObjects, instances of classes

Accessing attributes and methodsAccessing attributes and methods

The constructorThe constructor

Additional principlesAdditional principles

Page 141: TAW 10 part 2 of 2

© SAP AG TAW10 6-4

SAP AG 2002

Example of a Class

lcl_vehicle

Privatecomponents

Methods:Implementation

Publiccomponents

Private access• Encapsulation• Normally attributes

Public access• Interface• Normally methods, events

make

modelset_make

get_make

Represented in course by

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

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

Page 142: TAW 10 part 2 of 2

© SAP AG TAW10 6-5

SAP AG 2002

Defining Classes

CLASS lcl_vehicle DEFINITION.

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.

ENDCLASS.

lcl_vehicle

Privatecomponents

Methodimplementation

Publiccomponents

ABAP code

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.

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

n The CLASS statement cannot be nested, that is, you cannot define a class within a class.

Page 143: TAW 10 part 2 of 2

© SAP AG TAW10 6-6

SAP AG 2002

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 anobject, in this case “r_car”

(5) lcl_car

PrivatePublic

make TYPE STRING,...

r_motor TYPE REF TO ...

(3) lcl_rental

r_car

n Attributes describe the data that can be stored in the objects of a class. n 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

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

Page 144: TAW 10 part 2 of 2

© SAP AG TAW10 6-7

SAP AG 2002

Attributes, Types, and Constants: Syntax

CLASS <classname> DEFINITION....

TYPES: <normale Typdefinition>.CONSTANTS: constant TYPE <type> VALUE <value>.

DATA: variable1 TYPE <type>,variable2 TYPE <ddic_type>,variable3 LIKE variable1,variable4 TYPE <type> VALUE <value>,variable5 TYPE <type> READ-ONLY, variable6 TYPE REF TO <classname>,variable7 TYPE REF TO <interface>.

CLASS-DATA: only_once TYPE ... .

ENDCLASS.

n In classes, you can only use the TYPE addition to refer to data types. n You can only use the LIKE reference for local data objects. n 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. n 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.

Page 145: TAW 10 part 2 of 2

© SAP AG TAW10 6-8

SAP AG 2002

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION....

PRIVATE SECTION.DATA: make TYPE string.

ENDCLASS.

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION.DATA: make TYPE string.

PRIVATE SECTION.

ENDCLASS.

Attributes and Visibility

l Public attributes

n Can be viewed and changed by all users and in all methods

n Direct access

l Private attributes

n Can only be viewed and changed from within the class

n No direct accessfrom outside the class

n You can protect attributes against access from outside by characterizing them as private attributes (defined in the PRIVATE SECTION).

n Attributes and their values that may be used directly by an external user are public attributes and are defined in the PUBLIC SECTION.

n In the above example for the class lcl_car, the attribute make is defined as a public attribute. n 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.

n As a general rule, you should define as few public attributes as possible.

Page 146: TAW 10 part 2 of 2

© SAP AG TAW10 6-9

SAP AG 2002

Accessing Private Attributes

(5) lcl_vehicle

PrivatePublic

r_vehicle

make

Client

set_makeget_make...

n You can access an object's private attributes using public methods, which in turn output this attribute or change it.

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

Page 147: TAW 10 part 2 of 2

© SAP AG TAW10 6-10

SAP AG 2002

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION....

PRIVATE SECTION.DATA: make TYPE string,

...

CLASS-DATA: n_o_vehicles TYPE i.

ENDCLASS.

Instance Attributes and Static Attributes (1)

l Instance attributes

n One per instance

n Statement: DATA

l Static attributes

n Only one per class

n Statement: CLASS-DATA

n Also known as class attributes

n There are two kinds of attributes: ­ Static attributes ­ Instance attributes

n Instance attributes are attributes that exist separately for each object. Instance attributes are defined using the ABAP keyword DATA.

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

n Static attributes are defined using the CLASS-DATA keyword. n You may come across the expression "class attributes" in documentation, however, the official term

in ABAP Objects (as in C++, Java) is "static" attributes.

Page 148: TAW 10 part 2 of 2

© SAP AG TAW10 6-11

SAP AG 2002

Instance Attributes and Static Attributes (2)

Internal sessionInternal session

Global data objects

(2) lcl _vehicle

(3) lcl_vehicle

...

n_o_vehicles 3

r_vehicle1

r_vehicle3

r_vehicle2

(1) lcl_vehicle

Static attributesStatic attributes

Static attributes only exist once

Instances / objects

...

n The graphic shows the static attribute n_o_vehicles. It exists only once, regardless of how many instances there are of lcl_vehicle.

n Therefore, you can say that instances share their common attributes.

Page 149: TAW 10 part 2 of 2

© SAP AG TAW10 6-12

SAP AG 2002

Methods: Syntax

CLASS <classname> IMPLEMENTATION.METHOD <method_name>....

ENDMETHOD.ENDCLASS.

CLASS <classname> DEFINITION....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.

Methods can have a signature

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

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.

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

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

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

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

Page 150: TAW 10 part 2 of 2

© SAP AG TAW10 6-13

SAP AG 2002

Accessing Private Methods

(5) lcl_vehicle

PrivatePublic

r_vehicleinit_make

set_make

make...

...

Client

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.

n It is not possible to directly access private methods from outside. However, a private method can be called by a public method.

n Both method types can access the public and private attributes.

Page 151: TAW 10 part 2 of 2

© SAP AG TAW10 6-14

SAP AG 2002

Methods and Visibility

l Public methods

n Can be called from anywhere

l Private methods

n Can only be called within the class

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.

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

Page 152: TAW 10 part 2 of 2

© SAP AG TAW10 6-15

SAP AG 2002

Instance Methods and Static Methods

l Instance methods

n Can use both static and instance components in their implementation part

n Can be called using an instance

l Static methods

n Can only use static components in their implementation part

n Can be called using the class

Rules:

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

n The term "class method" is common, but the official term in ABAP Objects (as in C++, Java) is "static method".

Page 153: TAW 10 part 2 of 2

© SAP AG TAW10 6-16

SAP AG 2002

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.

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

Page 154: TAW 10 part 2 of 2

© SAP AG TAW10 6-17

SAP AG 2002

Summary and UML Notation

+ refers to public components

- refers to private components

_ static components are underlined

CLASS lcl_vehicle DEFINITION.PUBLIC SECTION.METHODS: set_make IMPORTING im_make TYPE string.CLASS-METHODS: get_count EXPORTING ex_count TYPE i.

PRIVATE SECTION.DATA: make TYPE string. ...CLASS-DATA: n_o_vehicles TYPE i.METHODS: init_make.

ENDCLASS.

lcl_vehicle- make- model- n_o_vehicles...

+ set_make - init_make+ get_count...

n A UML class diagram shows firstly the class name and, underneath that, the class attributes and methods.

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

n Static components are marked with an underscore. n 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.

Page 155: TAW 10 part 2 of 2

© SAP AG TAW10 6-18

SAP AG 2002

Principles (2)

Classes, attributes, and methodsClasses, attributes, and methods

Objects, instances of classesObjects, instances of classes

Accessing attributes and methodsAccessing attributes and methods

The constructorThe constructor

Additional principlesAdditional principles

Page 156: TAW 10 part 2 of 2

© SAP AG TAW10 6-19

SAP AG 2002

Creating Objects

Rules: l Objects are created using the CREATE OBJECT statement

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

(5) lcl_vehicle

PrivatePublicmakemodellser_no...

set_makeget_count...

CREATE OBJECT r_vehicle

r_vehicle

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

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

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

Page 157: TAW 10 part 2 of 2

© SAP AG TAW10 6-20

SAP AG 2002

Reference Variables

...

CLASS lcl_vehicle DEFINITION.PUBLIC SECTION....

PRIVATE SECTION....

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION....

ENDCLASS.

DATA: r_vehicle1 TYPE REF TO lcl_vehicle,r_vehicle2 TYPE REF TO lcl_vehilce.

START-OF_SELECTION....

r_vehicle1

r_vehicle2?

?

What do these reference variables

point to?

n DATA: r_vehicle1 TYPE REF TO lcl_vehicle declares a reference variable that acts as a pointer to an object.

Page 158: TAW 10 part 2 of 2

© SAP AG TAW10 6-21

SAP AG 2002

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.

r_vehicle1

r_vehicle2

(3) lcl_vehicle

PrivatePublic

(4) lcl_vehicle

PrivatePublic

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.

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

Page 159: TAW 10 part 2 of 2

© SAP AG TAW10 6-22

SAP AG 2002

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

r_vehicle2 (4) lcl_vehicle

PrivatePublic

r_vehicle1

(3) lcl_vehicle

PrivatePublic

n As soon as no more references point to an object, the Garbage Collector removes it from the memory.

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

Page 160: TAW 10 part 2 of 2

© SAP AG TAW10 6-23

SAP AG 2002

Garbage Collector: Procedure

l All independent references in the global main memory are checked. The references point to active objects, which are marked internally.

l References of class or instance attributes to other objects are followed. These objects are also marked.

l Objects that are not marked are deleted from the main memory.

(2) lcl_object

(4) lcl_object

(5) lcl_object

Deleted

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

Page 161: TAW 10 part 2 of 2

© SAP AG TAW10 6-24

SAP AG 2002

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

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.

n You can process the objects using a LOOP through the internal table.

Page 162: TAW 10 part 2 of 2

© SAP AG TAW10 6-25

SAP AG 2002

Aggregation Example

(5) lcl_vehicle

PrivatePublic

itab_wheels

(17) lcl_wheel

(25) lcl_wheel

(29) lcl_wheel

(36) lcl_wheel

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

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

Page 163: TAW 10 part 2 of 2

© SAP AG TAW10 6-26

SAP AG 2002

Principles (3)

Classes, attributes, and methodsClasses, attributes, and methods

Objects, instances of classesObjects, instances of classes

Accessing attributes and methodsAccessing attributes and methods

The constructorThe constructor

Additional principlesAdditional principles

Page 164: TAW 10 part 2 of 2

© SAP AG TAW10 6-27

SAP AG 2002

Calling Methods

(5) lcl_vehicle

PrivatePublic

r_vehicle->motor_on( )

Reference

Component selector

Method

Client

motor_on

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

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

n For the sake of simplicity, method will henceforth be used as a synonym for operation and message. n The example shows the new syntax for method calls, in which the CALL-METHOD prefix is omitted.

Page 165: TAW 10 part 2 of 2

© SAP AG TAW10 6-28

SAP AG 2002

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: <instance>-><instance_method>(see online documentation) ( [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 ).

n Instance methods are called using CALL METHOD <reference>-><instance_method>. n 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. n 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. n 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.

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

n In method calls, multiple parameters are separated by spaces.

Page 166: TAW 10 part 2 of 2

© SAP AG TAW10 6-29

SAP AG 2002

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_countCALL METHOD lcl_vehicle=>get_count( IMPORTING re_count = count ).

* other variant, since 6.1 available, see documentationlcl_vehicle=>get_count( IMPORTING re_count = count ).

n Static methods (also referred to as class methods) are called using CALL METHOD <classname>=><class_method>.

n Static methods are addressed with their class name, since they do not need instances. n Note:

If you are calling a static method from within the class, you can omit the class name.

Page 167: TAW 10 part 2 of 2

© SAP AG TAW10 6-30

SAP AG 2002

Functional Methods

l When defining:

§ Only one RETURNING parameter

§ Only IMPORTING parameters and exceptions are possible

l When calling:

§ a) RECEIVING parameters possible

§ b) Various forms of direct call possible:

w MOVE, CASE, LOOP

w Logical expressions (IF, ELSEIF, WHILE, CHECK, WAIT)

w Arithmetic expressions and bit expressions (COMPUTE),see example: a = b + c

a = b + Functional method

Example

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

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

Page 168: TAW 10 part 2 of 2

© SAP AG TAW10 6-31

SAP AG 2002

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

r_vehicle1->get_average_fuel( im_distance = 500 im_fuel = 50 )+ r_vehicle2->get_average_fuel( im_distance = 600 im_fuel = 60 ).

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

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

Page 169: TAW 10 part 2 of 2

© SAP AG TAW10 6-32

SAP AG 2002

External Access to Public Attributes

CLASS lcl_vehicle DEFINITION.PUBLIC SECTION.

DATA: make TYPE string READ-ONLY. “just a demo CLASS-DATA: n_o_vehicles TYPE i READ-ONLY. “just a demo

...ENDCLASS....

DATA: r_vehicle TYPE REF TO lcl_vehicle.DATA: make_name TYPE string,

count TYPE i.

START-OF-SELECTION.*---------------------------------------* main program, think of a client !CREATE OBJECT r_vehicle.

make_name = r_vehicle->make. “only if public attr.count = lcl_vehicle=>n_o_vehicles. “only if public attr.

(2) lcl_vehicle

make...

r_vehicle

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

Page 170: TAW 10 part 2 of 2

© SAP AG TAW10 6-33

SAP AG 2002

Classes, attributes, and methodsClasses, attributes, and methods

Objects, instances of classesObjects, instances of classes

Accessing attributes and methodsAccessing attributes and methods

The constructorThe constructor

Additional principlesAdditional principles

Principles (4)

Page 171: TAW 10 part 2 of 2

© SAP AG TAW10 6-34

SAP AG 2002

Constructor

l Special method for creating objects with defined initial state

l Only has IMPORTING parameters and EXCEPTIONS

l Is executed only once per instance

CREATE OBJECT

METHODS constructor IMPORTING <im_parameter>EXCEPTIONS <exception>.

METHODS constructor IMPORTING <im_parameter>EXCEPTIONS <exception>.

lcl_vehicle- make- model- n_o_vehicles...

+ constructor...

(3) lcl_vehicle

PrivatePublic

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

n When exceptions are raised in the constructor, instances are not created, so no main memory space is occupied.

Page 172: TAW 10 part 2 of 2

© SAP AG TAW10 6-35

SAP AG 2002

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.

Constructor: Example

DATA r_vehicle TYPE REF TO lcl_vehicle....CREATE OBJECT r_vehicle

EXPORTING im_make = 'Ferrari'im_model = 'F40'.

Automatic constructor call

Call from the main program

n 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

n You cannot normally call the constructor explicitly.

Page 173: TAW 10 part 2 of 2

© SAP AG TAW10 6-36

SAP AG 2002

Preview: Static Constructor

CLASS lcl_vehicle DEFINITION.PUBLIC SECTION.

CLASS-METHODS: CLASS_CONSTRUCTOR.PRIVATE SECTION.

CLASS-DATA: n_o_vehicles TYPE I.ENDCLASS.

l Special static method

l Automatically called before the class is first accessed

l Only executed once per programCLASS lcl_vehicle IMPLEMENTATION.

METHOD CLASS_CONSTRUCTOR....

ENDMETHOD. ...ENDCLASS.

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

n 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>. n The static constructor cannot be called explicitly.

Page 174: TAW 10 part 2 of 2

© SAP AG TAW10 6-37

SAP AG 2002

Principles (5)

Classes, attributes, and methodsClasses, attributes, and methods

Objects, instances of classesObjects, instances of classes

Accessing attributes and methodsAccessing attributes and methods

The constructorThe constructor

Additional principlesAdditional principles

Page 175: TAW 10 part 2 of 2

© SAP AG TAW10 6-38

SAP AG 2002

Namespace Within a Class

l The same namespace for

n Attributes

n Methods

n Events

n Types

n Constants

n ALIAS names

l There is a local namespace within methods

lcl_vehicle

Privatecomponents

Methodimplementation

Publiccomponents

AttributemakeMethod

make

n Within a class, attribute names, method names, event names, constant names, type names and alias names all share the same namespace.

n There is a local namespace within methods. Definitions of local variables can cover components in one class.

Page 176: TAW 10 part 2 of 2

© SAP AG TAW10 6-39

SAP AG 2002

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

lcl_vehicle

Privatecomponents

Methodimplementation

Publiccomponents

Attributemake

ME->make

n You can address the object itself within instance methods using the implicitly available reference variable me.

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

n The dummy method demonstrates how to call a class's own method. You can omit the prefix me->. n Other important use:

An object calls another object's method and passes its own address.

Page 177: TAW 10 part 2 of 2

© SAP AG TAW10 6-40

SAP AG 2002

l Create classes

l Create objects

l Call methods

l Explain how the garbage collector works

You are now able to:

Principles of Object-Oriented Programming: Unit Summary

Page 178: TAW 10 part 2 of 2

© SAP AG TAW10 6-41

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.

1-2 Create the main program ZBC401_##_MAIN_AIRPLANE and the include program ZBC401_##_AIRPLANE the main program contains (##: group number).

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

Page 179: TAW 10 part 2 of 2

© SAP AG TAW10 6-42

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

Page 180: TAW 10 part 2 of 2

© SAP AG TAW10 6-43

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

Page 181: TAW 10 part 2 of 2

© SAP AG TAW10 6-44

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.

Page 182: TAW 10 part 2 of 2

© SAP AG TAW10 6-45

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 The constructor must have two importing parameters that fill the instance attributes name and planetype.

4-1-2 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 constructor’s 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.

Page 183: TAW 10 part 2 of 2

© SAP AG TAW10 6-46

Exercises

Unit: Principles of Object-Oriented Programming

Topic: Calling a Private Method

At the conclusion of these exercises, you will be able to:

• Call methods within a class

Model solution: SAPBC401_AIRS_MAIN_E SAPBC401_AIRS_E include program

5 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 By calling it from the main program

5-5-2 By calling it within the display_attributes method

5-3-3 Which call was successful, and why?

Page 184: TAW 10 part 2 of 2

© SAP AG TAW10 6-47

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.

Page 185: TAW 10 part 2 of 2

© SAP AG TAW10 6-48

ENDCLASS.

*------------------------------------------------------------------*

* CLASS lcl_airplane IMPLEMENTATION *

*------------------------------------------------------------------*

CLASS lcl_airplane IMPLEMENTATION.

METHOD set_attributes.

name = im_name.

planetype = im_planetype.

n_o_airplanes = n_o_airplanes + 1.

ENDMETHOD.

METHOD display_attributes.

WRITE: / icon_ws_plane as icon,

/ 'Name of airplane:'(001), AT pos_1 name,

/ 'Airplane type'(002), AT pos_1 planetype.

ENDMETHOD.

METHOD display_n_o_airplanes.

WRITE: /, / 'Total number of planes'(ca1),

AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.

ENDMETHOD.

ENDCLASS.

Page 186: TAW 10 part 2 of 2

© SAP AG TAW10 6-49

Solutions

Unit: Principles of Object-Oriented Programming

Topic: Instantiating Objects

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

*& Report SAPBC401_AIRS_MAIN_b *

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

*& create and insert planes into internal table *

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

REPORT sapbc401_airs_main_b.

TYPE-POOLS icon.

INCLUDE SAPBC401_airs_A.

DATA: r_plane TYPE REF TO lcl_airplane,

plane_list TYPE TABLE OF REF TO lcl_airplane.

START-OF-SELECTION.

*##############################

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.

Page 187: TAW 10 part 2 of 2

© SAP AG TAW10 6-50

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.

Page 188: TAW 10 part 2 of 2

© SAP AG TAW10 6-51

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.

Page 189: TAW 10 part 2 of 2

© SAP AG TAW10 6-52

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

*& 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 = im_name.

planetype = im_planetype.

n_o_airplanes = n_o_airplanes + 1.

ENDMETHOD.

Page 190: TAW 10 part 2 of 2

© SAP AG TAW10 6-53

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.

Page 191: TAW 10 part 2 of 2

© SAP AG TAW10 6-54

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

Page 192: TAW 10 part 2 of 2

© SAP AG TAW10 6-55

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

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

Page 193: TAW 10 part 2 of 2

© SAP AG TAW10 6-56

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

ENDCLASS.

Page 194: TAW 10 part 2 of 2

© SAP AG TAW10 6-57

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 *

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

Page 195: TAW 10 part 2 of 2

© SAP AG TAW10 6-58

*------------------------------------------------------------------*

* 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 type saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacity.

DATA: name TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i.

ENDCLASS. "lcl_airplane DEFINITION

Page 196: TAW 10 part 2 of 2

© SAP AG TAW10 6-59

*------------------------------------------------------------------*

* CLASS lcl_airplane IMPLEMENTATION *

*------------------------------------------------------------------*

CLASS lcl_airplane IMPLEMENTATION.

METHOD constructor.

name = im_name.

planetype = im_planetype.

n_o_airplanes = n_o_airplanes + 1.

ENDMETHOD. "constructor

METHOD display_attributes.

data: weight type saplane-weight,

cap type saplane-tankcap.

WRITE: / icon_ws_plane AS ICON,

/ 'Name of airplane'(001), AT pos_1 name,

/ 'Airplane type: '(002), AT pos_1 planetype.

get_technical_attributes( exporting im_type = planetype

importing ex_weight = weight

ex_tankcap = cap ).

write: / 'wheight: '(003), weight,

'tankcap: '(004), 60 cap.

ENDMETHOD. "display_attributes

METHOD display_n_o_airplanes.

WRITE: /, / 'Number of airplanes: '(ca1),

AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.

ENDMETHOD. "display_n_o_airplanes

METHOD get_technical_attributes.

SELECT SINGLE weight tankcap FROM saplane

INTO (ex_weight, ex_tankcap)

WHERE planetype = im_type.

IF sy-subrc <> 0.

ex_weight = 100000.

ex_tankcap = 10000.

ENDIF.

ENDMETHOD. "get_technical_attributes

ENDCLASS. "lcl_airplane IMPLEMENTATION

Page 197: TAW 10 part 2 of 2

© SAP AG TAW10 7-1

SAP AG 2002

l Generalization / specialization of classes

Contents:

Inheritance

Page 198: TAW 10 part 2 of 2

© SAP AG TAW10 7-2

SAP AG 2002

l Define an inheritance relationship between classes

l Redefine methods

At the conclusion of this unit, you will be able to:

Inheritance: Unit Objectives

Page 199: TAW 10 part 2 of 2

© SAP AG TAW10 7-3

SAP AG 2002

lcl_truck- max_cargo- n_o_tanks- n_o_wheels

+... +get_cargo

Inheritance: UML Example

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

lcl_car- car_type- max_seats- accelertion

+... +get_type

lcl_bus- max_passengers- lavatory- television

+... +get_passengers

"is a" relationship

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

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

n The inheritance relationship is often described as an "is a" relationship: A truck is a vehicle.

Page 200: TAW 10 part 2 of 2

© SAP AG TAW10 7-4

SAP AG 2002

Multiple Inheritance?

Spe

cial

izat

ion

Gen

eral

izat

ion

Nomultiple inheritance

lcl_super1 lcl_super2

lcl_sub1 lcl_sub2 lcl_sub3

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.

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

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

n Inheritance is a "one-sided relationship": Subclasses know their direct superclasses, but (super)classes do not know their subclasses.

Page 201: TAW 10 part 2 of 2

© SAP AG TAW10 7-5

SAP AG 2002

Relationships Between Superclasses and Subclasses

l Common components only exist once in the superclass

n New components in the superclass are automatically available in subclasses

n 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

lcl_super

Inherited components

New components

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

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

Page 202: TAW 10 part 2 of 2

© SAP AG TAW10 7-6

SAP AG 2002

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.

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.

n The attributes of the superclass lcl_vehicle exist in the subclass lcl_truck; the method estimate_fuel is also available in the subclass.

n The subclass defines a method get_cargo. It is not visible in the superclass.

Page 203: TAW 10 part 2 of 2

© SAP AG TAW10 7-7

SAP AG 2002

CLASS lcl_truck IMPLEMENTATION.METHOD estimate_fuel.

...super->estimate_fuel(...)

ENDMETHOD.ENDCLASS.

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.Cannot change the interface

New implementation of methodAlways points to the

superclass component

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

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

n In the case of redefined methods, changing the interface (overloading) is not permitted; exception: Overloading is possible with the constructor.

n Within the redefined method, you can access components of the direct superclass using the SUPER reference.

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

Page 204: TAW 10 part 2 of 2

© SAP AG TAW10 7-8

SAP AG 2002

Inheritance and Redefining the Constructor

CLASS lcl_vehicle DEFINITION.PUBLIC SECTION.METHODS: constructor IMPORTING

im_make TYPE string.ENDCLASS.

CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.PUBLIC SECTION.METHODS: constructor IMPORTING im_make TYPE string

im_cargo TYPE ty_cargo.PRIVATE SECTION.DATA: max_cargo TYPE ty_cargo.

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.METHOD CONSTRUCTOR.make = im_make.

ENDMETHOD.ENDCLASS.

CLASS lcl_truck IMPLEMENTATION.METHOD constructor.

CALL METHOD super->constructor( im_make = im_make ).max_cargo = im_cargo.

ENDMETHOD.ENDCLASS.

Can change the interface

Call constructor of immediatesuperclass

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

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

Page 205: TAW 10 part 2 of 2

© SAP AG TAW10 7-9

SAP AG 2002

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 = 100im_a2 = 1000.

Rules for Calling the Constructor

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_1

a1constructor (im_a1:i)

lcl_2

lcl_3

a2constructor(im_a1, im_a2)

n The model described for instance constructors must also be taken into account for CREATE OBJECT.

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

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

Page 206: TAW 10 part 2 of 2

© SAP AG TAW10 7-10

SAP AG 2002

CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION. ...

PROTECTED SECTION.DATA tank TYPE REF TO lcl_tank.

PRIVATE SECTION.DATA make TYPE string.

ENDCLASS.

Inheritance and Visibility

l Public components

n Visible to all

n Direct access

l Protected components

n Only visible within the class and its subclasses

l Private components

n Only visible within the class

n No access from outside the class, not even from the subclass

lcl_vehicle- make- modell# tank...

+constructor+display_attributes+get_count

+ public# protected

- private

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

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

n In ABAP Objects, you must keep to the section sequence PUBLIC, PROTECTED, PRIVATE.

Page 207: TAW 10 part 2 of 2

© SAP AG TAW10 7-11

SAP AG 2002

(5) lcl_busPrivatePublic

Protected

Can be addressed "from outside" for all clients

Can only be addressed within the class

Inherited

tank

get_makeset_makeget_countdisplay_attributesestimate_fuel

Inherited

Visibility of Protected Components

n In this example, lcl_bus, a subclass of lcl_vehicle, can directly access the protected attribute tank. If the attribute was private, the subclasses would only be able to access tank using non-private methods.

Page 208: TAW 10 part 2 of 2

© SAP AG TAW10 7-12

SAP AG 2002

Rules for Redefining Methods

l Inherited methods can be redefined in subclasses

n Redefined methods must be re-implemented in subclasses

n The signature of redefined methods cannot be changed

n Static methods cannot be redefined

n In inheritance, static components are "shared":A class shares its non-private static attributes with all its subclasses

lcl_vehicles

lcl_car lcl_truck lcl_bus

estimate_fuel

The method is implemented in different ways

estimate_fuel estimate_fuel estimate_fuel

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.

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

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

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

Page 209: TAW 10 part 2 of 2

© SAP AG TAW10 7-13

SAP AG 2002

Redefining Methods: Example

METHOD estimate_fuel.DATA: total_weight ...

* just an example!total_weight = max_cargo +

weight. re_fuel = total_weight *

im_distance * factor.ENDMETHOD.

METHOD estimate_fuel.DATA: total_weight ...* just an example!total_weight = max_passengers *

average_weight + weight.re_fuel = total_weight *

im_distance * factor.ENDMETHOD.

lcl_bus

- max_passengers ...

+ constructor+ estimate_fuel

lcl_truck

- max_cargo...

+ constructor+ estimate_fuel

n In the above example, both redefined methods calculate the return code in different ways. The important point is that the semantics stay the same.

Page 210: TAW 10 part 2 of 2

© SAP AG TAW10 7-14

SAP AG 2002

l Define an inheritance relationship between classes

l Redefine methods

You are now able to:

Inheritance: Unit Summary

Page 211: TAW 10 part 2 of 2

© SAP AG TAW10 7-15

Inheritance Exercises

Unit: Inheritance

Topic: Creating Class Hierarchies

At the conclusion of these exercises, you will be able to:

• Define subclasses

• Redefine superclass methods in subclasses

Model solution: SAPBC401_INHS_MAIN_A SAPBC401_INHS_A include program Your program: ZBC401_##_MAIN_AIRPLANE ZBC401_##_AIRPLANE include program

1-1 Make both instance attributes of the class lcl_airplane visible to their subclasses (PRIVATE SECTION -> PROTECTED SECTION).

1-2 Create the subclass lcl_passenger_plane for the class lcl_airplane. Also, create this subclass in your include program.

1-2-1 The class is to have a private instance attribute max_seats with the same type as table field sflight-seatsmax.

1-2-2 A public constructor is to be defined and implemented in the class. This constructor provides all instance attributes in the class with values.

1-2-3 Redefine the method display_attributes of the class lcl_airplane, so that, using the redefined method, the WRITE statement displays all instance attributes.

1-3 Create the subclass lcl_cargo_plane for the class lcl_airplane. Also, create this subclass in your include program.

1-3-1 The class is to have a private instance attribute max_cargo with the same type as the table field scplane-cargomax.

1-3-2 A public constructor is to be defined and implemented in the class. This constructor provides all instance attributes in the class with values.

1-3-3 Redefine the method display_attributes of the class lcl_airplane, so that, using the redefined method, the WRITE statement displays all instance attributes.

Page 212: TAW 10 part 2 of 2

© SAP AG TAW10 7-16

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.

1-6 Can the method get_technical_attributes be called directly from the redefined method display_atributes of the subclass?

1-7 Is it necessary for the subclasses to directly access the attributes name and planetype of the superclass to initialize them? Or, to formulate it differently: If these attributes remained in the private visibility area of the superclass, how would the subclasses have to access the attributes?

Page 213: TAW 10 part 2 of 2

© SAP AG TAW10 7-17

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

Page 214: TAW 10 part 2 of 2

© SAP AG TAW10 7-18

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

*& 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. "constructor

Page 215: TAW 10 part 2 of 2

© SAP AG TAW10 7-19

METHOD display_attributes.

super->display_attributes( ).

WRITE: / 'Max Cargo = ', max_cargo.

ULINE.

ENDMETHOD. "display_attributes

ENDCLASS. "lcl_cargo_plane IMPLEMENTATION

Page 216: TAW 10 part 2 of 2

© SAP AG TAW10 7-20

*---------------------------------------------------------------------*

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

ENDCLASS. "lcl_passenger_plane IMPLEMENTATION

Page 217: TAW 10 part 2 of 2

© SAP AG TAW10 8-1

SAP AG 2002

l Cast

l Polymorphism

Contents:

Casting

Page 218: TAW 10 part 2 of 2

© SAP AG TAW10 8-2

SAP AG 2002

l Use casts

l Develop generic programs using polymorphism with inheritance

At the conclusion of this unit, you will be able to:

Casting: Unit Objectives

Page 219: TAW 10 part 2 of 2

© SAP AG TAW10 8-3

SAP AG 2002

Casting (1)

Narrowing castNarrowing cast

Widening cast Widening cast

Inheritance and polymorphism Inheritance and polymorphism

Page 220: TAW 10 part 2 of 2

© SAP AG TAW10 8-4

SAP AG 2002

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

CREATE OBJECT r_truck.

* Narrowing Castr_vehicle = r_truck

Principle of Narrowing Cast

r_truck

r_vehicle

r_vehicle

(5) lcl_truckPublic

Geerbtget_makeget_count

display_attributesset_attributesestimate_fuel

Redefiniert

get_cargo...

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

Page 221: TAW 10 part 2 of 2

© SAP AG TAW10 8-5

SAP AG 2002

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

* generic access to subclass serviceslevel = r_truck->estimate_fuel( 1000 ).

* Narrowing Castr_vehicle = r_truck.

* Use of the subclass instance in the superclass contextlevel = r_vehicle->estimate_fuel( 1000 ).

Compatibility and Narrowing Cast

l Instances from subclasses can be used in any context, in which the instances of the superclass appear

l The components inherited from the superclass can be addressed

l Generic access by the client is possible

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.

n Variables that point to a superclass instance can also refer to subclass instances at runtime. n 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.

n The description "up-cast" is also used. n 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.

Page 222: TAW 10 part 2 of 2

© SAP AG TAW10 8-6

SAP AG 2002

(4) lcl_bus

lcl_rental lcl_vehicles1..*1

(5) lcl _truck

(1) lcl_rental

PrivatePublicitab

?

The client

lcl_truck lcl_bus

(2) lcl_car

Generic Access?

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

Page 223: TAW 10 part 2 of 2

© SAP AG TAW10 8-7

SAP AG 2002

2 lcl _bus(1) lcl_rental

PrivatePublic

add_vehicle 3 lcl_truck

4 lcl_car

vehicle_list

...METHODS: add_vehicle IMPORTING im_vehicle TYPE REF TO lcl_vehicle....

The client

Preparations for Generic Access (1)

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

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

Page 224: TAW 10 part 2 of 2

© SAP AG TAW10 8-8

SAP AG 2002

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.

Preparations for Generic Access (2)

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

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

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

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

Page 225: TAW 10 part 2 of 2

© SAP AG TAW10 8-9

SAP AG 2002

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.

Polymorphism - Generic Access

(5) lcl_truckPublic

Geerbt /redefiniert

Estimate_fuel

(2) lcl_busPublic

Geerbt /redefiniert

Estimate_fuel

METHOD estimate_fuel. ...total_weight = max_passengers *

average_weight + weight.re_fuel = total_weight *

im_distance * factor.ENDMETHOD.

METHOD estimate_fuel. ...total_weight = max_cargo + weight.re_fuel = total_weight *

im_distance * factor.ENDMETHOD.

vehicle_list

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

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

Page 226: TAW 10 part 2 of 2

© SAP AG TAW10 8-10

SAP AG 2002

Static and Dynamic Types of References

l The static type of a reference variable

§ Is defined using TYPE REF TO

§ 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

DATA: r_vehicle TYPE REF TO lcl_vehicle.

r_vehicle

(5) lcl_truck

Inherited / redefined

Estimate_fuel

Estimate_fuel

(2) lcl_bus

Inherited / redefinedEstimate_fuel

Estimate_fuel

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.

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

n In the Debugger, the reference me can be used to determine the dynamic type.

Page 227: TAW 10 part 2 of 2

© SAP AG TAW10 8-11

SAP AG 2002

* Procedural realisation of the example without polymorphism

DATA: vehicle_list TYPE TABLE OF vehicle_list_type,vehicle TYPE vehicle_list_type, ...

...LOOP AT vehicle_list INTO vehicle.CASE vehicle-category.

WHEN 'TRUCK'.PERFORM estimate_fuel_truck USING ...

CHANGING fuel.WHEN 'BUS'.PERFORM estimate_fuel_bus USING ...

CHANGING fuel.ENDCASE.ADD fuel TO needed_fuel.

ENDLOOP.

name category ...

vehicle_list

Comparison to Procedural Programming

l In object-oriented programming, you do not need to change the coding if you add use cases

l In a procedural program, you would have to adjust CASE constructions, for example:

truck1bus1bus2truck2

truck3

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

Page 228: TAW 10 part 2 of 2

© SAP AG TAW10 8-12

SAP AG 2002

Narrowing castNarrowing cast

Widening cast Widening cast

Inheritance and polymorphism Inheritance and polymorphism

Casting (2)

Page 229: TAW 10 part 2 of 2

© SAP AG TAW10 8-13

SAP AG 2002

2 lcl_bus

(1) lcl_rental

PrivatePublic

get_max_cargo

3 lcl_truck

4 lcl _car

vehicle_list

The client

3 lcl_truck

max_cargo = 50

max_cargo = 30

METHOD get_max_cargo.DATA: r_vehicle TYPE REF TO lcl_vehicle.LOOP AT vehicle_list INTO r_vehicle.

* Problem: is this really a truck ?* Determine the max cargoENDLOOP.

ENDMETHOD.

Truck or other vehicle?

Use of Widening Cast

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

Page 230: TAW 10 part 2 of 2

© SAP AG TAW10 8-14

SAP AG 2002

(2) lcl_bus

5 lcl_rental(3) lcl_truck

(4) lcl_car

get_max_cargo

vehicle_list

(9) lcl_truck

max_cargo= 50

max_cargo= 30

METHOD get_max_cargo.DATA: r_vehicle TYPE REF TO lcl_vehicle,

r_truck TYPE REF TO lcl_truck.LOOP AT vehicle_list INTO r_vehicle.

TRY. r_truck ?= r_vehicle.

* put max cargo in variable re_cargo...CATCH cx_sy_move_cast_error.

* react on that cast errorENDTRY.

ENDLOOP.ENDMETHOD.

(1) lcl_rental

Widening Cast: Example

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

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

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

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

Page 231: TAW 10 part 2 of 2

© SAP AG TAW10 8-15

SAP AG 2002

Narrowing castNarrowing cast

Widening cast Widening cast

Inheritance and polymorphism Inheritance and polymorphism

Casting (3)

Page 232: TAW 10 part 2 of 2

© SAP AG TAW10 8-16

SAP AG 2002

Semantics and Use with Inheritance

l Inherited components must behave in subclasses exactly as they do in superclasses for all users

l When you redefine a method its semantics must remain the same; you cannot change the signature

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

Rules:

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

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

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

Page 233: TAW 10 part 2 of 2

© SAP AG TAW10 8-17

SAP AG 2002

Incorrect Use of Inheritance

l Inheritance is often used incorrectly:

n To simply reuse code

n Instead of additional attributes/aggregation/role concepts

n The use of inheritance does not always correspond to expectations in the real world

Rules:

car

car_red car_blue

SuperclassRectangular

change_width

change_height

Subclasssquare

design ?

design ?

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

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

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

Page 234: TAW 10 part 2 of 2

© SAP AG TAW10 8-18

SAP AG 2002

l Use casts

l Develop generic programs using polymorphism with inheritance

You are now able to:

Casting: Unit Summary

Page 235: TAW 10 part 2 of 2

© SAP AG TAW10 8-19

Casting Exercises

Unit: Casting

Topic: Polymorphism

At the conclusion of these exercises, you will be able to:

• Describe polymorphism and inheritance

• Use generic programming for inheritance relationships and implement polymorphic method calls

Model solution: SAPBC401_CASS_MAIN_A SAPBC401_INHS_A include program

1-1 Extend your existing program ZBC401_##_MAIN_AIRPLANE or start with the model solution from the last chapter’s exercises.

1-2 In your main program, define an internal table for buffering airplane objects. The type of the internal table should be REF TO lcl_airplane.

1-3 Try to insert the planes (passenger and cargo) into this internal table and execute the display_attributes method for every plane in a LOOP. Read the internal table in the LOOP using the auxiliary reference variable r_airplane (type REF TO lcl_airplane).

1-3-1 Was this successful?

1-3-2 Check the internal table and the execution of the display_attributes method in the Debugger

1-3-3 Which source code is executed when the display_attributes method is called, the original method from the superclass or the relevant redefined methods from the subclasses? What would happen if one of these methods had not been redefined in the subclass?

Page 236: TAW 10 part 2 of 2

© SAP AG TAW10 8-20

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

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

Page 237: TAW 10 part 2 of 2

© SAP AG TAW10 8-21

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'

Page 238: TAW 10 part 2 of 2

© SAP AG TAW10 8-22

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

Page 239: TAW 10 part 2 of 2

© SAP AG TAW10 8-23

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

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

Page 240: TAW 10 part 2 of 2

© SAP AG TAW10 8-24

*---------------------------------------------------------------------*

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

Page 241: TAW 10 part 2 of 2

© SAP AG TAW10 8-25

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.

Page 242: TAW 10 part 2 of 2

© SAP AG TAW10 9-1

SAP AG 2002

l Interfaces

l Compound interfaces

l Polymorphism

Contents:

Interfaces

Page 243: TAW 10 part 2 of 2

© SAP AG TAW10 9-2

SAP AG 2002

l Define and implement interfaces

l Develop generic programs using polymorphism with interfaces

At the conclusion of this unit, you will be able to:

Interfaces: Unit Objectives

Page 244: TAW 10 part 2 of 2

© SAP AG TAW10 9-3

SAP AG 2002

Interfaces: Principles Interfaces: Principles

Working with interfacesWorking with interfaces

Preview: Compound interfacesPreview: Compound interfaces

Interfaces (1)

Page 245: TAW 10 part 2 of 2

© SAP AG TAW10 9-4

SAP AG 2002

lcl_airplane lcl_vehicles

lcl_rental

Shared services

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

InterfacesInterfaces

lcl_carrier lcl_hotel

Service 1Service 2Service 3

...

?

Interfaces: Use

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

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

Page 246: TAW 10 part 2 of 2

© SAP AG TAW10 9-5

SAP AG 2002

lcl_airplane lcl_vehicles

lcl_rental

Client uses

Shared services

display_partnercheck_availability

...

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

InterfaceInterface

lcl_carrier lcl_hotel

Interfaces: Services

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

n The following are examples of shared services of the server classes in the above case: display_partner, check_availability, booking, or cancel_booking.

Page 247: TAW 10 part 2 of 2

© SAP AG TAW10 9-6

SAP AG 2002

Implementationmehrerer Interfacesmöglich !

It is possible to implement several interfaces

lcl_airplane lcl_vehicles

lcl_rentallcl_carrier

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

lcl_hotel

lcl_travel_agency

lif_partners

implements

usesClientClient

lif_license

...

<<Interface>><<Interface>> <<Interface>><<Interface>>

Interface: UML Example

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.

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

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

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

Page 248: TAW 10 part 2 of 2

© SAP AG TAW10 9-7

SAP AG 2002

Defining and Implementing an Interface

INTERFACE lif_partners.METHODS: display_partner.

ENDINTERFACE.

CLASS lcl_rental DEFINITION.PUBLIC SECTION.

INTERFACES lif_partners.ENDCLASS.

l Declaring the interface

l The server classes "make the interface public"

l Interfaces are implemented in classes

l Interfaces do not have visibility sections

CLASS lcl_rental IMPLEMENTATION.

METHOD lif_partners~display_partner.* just call existing method that fits

display_attributes( )....

ENDMETHOD.

ENDCLASS.

Interface resolution operator

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

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

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

n Changes to an interface usually invalidate all the classes implementing it.

Page 249: TAW 10 part 2 of 2

© SAP AG TAW10 9-8

SAP AG 2002

Code 2

Code 1

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

n The client defines the protocol, the server implements it

n "Black Box principle": Client only knows the interface, not the implementation

n Looser linkage between client and server

l Polymorphism

n Generic handling of objects of different classes

l Abstraction

n Interface as a generalization of the implementing class

l Simulation of multiple inheritance

super1

sub1 sub2

Interf.

Interfaces: Features

Code 4

Code 3display_partner

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

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

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

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

Page 250: TAW 10 part 2 of 2

© SAP AG TAW10 9-9

SAP AG 2002

Interfaces: Principles Interfaces: Principles

Working with interfacesWorking with interfaces

Preview: Compound interfacesPreview: Compound interfaces

Interfaces (2)

Page 251: TAW 10 part 2 of 2

© SAP AG TAW10 9-10

SAP AG 2002

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.

DATA: r_vehicle TYPE REF TO lcl_vehicle....

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

lcl_rental- name- vehicle_list

+ add_vehicle+ display_attributes ...

lif_partners

display_partnercheck_availability...

implements

Interface resolution operator

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.

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

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

Page 252: TAW 10 part 2 of 2

© SAP AG TAW10 9-11

SAP AG 2002

Interface References: Narrowing Cast

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

CREATE OBJECT r_rental.

* Narrowing Castr_lif = r_rental

r_rental

r_lif

r_lif

(1) lcl_rentalPublic

display_partnercheck_availability...

Interface components

Private

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.

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

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

n When an object reference is assigned to an interface reference, you must be able to convert the dynamic type of the interface reference to the static type of the object reference - that is, the class that was used to define the object reference must have implemented the interface of the interface-reference.

Page 253: TAW 10 part 2 of 2

© SAP AG TAW10 9-12

SAP AG 2002

2 lcl_hotel(9) lcl_travel_agency

PrivatePublic

add_partnerpartner_list

...METHODS: add_partner IMPORTING im_partner TYPE REF TO lif_partners....

2 lcl_rental

2 lcl_carrier

Using the Interface

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

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

n The aim here is polymorphism: It needs to be possible to generically access the services of the interface later.

Page 254: TAW 10 part 2 of 2

© SAP AG TAW10 9-13

SAP AG 2002

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.

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

ENDMETHOD.

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

partner_list

(1) lcl_rental

(7) lcl_hotel

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

(6) lcl_carrier

Polymorphism and Interfaces

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.

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

Page 255: TAW 10 part 2 of 2

© SAP AG TAW10 9-14

SAP AG 2002

5 lcl_rentalbook_flight

partner_list

METHOD book_flight.DATA: r_carrier TYPE REF TO lcl_carrier,

r_partner TYPE REF TO lcl_partner.LOOP AT partner_list INTO r_partner.

TRY. r_carrier ?= r_partner.

* call method of lcl_carrier to book flight...CATCH cx_sy_move_cast_error.

* react on that cast errorENDTRY.

ENDLOOP.ENDMETHOD.

3 lcl_travel_agency2 lcl_hotel

2 lcl_rental

2 lcl_carrier

Interface References: Widening Cast

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.

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

n 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 ?=.

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

Page 256: TAW 10 part 2 of 2

© SAP AG TAW10 9-15

SAP AG 2002

Interfaces: Principles Interfaces: Principles

Working with interfacesWorking with interfaces

Preview: Compound interfacesPreview: Compound interfaces

Interfaces (3)

Page 257: TAW 10 part 2 of 2

© SAP AG TAW10 9-16

SAP AG 2002

Compound Interfaces

lcl_rentallcl_carrier

InterfaceInterface

lcl_hotel

lif_partners book_room

Problem:Extending interfaces

lcl_hotel

InterfaceInterfacelif_room_booking

InterfaceInterfacelif_partners

lcl_carrier lcl_rental

Solution:Compound interfaces

?

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.

n One interface can be used as a component interface in several compound interfaces. n 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.

n Compound interfaces in ABAP Objects can always be seen as specializations of their component interfaces and represented as such in UML.

Page 258: TAW 10 part 2 of 2

© SAP AG TAW10 9-17

SAP AG 2002

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 TYPE REF TO lif_partners,i_room_book TYPE REF TO lif_room_booking,

...i_partner = i_room_book. “Narrowing Cast

i_room_book->lif_partners~display_partner( ).* i_partner->display_partner( ) also possible

i_room_book ?= i_partner. “Widening Cast

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

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

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

Page 259: TAW 10 part 2 of 2

© SAP AG TAW10 9-18

SAP AG 2002

l Define and implement interfaces

l Develop generic programs using polymorphism with interfaces

You are now able to:

Interfaces: Unit Summary

Page 260: TAW 10 part 2 of 2

© SAP AG TAW10 9-19

Interfaces Exercises

Unit: Interfaces

Topic: Defining Interfaces

At the conclusion of these exercises, you will be able to:

• Define and implement interfaces

Model solution: SAPBC401_INTS_MAIN_A SAPBC401_VEHD_F include program SAPBC401_INTS_A include program

1 The classes lcl_rental, lcl_vehicle, and their subclasses are to be added to the existing UML diagram. The classes lcl_rental, lcl_carrier, and later lcl_hotel will all store separate services and provide a possible client (to be defined later) using an interface lif_partners.

1-1 Add the interface lif_partners to your UML diagram. display_partner is to be the only interface method. What are the roles of the classes lcl_rental, lcl_carrier, and lcl_hotel? Depict this in the UML diagram by adding text and arrows. Fill in the UML diagram on the next page.

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

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

Page 261: TAW 10 part 2 of 2

© SAP AG TAW10 9-20

1-4 Now implement the interface of your class lcl_carrier.

1-5 In the main program, create some instances for lcl_rental, lcl_vehicle, and so on by copying the relevant code from the template SAPBC401_VEHT_MAIN_A. Call the method display_attributes of the class lcl_rental. Start your program. You should see an airline with your planes and a car rental company with various vehicles. (You will use the interface in the next exercise.)

UML-Template for Exercise 1-1

Page 262: TAW 10 part 2 of 2

© SAP AG TAW10 9-21

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

2 Now the class lcl_travel_agency (travel agency) is to be added to the existing UML diagram. It will use the interface to access the classes lcl_rental, lcl_carrier, lcl_hotel (not yet implemented).

2-1 Add the class lcl_travel_agency to your UML diagram. What is the role of this class? Depict this in the UML diagram by adding text and arrows. Fill in the UML diagram on the next page.

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

Page 263: TAW 10 part 2 of 2

© SAP AG TAW10 9-22

2-3 Go back to your main program.

2-4 Create an instance of the class lcl_travel_agency.

2-4-1 Use the add_partner method to add the travel agency’s business partners to the internal table.

2-4-2 Use the display_agency_partners method to display the travel agency’s business partners.

2-4-3 At which point does polymorphism take place? Follow this in the Debugger.

UML-Template for Exercise 2-1

Page 264: TAW 10 part 2 of 2

© SAP AG TAW10 9-23

Interfaces Solutions

Unit: Interfaces

Topic: Defining Interfaces

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

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

Page 265: TAW 10 part 2 of 2

© SAP AG TAW10 9-24

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

Page 266: TAW 10 part 2 of 2

© SAP AG TAW10 9-25

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

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

Page 267: TAW 10 part 2 of 2

© SAP AG TAW10 9-26

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

Page 268: TAW 10 part 2 of 2

© SAP AG TAW10 9-27

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

Page 269: TAW 10 part 2 of 2

© SAP AG TAW10 9-28

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

Page 270: TAW 10 part 2 of 2

© SAP AG TAW10 9-29

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

*& 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 constructor IMPORTING im_make TYPE string.

METHODS display_attributes.

METHODS set_make IMPORTING im_make TYPE string.

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

Page 271: TAW 10 part 2 of 2

© SAP AG TAW10 9-30

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

ELSE.

make = im_make.

ENDIF.

ENDMETHOD. "set_make

METHOD init_make.

make = 'default make'.

ENDMETHOD. "init_make

METHOD get_make.

ex_make = make.

ENDMETHOD. "get_make

METHOD display_attributes.

WRITE: make.

ENDMETHOD. "display_attributes

METHOD get_count.

re_count = n_o_vehicles.

ENDMETHOD. "get_count

ENDCLASS. "lcl_vehicle IMPLEMENTATION

*---------------------------------------------------------------------*

* CLASS lcl_truck DEFINITION

*---------------------------------------------------------------------*

CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.

PUBLIC SECTION.

"-------------------

Page 272: TAW 10 part 2 of 2

© SAP AG TAW10 9-31

METHODS: constructor IMPORTING im_make TYPE string

im_cargo TYPE ty_cargo.

METHODS display_attributes REDEFINITION.

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

Page 273: TAW 10 part 2 of 2

© SAP AG TAW10 9-32

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: 20 ' Passengers = ', max_passengers.

ULINE.

ENDMETHOD. "display_attributes

ENDCLASS. "lcl_vehicle DEFINITION

*---------------------------------------------------------------------*

* CLASS lcl_rental DEFINITION

*---------------------------------------------------------------------*

CLASS lcl_rental DEFINITION.

PUBLIC SECTION.

"-------------------

METHODS: constructor IMPORTING im_name TYPE string.

METHODS add_vehicle IMPORTING im_vehicle

TYPE REF TO lcl_vehicle.

Page 274: TAW 10 part 2 of 2

© SAP AG TAW10 9-33

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: / icon_transport_proposal AS ICON, name.

WRITE: ' Here comes the vehicle list: '. ULINE. ULINE.

LOOP AT vehicle_list INTO r_vehicle.

r_vehicle->display_attributes( ).

ENDLOOP.

ENDMETHOD. "display_attributes

ENDCLASS. "lcl_rental IMPLEMENTATION

*---------------------------------------------------------------------*

* CLASS lcl_travel_agency DEFINITION

*---------------------------------------------------------------------*

CLASS lcl_travel_agency DEFINITION.

PUBLIC SECTION.

"-------------------

METHODS: constructor IMPORTING im_name TYPE string.

Page 275: TAW 10 part 2 of 2

© SAP AG TAW10 9-34

METHODS add_partner IMPORTING im_partner

TYPE REF TO lif_partners.

METHODS display_agency_partners.

PRIVATE SECTION.

"-------------------

DATA: name TYPE string,

partner_list TYPE TABLE OF REF TO lif_partners.

ENDCLASS. "lcl_travel_agency DEFINITION

*---------------------------------------------------------------------*

* CLASS lcl_travel_agency IMPLEMENTATION

*---------------------------------------------------------------------*

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

ENDCLASS. "lcl_travel_agency IMPLEMENTATION

Page 276: TAW 10 part 2 of 2

© SAP AG TAW10 10-1

SAP AG 2002

l Defining and triggering events

l Registering and handling events

Contents:

Events

Page 277: TAW 10 part 2 of 2

© SAP AG TAW10 10-2

SAP AG 2002

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

At the conclusion of this unit, you will be able to:

Events: Unit Objectives

Page 278: TAW 10 part 2 of 2

© SAP AG TAW10 10-3

SAP AG 2002

Events: Overview

CarVehicle registration office

Car rental company

* main program

CREATE OBJECT r_car EXPORTING ...

Sender

Receiver / handler

...

Event: “vehicle_created”

n By triggering an event, an object or class announces a change of state, or that a certain state has been achieved.

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

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

Page 279: TAW 10 part 2 of 2

© SAP AG TAW10 10-4

SAP AG 2002

Features

l Looser linkage than for a method call

n Triggering object makes status change known

n 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

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.

n Events are most often used in GUI implementations. n Other external object models, such as COM, ActiveX controls, and so on, also provide events.

Page 280: TAW 10 part 2 of 2

© SAP AG TAW10 10-5

SAP AG 2002

Triggering and Handling Events: Overview

l Triggering events

§ Class defines event(EVENTS, CLASS-EVENTS)

§ Object or class triggers event (RAISE EVENT)

l Handling events

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

Rules:

1

2

3

4

n At the moment of implementation, a class defines its: ­ Instance events (using the EVENTS statement) ­ Static events (using the CLASS-EVENTS statement)

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

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

n A class or instance can trigger an event at runtime using the RAISE EVENT statement.

Page 281: TAW 10 part 2 of 2

© SAP AG TAW10 10-6

SAP AG 2002

Defining and Triggering Events: Syntax

CLASS <classname> DEFINITION.EVENTS: <event> EXPORTING VALUE(<ex_par>) TYPE <type>.

CLASS lcl_vehicle DEFINITION.PUBLIC SECTION.

METHODS constructor IMPORTING ... .EVENTS vehicle_created.

...

ENDCLASS.

CLASS <classname> IMPLEMENTATION.METHOD <m>.RAISE EVENT <event> EXPORTING <ex_par> = <act_par>.

CLASS lcl_vehicle IMPLEMENTATION.METHOD constructor.

...

RAISE EVENT vehicle_created.ENDMETHOD.

ENDCLASS.

car

1

2

“vehicle_created”

n Both instance and static events can be triggered in instance methods. n Only static events can be triggered in static methods. n Events can only have EXPORTING parameters which must be passed by value. n 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

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

Page 282: TAW 10 part 2 of 2

© SAP AG TAW10 10-7

SAP AG 2002

Handling and Registering Events

registrationoffice

rentalcar1

car2

truck

carrier

Interest in event?

Sender Handler

“vehicle_created”

n Events are registered using the SET HANDLER statement. Registration is only active at program runtime. Events cannot be persistent.

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

n When the event is triggered, the list shows which event handler methods need to be called.

Page 283: TAW 10 part 2 of 2

© SAP AG TAW10 10-8

SAP AG 2002

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

IMPORTING sender.ENDCLASS.

car1 rental

add_vehicle

3

“vehicle_created”

n Event handler methods are triggered by events (RAISE EVENT), although they can also be called like normal methods (CALL METHOD).

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

Page 284: TAW 10 part 2 of 2

© SAP AG TAW10 10-9

SAP AG 2002

CLASS lcl_rental IMPLEMENTATION.METHOD constructor.

...SET HANDLER add_vehicle FOR ALL INSTANCES.

ENDMETHOD.ENDCLASS.

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.

car1 rentalset handler

4

“vehicle_created”

n When an event is triggered, only those event handler methods are executed that have, by this point, registered themselves using SET HANDLER.

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

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

Page 285: TAW 10 part 2 of 2

© SAP AG TAW10 10-10

SAP AG 2002

Registration/Deregistration: Handler Tables

Handler table for "car2“

reg_vehicle

vehicle_created (event)Registeredobject

Handlermethod

car2

r_car

Handler table for "car1"

add_vehicle

vehicle_created (event)Registeredobject

Handlermethod

car1

r_car

reg_vehicle

registrationoffice

rental

registrationoffice

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.

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

Page 286: TAW 10 part 2 of 2

© SAP AG TAW10 10-11

SAP AG 2002

Event Handling: Features

l Event handling is sequential

l Sequence in which event handler methods are called is not defined

l 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 The visibility of an event defines authorization for event handling

l 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

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

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

n 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

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

Page 287: TAW 10 part 2 of 2

© SAP AG TAW10 10-12

SAP AG 2002

l Define and trigger events

l Handle events

l Register and deregister events

l Explain the conceptual differences between methods and events

You are now able to:

Events: Unit Summary

Page 288: TAW 10 part 2 of 2

© SAP AG TAW10 10-13

Events Exercises

Unit: Events

Topic: Triggering and Handling Events

At the conclusion of these exercises, you will be able to:

• Define and trigger events

• Handle events

• Register event handler methods

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

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.

1-2 Trigger the event airplane_created in a suitable method within the class lcl_airplane.

1-3 Handle the event within the class lcl_carrier using the handler method add_airplane. This method requires a new interface, its implementation must also be changed slightly.

1-4 In the main program, comment out the calls r_carrier->add_airplane.

1-5 In the debugger, check whether the event is triggered and handled by the event handler method when the planes are created. If this does not happen, check whether one of the four important steps for implementing events was perhaps left out.

1-6 Optional:

Page 289: TAW 10 part 2 of 2

© SAP AG TAW10 10-14

Implement the event vehicle_created for the car rental company and its corresponding vehicles.

2 Optional (advanced): In the UML, there is the possibility of using events when creating the business partners of the travel agency. If airlines, car rental companies, or hotels are created, these business partners should automatically be made known to the travel agency.

2-1 You could solve this using the events carrier_created, rental_created, and hotel_created. Would this be problematic? What would be the best solution?

2-2 Implement your solution for lcl_carrier and lcl_rental.

Page 290: TAW 10 part 2 of 2

© SAP AG TAW10 10-15

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

Page 291: TAW 10 part 2 of 2

© SAP AG TAW10 10-16

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

Page 292: TAW 10 part 2 of 2

© SAP AG TAW10 10-17

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

*& 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 TYPE saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

ex_tankcap 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 = im_name.

planetype = im_planetype.

Page 293: TAW 10 part 2 of 2

© SAP AG TAW10 10-18

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.

Page 294: TAW 10 part 2 of 2

© SAP AG TAW10 10-19

"----------------------

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

Page 295: TAW 10 part 2 of 2

© SAP AG TAW10 10-20

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

ENDCLASS. "lcl_passenger_plane IMPLEMENTATION

*---------------------------------------------------------------------*

* CLASS lcl_carrier DEFINITION

*---------------------------------------------------------------------*

CLASS lcl_carrier DEFINITION.

PUBLIC SECTION.

"----------------------------------------

INTERFACES lif_partners.

METHODS: constructor IMPORTING im_name TYPE string,

Page 296: TAW 10 part 2 of 2

© SAP AG TAW10 10-21

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.

Page 297: TAW 10 part 2 of 2

© SAP AG TAW10 10-22

ex_name = name.

ENDMETHOD. "get_name

ENDCLASS. "lcl_carrier IMPLEMENTATION

Page 298: TAW 10 part 2 of 2

© SAP AG TAW10 10-23

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

Page 299: TAW 10 part 2 of 2

© SAP AG TAW10 10-24

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

Page 300: TAW 10 part 2 of 2

© SAP AG TAW10 10-25

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

*& 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 TYPE saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

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

Page 301: TAW 10 part 2 of 2

© SAP AG TAW10 10-26

name = im_name.

planetype = im_planetype.

n_o_airplanes = n_o_airplanes + 1.

RAISE EVENT airplane_created.

ENDMETHOD. "constructor

METHOD display_attributes.

DATA: weight TYPE saplane-weight,

cap TYPE saplane-tankcap.

WRITE: / icon_ws_plane AS ICON,

/ 'Name of airplane'(001), AT pos_1 name,

/ 'Type of airplane: '(002), AT pos_1 planetype.

get_technical_attributes( EXPORTING im_type = planetype

IMPORTING ex_weight = weight

ex_tankcap = cap ).

WRITE: / 'Weight:'(003), weight,

'Tankkap:'(004), cap.

ENDMETHOD. "display_attributes

METHOD display_n_o_airplanes.

WRITE: /, / 'Number of airplanes: '(ca1),

AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.

ENDMETHOD. "display_n_o_airplanes

METHOD get_technical_attributes.

SELECT SINGLE weight tankcap FROM saplane

INTO (ex_weight, ex_tankcap)

WHERE planetype = im_type.

IF sy-subrc <> 0. ex_weight = 100000. ex_tankcap = 10000. ENDIF.

ENDMETHOD. "get_technical_attributes

ENDCLASS. "lcl_airplane IMPLEMENTATION

...

*---------------------------------------------------------------------*

* 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 FOR EVENT airplane_created OF lcl_airplane

IMPORTING sender,

Page 302: TAW 10 part 2 of 2

© SAP AG TAW10 10-27

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

RAISE EVENT lif_partners~partner_created.

ENDMETHOD. "constructor

ENDCLASS. "lcl_carrier IMPLEMENTATION

Page 303: TAW 10 part 2 of 2

© SAP AG TAW10 10-28

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

*& 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 constructor IMPORTING im_make TYPE string.

METHODS display_attributes.

METHODS set_make IMPORTING im_make TYPE string.

METHODS 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

*---------------------------------------------------------------------*

Page 304: TAW 10 part 2 of 2

© SAP AG TAW10 10-29

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

ELSE.

make = im_make.

ENDIF.

ENDMETHOD. "set_make

METHOD init_make.

make = 'default make'.

ENDMETHOD. "init_make

METHOD get_make.

ex_make = make.

ENDMETHOD. "get_make

METHOD display_attributes.

WRITE: make.

ENDMETHOD. "display_attributes

METHOD get_count.

re_count = n_o_vehicles.

ENDMETHOD. "get_count

ENDCLASS. "lcl_vehicle IMPLEMENTATION

*---------------------------------------------------------------------*

* CLASS lcl_rental DEFINITION

*---------------------------------------------------------------------*

Page 305: TAW 10 part 2 of 2

© SAP AG TAW10 10-30

CLASS lcl_rental DEFINITION.

PUBLIC SECTION.

"-------------------

METHODS: constructor IMPORTING im_name TYPE string.

METHODS 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: / icon_transport_proposal AS ICON, name.

WRITE: ' Here comes the vehicle list: '. ULINE. ULINE.

LOOP AT vehicle_list INTO r_vehicle.

r_vehicle->display_attributes( ).

ENDLOOP.

ENDMETHOD. "display_attributes

Page 306: TAW 10 part 2 of 2

© SAP AG TAW10 10-31

ENDCLASS. "lcl_rental IMPLEMENTATION

*---------------------------------------------------------------------*

* CLASS lcl_travel_agency DEFINITION

*---------------------------------------------------------------------*

CLASS lcl_travel_agency DEFINITION.

PUBLIC SECTION.

"-------------------

METHODS: constructor IMPORTING im_name TYPE string.

METHODS add_partner for event partner_created of lif_partners

IMPORTING sender.

METHODS display_agency_partners.

PRIVATE SECTION.

"-------------------

DATA: name TYPE string,

partner_list TYPE TABLE OF REF TO lif_partners.

ENDCLASS. "lcl_travel_agency DEFINITION

*---------------------------------------------------------------------*

* CLASS lcl_travel_agency IMPLEMENTATION

*---------------------------------------------------------------------*

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

ENDCLASS. "lcl_travel_agency IMPLEMENTATION

Page 307: TAW 10 part 2 of 2

© SAP AG TAW10 11-1

SAP AG 2002

l Local versus global classes and interfaces

l Class Builder

Contents:

Global Classes and Interfaces

Page 308: TAW 10 part 2 of 2

© SAP AG TAW10 11-2

SAP AG 2002

l Describe the difference between local and global classes and interfaces

l Create global classes and interfaces using the Class Builder

At the conclusion of this unit, you will be able to:

Global Classes and Interfaces: Unit Objectives

Page 309: TAW 10 part 2 of 2

© SAP AG TAW10 11-3

SAP AG 2003

Class BuilderClass Builder

Working with global classes and interfacesWorking with global classes and interfaces

Global Classes / Interfaces (1)

Page 310: TAW 10 part 2 of 2

© SAP AG TAW10 11-4

SAP AG 2002

Review: Local Classes and Interfaces

REPORT prog1.

CLASS lcl_airplane DEFINITION....

ENDCLASS....

REPORT prog2.

DATA: r_airplane TYPE REF TO lcl_airplane.

...

l Local program classes

n Local classes are only visible in the program they were defined in

n No global access possible

n Not stored in the Repository, no where-used list, and so on

Programm-1Programm-2

n Local classes and interfaces are only known within the program in which they are defined and implemented.

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

Page 311: TAW 10 part 2 of 2

© SAP AG TAW10 11-5

SAP AG 2002

Global Classes and Interfaces

l ABAP Workbench development tool: Class Builder

l Tool for creating, testing, and managing global classes and interfaces

n Stored in Repository

n Generates the framework coding, for example CLASS <name> DEFINITION

n Manages the include programs in which the coding is stored

l Access from all programs using TYPE REF TO

l Customer namespace for global classes and interfaces: Y* or Z*

l Where-used list available

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.

n Global class and interface names share the same namespace. n Individual methods of global classes and interfaces can be transported separately.

Page 312: TAW 10 part 2 of 2

© SAP AG TAW10 11-6

SAP AG 2002

Diese Knöpre hierbrauche ich auch

Package

ZBC401_00

Report MIME RepositoryRepository BrowserRepository Information SystemTag LibraryTransport Organizer

Object Name Description

privateprotectedpublicabstract

Creating Global Classes in the Object Navigator

Instance creation

Normal ABAP classException classPersistent class

Final classOnly modeled

ZBC401_00Class Library

Classes

Create a class in the Object Navigator

Workbench Edit Goto Utilities Environment System Help

n You can also display the Class Builder's global classes in the Object Navigator. n Being able to view classes through the navigation window on the left is especially useful when

developing code. n 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. n 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. n 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)

Page 313: TAW 10 part 2 of 2

© SAP AG TAW10 11-7

SAP AG 2002

Class Builder: Attributes

Class Edit Goto Utilities Environment System Help

Class Builder: Change Class ZCL_AIRPLANE_00

Methods

Attribute

Name

Level Visib. Re. Typing Assoc. Type DescriptionMod.

Events Internal Types AliasesAttributesFriendsInterfacesProperties

PLANE _TYPE

N_O_AIRPLANES

Type STRING Name of airplane

Type SAPLANE Airplane type

Type I Number of airplanes

Class Interface ZCL_AIRPLANE_00 Implemented/Active

Class Constructor

Instan Priv

Instan Priv

Static Priv

Filter

Define class attributes

n In the Class Builder, choosing the Attributes tab displays the class attributes and their properties (instance attribute/static attribute and the visibility area)

Page 314: TAW 10 part 2 of 2

© SAP AG TAW10 11-8

SAP AG 2002

Class Builder: Methods

Class Edit Goto Utilities Environment System Help

Class Builder: Change Class ZCL_ AIRPLANE_00

Methods

CONSTRUCTOR

Airplane attributes

Number of planes

Parameters Exceptions

CONSTRUCTOR

Level Visibility Met. Description

Events Internal Types AliasesAttributeFriendsInterfacesProperties

DISPLAY ATTRIBUTES

DISPLAY_N_O_AIRPLANES

Class Interface ZCL_AIRPLANE_00 Implemented/Active

Methods

Instance Method Public

Instance Method Public

Static Method Public

Define signature of selected method,

here: CONSTRUCTOR

Constructor

Define class methods

Mod.

n Under the Methods tab, you can create methods. n 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. n Choose Parameter to define the signature for the method the cursor is currently on.

Page 315: TAW 10 part 2 of 2

© SAP AG TAW10 11-9

SAP AG 2002

Class Edit Goto Utilities Environment System Help

Class Builder: Change Class ZCL_ AIRPLANE_00

Methods

CONSTRUCTOR

Airplane attributes

Number of planes

Parameters Exceptions

CONSTRUCTOR

Level Visibility Met. Description

Events Internal Types AliasesAttributeFriendsInterfacesProperties

DISPLAY ATTRIBUTES

DISPLAY_N_O_AIRPLANES

Class Interface ZCL_AIRPLANE_00 Implemented/Active

Methods

Instance Method Public

Instance Method Public

Static Method Public

ZIF_FLY~START Interface Method Public Preparations for start

2) Method implementation of a global interface

Class Builder: Interface Methods

Mod.

1) Announce a global interface in a global class

n A global interface that was created in the Class Builder can be announced in a server class by choosing the Interfaces tab.

n All interface methods are then automatically listed under the Methods tab. n All interface methods must then be implemented in this server class. In the example, the interface zif_fly consists of a single method start.

Page 316: TAW 10 part 2 of 2

© SAP AG TAW10 11-10

SAP AG 2002

Class Builder: Method Interface

Class Edit Goto Utilities Environment System Help

Class Builder: Change Class ZCL_AIRPLANE_00

Methods Events Internal Types AliasesAttributesFriendsInterfacesProperties

Methods Exceptions

IM_ NAME

P O Typing Assoc. Type Default Value Description

IM_PLANETYPE

Type STRING

Type SAPLANE-... Plane type

Type C

Type C

Method Parameters CONSTRUCTOR

Class Interface ZCL_AIRPLANE_00 Implemented/Active

Constructor

Parameter

Signature parameters of method,

here: CONSTRUCTOR

n Selecting a method and choosing Parameters displays a list of all the method's signature parameters.

Page 317: TAW 10 part 2 of 2

© SAP AG TAW10 11-11

SAP AG 2002

Class Builder: Method Implementation

Class Builder: Change Class ZCL_ AIRPLANE_00

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

ENDMETHOD.

Signature

Method CONSTRUCTOR active

Type

IM_NAME TYPE STRING

IM_PLANETYPE TYPE SAPLANE-PLANETYPE Plane type

Type spec. DescriptionParameters

Display the interface to help with implementing the method

Display the interface to help with implementing the method

Method Edit Goto Utilities Environment System Help

n When implementing methods, you can also display the signature of the method to aid your work. n In this example (constructor), the signature consists of the import parameters im_make and im_planetype.

Page 318: TAW 10 part 2 of 2

© SAP AG TAW10 11-12

SAP AG 2002

Class Builder: Inheritance

Class Edit Goto Utilities Environment System Help

Class Builder: Change Class CL_VEHICLE

Methods Events Internal Types AliasesAttributesFriendsInterfacesProperties

Class Interface ZCL_CARGO_PLANE_00 Implemented/Active

Class Constructor

Announce superclass

SuperclassSuperclass

Superclass ZCL_AIRPLANE_00

Description

Instantiation

...

...

Final...

n In the Class Builder, inheritance relationships are defined by choosing the Properties tab. n Here, for example, is the Superclass function, which you can use to specify the superclass for the

current class. n In this example, the superclass ZCL_AIRPLANE_00 is specified for the subclass ZCL_CARGO_PLANE_00.

Page 319: TAW 10 part 2 of 2

© SAP AG TAW10 11-13

SAP AG 2002

Instance

Create an instance with the test environment

DISPLAY_N_O_AIRPLANES

Upper/Lower Case Active

ZCL_AIRPLANE_00

AttributesMethods

TestObject->

Upper/Lower Case Active

ZCL_AIRPLANE_00 45<CL_AIRPLANE_00

InterfacesAttributesMethods

DISPLAY_ATTRIBUTESDISPLAY_N_O_AIRPLANES

Class Builder: Test Environment

Class Edit Goto Utilities

Test Class ZCL_AIRPLANE_00

Test Class ZCL_AIRPLANE_00Handler

Handler

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

Page 320: TAW 10 part 2 of 2

© SAP AG TAW10 11-14

SAP AG 2003

Class BuilderClass Builder

Working with global classes and interfacesWorking with global classes and interfaces

Global Classes / Interfaces (2)

Page 321: TAW 10 part 2 of 2

© SAP AG TAW10 11-15

SAP AG 2002

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

EXPORINGIMPORTING ...

Diese Knöpre hierbrauche ich auch

Class/Interface

ZCL_AIRPLANE_00

Report zdemo ActiveMIME RepositoryRepository BrowserRepository Information SystemTag LibraryTransport Organizer

ZCL_AIRPLANE_00 Class Airplane e

Attributes

n NAME Name of airplanen N_O_AIRPLANES Number of planesn PLANE _TYPE Airplane type

Methods

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

Object Name Description

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

Right: Edit an ABAP program in the Editor

ABAP Editor: Report zdemo

Global Classes in the Object Navigator

Workbench Edit Goto Utilities Environment System Help

Pattern

n You can also display the Class Builder's global classes in the Object Navigator. n 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).

Page 322: TAW 10 part 2 of 2

© SAP AG TAW10 11-16

SAP AG 2002

Report zdemo Active

********************************************************************** XY_00_airplane********************************************************************** XY_00_airplaneCLASS lcl_airplane DEFINITION.

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

CREATE OBJECT r_airplane EXPORING ...IMPORTING ...

Diese Knöpre hierbrauche ich auch

Class/Interface

ZCL_AIRPLANE_00

MIME RepositoryRepository BrowserRepository Information SystemTag Library

Transport Organizer

ZCL_AIRPLANE_00 Class Airplane e

Attributes

n NAME Name of airplanen N_O_AIRPLANES Number of planesn PLANE _TYPE Airplane type

Methods

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

Object Name Description

Selecting and dragging into the Editor creates CREATE OBJECT

ABAP Editor: Report zdemo

Class Builder: CREATE OBJECT

Workbench Edit Goto Utilities Environment System Help

Pattern

n Drag & drop the class name: Instantiates an object. n 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.

Page 323: TAW 10 part 2 of 2

© SAP AG TAW10 11-17

SAP AG 2002

********************************************** XY_00_airplane********************************************** XY_00_airplaneclass lcl airplane definition

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

Diese Knöpre hierbrauche ich auch

Class/Interface

ZCL_AIRPLANE_00

Report zdemo ActiveMIME RepositoryRepository BrowserRepository Information SystemTag Library

Transport Organizer

ZCL_AIRPLANE_00 Class Airplane e

Attributes

n NAME Name of airplanen N_O_AIRPLANES Number of planesn PLANE _TYPE Airplane type

Methods

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

Object Name Description

CALL METHOD xxx->display_attributes

Selecting and dragging into the Editor creates CALL METHOD

ABAP Editor: Report zdemo

Class Builder: CALL METHOD

Workbench Edit Goto Utilities Environment System Help

Pattern

n Drag & drop the method name: Calls a method n 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.

Page 324: TAW 10 part 2 of 2

© SAP AG TAW10 11-18

SAP AG 2002

l Describe the difference between local and global classes and interfaces

l Create global classes and interfaces using the Class Builder

You are now able to:

Global Classes and Interfaces: Unit Summary

Page 325: TAW 10 part 2 of 2

© SAP AG TAW10 11-19

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 Create the global class ZCL_##_HOTEL in the Class Builder.

1-2 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

1-3 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

1-4 Implement these methods.

1-5 Activate and test your class using the Class Builder test tool.

Page 326: TAW 10 part 2 of 2

© SAP AG TAW10 11-20

2 Define the global interface ZIF_##_PARTNERS with the interface method display_partner. Implement the interface in the class ZCL_##_HOTEL.

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

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.

lcl_carrier

lcl_airplane lcl_vehicles

lcl_car_rental

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

lcl_hotel

zif_partners

implements

lcl_travel_agency

uses

Page 327: TAW 10 part 2 of 2

© SAP AG TAW10 11-21

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

Page 328: TAW 10 part 2 of 2

© SAP AG TAW10 11-22

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

Page 329: TAW 10 part 2 of 2

© SAP AG TAW10 12-1

SAP AG 2002

l Abstract and final classes

l Visibility of constructors

l Friends

l Object Services

Contents:

Special Techniques

Page 330: TAW 10 part 2 of 2

© SAP AG TAW10 12-2

SAP AG 2002

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

At the conclusion of this unit, you will be able to:

Special Techniques: Unit Objectives

Page 331: TAW 10 part 2 of 2

© SAP AG TAW10 12-3

SAP AG 2002

Abstract and final classesAbstract and final classes

Visibility of constructorsVisibility of constructors

The friend concept The friend concept

Persistent objectsPersistent objects

Special Techniques (1)

Page 332: TAW 10 part 2 of 2

© SAP AG TAW10 12-4

SAP AG 2002

CLASS lcl_vehicle DEFINITION ABSTRACT.PUBLIC SECTION.METHODS estimate_fuel_consumption ABSTRACT

IMPORTING ...ENDCLASS.

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

n References to abstract classes can refer to instances of subclasses

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

n They must be redefined in subclasses

Class cannot be instantiated

Method not implemented in this class

Abstract Classes

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

n Abstract classes are normally used as an incomplete blueprint for concrete (that is, non-abstract) subclasses, for example to define a uniform interface.

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

n Classes with at least one abstract method are themselves abstract. n Static methods and constructors cannot be abstract (they cannot be redefined).

Page 333: TAW 10 part 2 of 2

© SAP AG TAW10 12-5

SAP AG 2002

CLASS lcl_truck DEFINITION FINALINHERITING FROM lcl_vehicle.

...ENDCLASS.

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

ENDCLASS.

l Final methods cannot be redefined in subclasses

l Final classes cannot have subclasses

vehicle

truck bus

... ......

Final Classes

n A final class cannot have subclasses, and can protect itself in this way against (uncontrolled) specialization.

n A final method in a class cannot be redefined in a subclass, and can protect itself in this way against (uncontrolled) redefinition.

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

Page 334: TAW 10 part 2 of 2

© SAP AG TAW10 12-6

SAP AG 2002

Abstract and final classesAbstract and final classes

Visibility of constructorsVisibility of constructors

The friend concept The friend concept

Persistent objectsPersistent objects

Special Techniques (2)

Page 335: TAW 10 part 2 of 2

© SAP AG TAW10 12-7

SAP AG 2002

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

n CREATE PUBLICEvery user (client) can create instances of a class(default setting)

n CREATE PROTECTEDOnly the class itself and all its subclasses can create instances of this class

n CREATE PRIVATEOnly the class can create instances of itself

l This implicitly controls the visibility of the class

l Possible use: Singleton concept

(1) lcl_singleton

PrivatePublic

r_singl

get_singleton

Client

Who Can Instantiate Classes?

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

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

Page 336: TAW 10 part 2 of 2

© SAP AG TAW10 12-8

SAP AG 2002

Abstract and final classesAbstract and final classes

Visibility of constructorsVisibility of constructors

The friend concept The friend concept

Persistent objectsPersistent objects

Special Techniques (3)

Page 337: TAW 10 part 2 of 2

© SAP AG TAW10 12-9

SAP AG 2002

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

n Methods that access the same data can therefore be spread over several classes

n Package creation support

flight_list

(5) lcl_flight_data(3) lcl_flight_factory

create_flightget_flightdelete_flight

Package

...

FriendFriendProvides friendship

Friends

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

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

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

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

Page 338: TAW 10 part 2 of 2

© SAP AG TAW10 12-10

SAP AG 2002

Abstract and final classesAbstract and final classes

Visibility of constructorsVisibility of constructors

The friend concept The friend concept

Persistent objectsPersistent objects

Special Techniques (4)

Page 339: TAW 10 part 2 of 2

© SAP AG TAW10 12-11

SAP AG 2002

ABAP program

Persistence service

Database

Transient objects

Persistent data in tables

Read/write objects

Persistence Service

n The persistence service helps the programmer to work object-oriented with data in relational databases.

n In principle, ABAP programs work with data and objects that exist(s) in the internal session at runtime. They are transient when the program is stopped. If this data is to be stored program-independently, that is persistently, it must be stored in the database. (You could also use files on operating system level.)

n 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 re-imported.

Page 340: TAW 10 part 2 of 2

© SAP AG TAW10 12-12

SAP AG 2002

l Objects of a running ABAP program are transient

l The persistence service allows you to work with persistent objects

l Persistent classes are created in the Class Builder

l Persistence service tasks

n Loading the objects from the database

n Managing changes to the objects

n Storing the objects in the database

Normal ABAP Class

Create Class CL_PERSISTENT_CLASS

Exception Class

Persistent Class ...

Class Type

Features of the Persistence Service

n To use the persistence service for objects, their classes must be created as so-called persistent classes in the Class Builder.

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

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

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

Page 341: TAW 10 part 2 of 2

© SAP AG TAW10 12-13

SAP AG 2002

...DATA: r_carrier TYPE REF TO cl_carrier,

r_agent TYPE REF TO ca_carrier, carrname TYPE s_carrname.

r_agent = ca_carrier=>agent.

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.

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

n Technically, the agent is a singleton, which is addressed using the public static attribute AGENT

The agent, a singleton of the class CA_CARRIER and friend of the persistent class CL_CARRIER

Class Agent

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

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

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

n The class actor manages one or more objects of the relevant persistent class. These objects must have different keys.

Page 342: TAW 10 part 2 of 2

© SAP AG TAW10 12-14

SAP AG 2002

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

You are now able to:

Special Techniques: Unit Summary

Page 343: TAW 10 part 2 of 2

© SAP AG TAW10 12-15

Exercises - optional

Unit: Special Techniques

Topic: Singleton Classes

At the conclusion of these exercises, you will be able to:

• Create a singleton; requirement for next exercise

Model solution: CL_SINGLETON SAPBC401_SPCS_MAIN_A

1 (Advanced) Create the global class ZCL_##_SINGLETON in the Class Builder. The following must be specified for the class:

1-1 You must be able to be instantiate the class only once. (Tip: Instantiation should take place automatically when the class is first accessed.)

1-2 Instantiation only takes place within the class.

1-3 The class has a static reference variable r_singleton that refers to the instantiated object.

1-4 The class has a static reference variable r_singleton that refers to the instantiated object.

2 In the main program ZBC401_##_MAIN_SPECIAL, instantiate the singleton class ZCL_##_SINGLETON by calling the get_singleton method.

2-1 Why must the get_singleton method in this example be static?

2-2 Verify your blueprint by calling get_singleton several times. (Debug.) When does instantiation take place and how often?

Page 344: TAW 10 part 2 of 2

© SAP AG TAW10 12-16

Exercises - optional

Unit: Special Techniques

Topic: Concluding Project Exercise

At the conclusion of these exercises, you will be able to:

• Create a “friends” relationship and access the data of a class providing the friendship (a singleton) from the befriended class (Note that the friends concept is mainly used in bigger projects with more complex classes)

Model solution: CL_AGENCY SAPBC401_SPCS_MAIN_B

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

3-2 When instantiating the singleton, this internal table is to be automatically filled with the flight connections from the table SPFLI.

4 Create a global class ZCL_##_AGENCY, which is to be provided friendship by the singleton.

4-1 Define and implement a constructor for ZCL_##_AGENCY. In the constructor, the private attribute of the class name is to be initialized.

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

Page 345: TAW 10 part 2 of 2

© SAP AG TAW10 12-17

4-2-3 In the method, the internal table of the class providing the friendship is to be accessed in a single record access. (READ TABLE...) If the requested record does not exist, it is sufficient in this example to display an appropriate message using the WRITE statement.

5 Go back to the singleton class. Here, provide friendship to the class ZCL_##_AGENCY.

6 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‘)

connection_list

(1) cl_singleton (3) lcl_agency

get_ connection

friend

Page 346: TAW 10 part 2 of 2

© SAP AG TAW10 12-18

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

Page 347: TAW 10 part 2 of 2

© SAP AG TAW10 12-19

Solutions - optional

Unit: Special Techniques

Topic: Concluding Project Exercise

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

*& Report SAPBC401_spcS_MAIN_B *

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

*& Practice with singleton & friends (show package concept )

*&

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

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

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.

Page 348: TAW 10 part 2 of 2

© SAP AG TAW10 13-1

SAP AG 2002

l Predefined exceptions and exceptions you define yourself

l Raising, handling, and passing along exceptions

Contents:

Exception Handling

Page 349: TAW 10 part 2 of 2

© SAP AG TAW10 13-2

SAP AG 2002

l Create your own exception classes

l Raise exceptions in a program

l Handle exceptions

l Pass exceptions along

At the conclusion of this unit, you will be able to:

Exception Handling: Unit Objectives

Page 350: TAW 10 part 2 of 2

© SAP AG TAW10 13-3

SAP AG 2002

Class-Based Exceptions: Overview

cx_exception...

...

Exception class (either predefined or defined by you)

...RAISE EXCEPTION TYPE cx_exception

[EXPORTING attr1 = ...attr2 = ...].

...* Exception handling...

ABAP runtime system

Exception raised either in ABAP statement or by runtime system

ABAP program

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

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

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

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

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

Page 351: TAW 10 part 2 of 2

© SAP AG TAW10 13-4

SAP AG 2002

Exception Classes: The Inheritance Hierarchy

cx_static_checkcx_dynamic_checkcx_no_check

cx_sy_move_cast_errorcx_sy_arithmetic_error

cx_sy_arithmetic_overflow

textidkernel_errid...

get_textget_source_position

cx_root

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

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

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

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

Page 352: TAW 10 part 2 of 2

© SAP AG TAW10 13-5

SAP AG 2002

TRY.

...

CATCH cx_... cx_... ... [INTO r_exc1].

...

CATCH cx_... ... [INTO r_exc2].

...

CLEANUP.

...

ENDTRY.

Handling Exceptions

Code whose exceptions (if any) are to be

handled

Handlers for the specified

exception classes and their

subclasses

Block for "tidying up" if there is no handler available in the TRY-ENDTRY structure

Handlers for the specified exception classes and their

subclasses

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

n The TRY block contains the application code that is to handle the exceptions. If an exception occurs in the TRY block the system searches first for a CATCH statement (which will handle the exception) in the same TRY-ENDTRY structure and then step by step outwards in all the enclosing TRY-ENDTRY structures. If it finds one, it navigates to this handler. If it cannot find a handler but the TRY-ENDTRY structure is in a procedure, it then tries to pass the exception along to the calling program. (This will be discussed in more detail later.)

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

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

Page 353: TAW 10 part 2 of 2

© SAP AG TAW10 13-6

SAP AG 2002

Example: Handling a Predefined Exception

PARAMETERS: int1 TYPE i,int2 TYPE i.

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

...

TRY.result = int1 * int2.WRITE result.

CATCH cx_sy_arithmetic_overflow INTO r_exc.text = r_exc->get_text( ).MESSAGE text TYPE 'I'.

ENDTRY.

...

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

exception

Information

Overflow in the operation '*'

?

ii

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.

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

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

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

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

n The keyword documentation for each keyword lists the exception classes whose exceptions may occur when the appropriate ABAP statement is executed.

Page 354: TAW 10 part 2 of 2

© SAP AG TAW10 13-7

SAP AG 2002

Example: Using Your Own Exceptions

CLASS lcl_airplane IMPLEMENTATION....METHOD get_technical_attributes.

SELECT SINGLE weight tankcap FROM saplaneINTO (ex_weight, ex_tankcap)WHERE planetype = im_type.

IF sy-subrc <> 0.ex_weight = 100000.ex_tankcap = 10000.

ENDIF.

ENDMETHOD. ...ENDCLASS.

CLASS lcl_airplane DEFINITION....METHODS get_technical_attributes

IMPORTING im_type TYPE saplane-planetypeEXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacity....ENDCLASS.

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

have written

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

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

Page 355: TAW 10 part 2 of 2

© SAP AG TAW10 13-8

SAP AG 2002

Creating Your Own Exception Classes

Diese Knöpre hierbrauche ich auch

Report MIME RepositoryObject NavigatorRepository InfosystemTag LibraryTransport Organizer

Object Name Description

privatprotectedpublicabstract

Inherits From

Class Type:Usual ABAP ClassException ClassPersistent Class

Final ClassOnly modeled

ZBC401_00Class Library

Classes

Workbench Edit Goto Utilities Environment System Help

CX_STATICS_CHECK

ZCX_WRONG_PLANETYPEClassPackage

ZBC401_00

!

Pattern Pretty Printer

n Exceptions are represented by objects that are instances of exception classes. Defining an exception is thus synonymous with creating an exception class.

n Exception classes are generally defined globally. For special exceptions that will only occur within a single ABAP program however, you can also define local exception classes.

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

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

Page 356: TAW 10 part 2 of 2

© SAP AG TAW10 13-9

SAP AG 2002

Maintaining Your Own Attributes and Exception Texts

Class Edit Goto Utilities Environment System Help

Class Builder: Change Class ZCX_WRONG_PLANETYPE

Attribute Type Re Typing Associated TypeNu

TextsAttributes

CX_ROOT

TEXTID

PREVIOUS

KERNEL_ERRID

PL_TYPE

Type SOTR_CONC

Type SOTR_CONC

Type Re CX_ROOT

Type S380ERRID

Type SAPLANE-PLANETYPE

Class Interface ZCX_WRONG_PLANETYPE Implemented/Active

Class Documentation

Const.. Pub..

Instan.. Pub..

Instan.. Pub..

Instan.. Pub..

Instan.. Pub..

FilterYour own attributes

provide the user with additional information

!

!

!

!

Exception text used to describe

exception situation in more detail

Exception ID Text

CX_ROOT An exception occurred

ZCX_WRONG_PLANETYPE This airplane type is unknown

n The methods are all inherited from CX_ROOT. You can also add your own methods. The instance constructor is generated automatically.

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

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

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

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

Page 357: TAW 10 part 2 of 2

© SAP AG TAW10 13-10

SAP AG 2002

METHOD get_technical_attributes.

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

SELECT SINGLE weight tankcap FROM saplaneINTO (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.

Raising and Handling Exceptions You Have Written

Example:im_type = A390-200

Information

The airplane type A390-200 is unknown

ii

?

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

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

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

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

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

Page 358: TAW 10 part 2 of 2

© SAP AG TAW10 13-11

SAP AG 2002

Passing Exceptions Along

CLASS class IMPLEMENTATION....METHOD meth....RAISE EXCEPTION TYPE cx_exception.ENDMETHOD.ENDCLASS.

CLASS class DEFINITION....METHODS meth IMPORTING <im_parameter>

EXPORTING <ex_parameter>RAISING cx_exception.

...ENDCLASS.

REPORT propagate_exceptions....DATA r_obj TYPE REF TO class....

TRY.r_obj->meth( EXPORTING ...

IMPORTING ... ).

CATCH cx_exception....

ENDTRY.

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

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.

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

n To pass along an exception from a procedure, you generally use the RAISING addition when defining the procedure interface.

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

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

Page 359: TAW 10 part 2 of 2

© SAP AG TAW10 13-12

SAP AG 2002

Example: Passing Exceptions Along

METHOD get_technical_attributes.

SELECT SINGLE weight tankcapFROM saplaneINTO (ex_weight, ex_tankcap)WHERE planetype = im_type.

IF sy-subrc <> 0.

RAISE EXCEPTIONTYPE zcx_wrong_planetypeEXPORTING pl_type = im_type.

ENDIF.

ENDMETHOD.

CLASS lcl_airplane DEFINITION.METHODS display_attributes.METHODS get_technical_attributes

IMPORTING im_type TYPE saplane-planetypeEXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacityRAISING 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 = planetypeIMPORTING ex_weight = weight

ex_tankcap = cap ).WRITE: /'Gewicht:'(003), weight,

'Tankkapazität:'(004), cap.CATCH zcx_wrong_planetype INTO r_exc.text = r_exc->get_text( ).MESSAGE text TYPE 'I'.

ENDTRY.ENDMETHOD.

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.

n To pass the exception along to the caller of the method, we enter it after the RAISING keyword. n 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.

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

Page 360: TAW 10 part 2 of 2

© SAP AG TAW10 13-13

SAP AG 2002

Exceptions That Must Be Declared

cx_dynamic_check cx_static_checkcx_no_check

cx_root

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

l Not part of syntax check

l You must handle these exceptions or pass them along explicitly using the RAISING addition

l Not part of syntax check

l You must handle these exceptions or pass them along explicitly using the RAISING addition

l Part of syntax check

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

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

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

Page 361: TAW 10 part 2 of 2

© SAP AG TAW10 13-14

SAP AG 2002

l Create your own exception classes

l Raise exceptions in a program

l Handle exceptions

l Pass exceptions along

You are now able to:

Exception Handling: Unit Summary

Page 362: TAW 10 part 2 of 2

© SAP AG TAW10 13-15

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.

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

Page 363: TAW 10 part 2 of 2

© SAP AG TAW10 13-16

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

Page 364: TAW 10 part 2 of 2

© SAP AG TAW10 13-17

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 TYPE saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacity

RAISING cx_bc401_invalid_planetype.

DATA: name TYPE string,

planetype TYPE saplane-planetype.

Page 365: TAW 10 part 2 of 2

© SAP AG TAW10 13-18

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)

Page 366: TAW 10 part 2 of 2

© SAP AG TAW10 13-19

WHERE planetype = im_type.

IF sy-subrc <> 0.

RAISE EXCEPTION TYPE cx_bc401_invalid_planetype

EXPORTING planetype = im_type.

ENDIF.

ENDMETHOD. "get_technical_attributes

ENDCLASS. "lcl_airplane IMPLEMENTATION

Page 367: TAW 10 part 2 of 2

© SAP AG TAW10 14-1

SAP AG 2002

l Dynamic attributes

l Data reference variables

l Field symbols

l Runtime Type Identification (RTTI)

Contents:

Dynamic Programming

Page 368: TAW 10 part 2 of 2

© SAP AG TAW10 14-2

SAP AG 2002

l Use dynamic attributes in suitable ABAP statements

l Use data objects generated at runtime

l Ascertain the attributes of data objects at runtime

At the conclusion of this unit, you will be able to:

Dynamic Programming: Unit Objectives

Page 369: TAW 10 part 2 of 2

© SAP AG TAW10 14-3

SAP AG 2002

Field Symbols in DetailField Symbols in Detail

Dynamic CallsDynamic Calls

Data ReferencesData References

Dynamic Programming (1)

Ascertaining Data Attributes DynamicallyAscertaining Data Attributes Dynamically

Page 370: TAW 10 part 2 of 2

© SAP AG TAW10 14-4

SAP AG 2002

Field Symbols

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.

15 fs_int int

15 fs_int int

FIELD-SYMBOLS <fs> TYPE|LIKE ... |TYPE ANY}.ASSIGN ... dataobject TO <fs>.UNASSIGN <fs>.... <fs> IS ASSIGNED ...

Generic or complete type specification

17 fs_int int

17 fs_int int

n You declare field symbols using the FIELD-SYMBOLS <fs> statement. Note that the parentheses (<>) are part of the syntax.

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

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

n Use the expression <fs> IS ASSIGNED to find out whether the field symbol <fs> is assigned to a field.

n The statement UNASSIGN <fs>. sets the field symbol <fs> so that it points to nothing. The logical expression <fs> IS ASSIGNED is then false.

Page 371: TAW 10 part 2 of 2

© SAP AG TAW10 14-5

SAP AG 2002

The CASTING Addition

TYPES: BEGIN OF st_date,year(4) TYPE n,month(2) TYPE n,day(2) TYPE n,

END OF st_date.

* option 1: implicitFIELD-SYMBOLS <fs> TYPE st_date.ASSIGN sy-datum TO <fs> CASTING.

* access after casting:WRITE: / <fs>-year, <fs>-month, <fs>-day.

* option 2: explicitFIELD-SYMBOLS <fs> TYPE ANY.ASSIGN sy-datum TO <fs> CASTING TYPE st_date....

20011221

fs

...sy

date

... ...

...

ASSIGN ... dataobject TO <fs> CASTING [TYPE type|...] .

Inhalt des zugewiesenen Datenobjekts wird so interpretiert, als ob er den implizit bzw. explizit angegeben Typ hätte

The content of the assigned data object is interpreted as

if it had the implicit or explicit type specified

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.

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

n In the above example, note that the system field sy-datum is an elementary character-type component of length 8.

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

Page 372: TAW 10 part 2 of 2

© SAP AG TAW10 14-6

SAP AG 2002

Field Symbols in DetailField Symbols in Detail

Dynamic CallsDynamic Calls

Dynamic Programming (2)

Data ReferencesData References

Ascertaining Data Attributes DynamicallyAscertaining Data Attributes Dynamically

Page 373: TAW 10 part 2 of 2

© SAP AG TAW10 14-7

SAP AG 2002

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.

SUBMIT report_name.* dynamic:data_object = 'REPORT_NAME'. SUBMIT (data_object).

SET PF-STATUS 'STATUS_NAME' EXCLUDING 'FC1' 'FC2' ... .* dynamic:* ... fill internal_table with function codes ...SET PF-STATUS 'STATUS_NAME' EXCLUDING internal_table .

l Replacing a list with an internal table:

l Replacing an identifier with a variable in parentheses (without spaces):

n In many ABAP statements, you can pass attributes dynamically. The syntax for doing this differs, depending on the statement you use:

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

n Note: you must use upper case when filling data objects with literals. n 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. n 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.

Page 374: TAW 10 part 2 of 2

© SAP AG TAW10 14-8

SAP AG 2002

Calling Methods Dynamically

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 ptabEXCEPTION-TABLE etab.

name kind valueptab

name valueetab

TYPE-POOL abap.

TYPES abap_parmbind_tab ...TYPES abap_excpbind_tab ...

...

Internaltable types

Reference to the actual parameter

How variable is passed(optional)

Name of formal parameter

Name of exception

Value forsy-subrc

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.

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

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

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

n The exception table must have the attributes of the ABAP_EXCPBIND_TAB table type. This table has two columns: NAME for the name of the exception; VALUE for the value to be assigned to sy-subrc. VALUE must be of type i.

Page 375: TAW 10 part 2 of 2

© SAP AG TAW10 14-9

SAP AG 2003

Creating Objects Dynamically

l You can enter the class name with CREATE OBJECT both statically and dynamically

n Subclasses possible with reference to class

n 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 doc TYPE cl_html_doc.CREATE OBJECT doc TYPE ( class_name).

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.

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

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

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

Page 376: TAW 10 part 2 of 2

© SAP AG TAW10 14-10

SAP AG 2002

Dynamic Programming (3)

Field Symbols in DetailField Symbols in Detail

Dynamic CallsDynamic Calls

Data ReferencesData References

Ascertaining Data Attributes DynamicallyAscertaining Data Attributes Dynamically

Page 377: TAW 10 part 2 of 2

© SAP AG TAW10 14-11

SAP AG 2002

Data Reference Variables

DATA: ref TYPE REF TO i,do TYPE i VALUE 15.

GET REFERENCE OF do INTO ref.

do

ref

do

ref

15

15

Get a reference to a data object

TYPES reftype { TYPE REF TO type_name |LIKE REF TO do_name | TYPE REF TO data }.

DATA ref { TYPE REF TO type_name |LIKE REF TO do_name | TYPE REF TO data }.

GET REFERENCE OF dataobject INTO ref.

Generic type assignment

Any completely specified type

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.

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

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

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

Page 378: TAW 10 part 2 of 2

© SAP AG TAW10 14-12

SAP AG 2002

Example: Using Data Reference Variables in Dynamic Method Calls

TYPE-POOLS abap.DATA: ptab TYPE abap_parmbind_tab,

wa_ptab LIKE LINE OF ptab,meth TYPE string,ref TYPE REF TO data,gd_make TYPE string.

...

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.

CLASS lcl_vehicle DEFINITION....METHODS get_make

EXPORTING ex_make TYPE string....

ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION....METHOD get_make.

ex_make = make.ENDMETHOD....ENDCLASS.

name kind value

ptab EX_MAKE

gd_make VOLVO

After the dynamic method call:

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.

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

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

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

n After the method call, the actual parameter gd_make contains the passed value.

Page 379: TAW 10 part 2 of 2

© SAP AG TAW10 14-13

SAP AG 2002

Generating Data Objects at Runtime

DATA ref { TYPE REF TO type_name | LIKE REF TO do_name }.CREATE DATA ref.

PARAMETERS pa_tab TYPE dd021-tabname.DATA ref_itab TYPE REF TO data.

CREATE DATA ref_itab TYPE STANDARD TABLE OF (pa_tab)WITH DEFAULT KEY.

DATA ref TYPE REF TO data.CREATE DATA ref TYPE { type_name | itab_type_def }.

ref_itab

Standard table with standard key and line type appropriate for the content of the data object pa_tab

You can also assign a type dynamically

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

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

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

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

Page 380: TAW 10 part 2 of 2

© SAP AG TAW10 14-14

SAP AG 2002

Dereferencing Data References

PARAMETERS pa_tab TYPE dd021-tabname.DATA ref_itab TYPE REF TO data.

FIELD-SYMBOLS <fs_itab> TYPE ANY TABLE.

CREATE DATA ref_itab TYPE STANDARD TABLE OF (pa_tab)WITH DEFAULT KEY.

ASSIGN ref_itab->* TO <fs_itab>.

SELECT * FROM (pa_tab) INTO TABLE <fs_itab>.

ref_itab

ASSIGN ref->* TO <fs> [CASTING ... ].

fs_itab

You can then address the contents of the

internal table using the field symbol

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.

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

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

Page 381: TAW 10 part 2 of 2

© SAP AG TAW10 14-15

SAP AG 2002

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.

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.

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

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

n You can now write each data record from the SELECT statement into the compatibly-typed data object using the field symbol <fs_wa>.

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

Page 382: TAW 10 part 2 of 2

© SAP AG TAW10 14-16

SAP AG 2002

Field Symbols in DetailField Symbols in Detail

Dynamic CallsDynamic Calls

Ascertaining Data Attributes DynamicallyAscertaining Data Attributes Dynamically

Dynamic Programming (4)

Data ReferencesData References

Page 383: TAW 10 part 2 of 2

© SAP AG TAW10 14-17

SAP AG 2002

Ascertaining Internal Table Attributes

DATA: no_of_lines TYPE i,initial_lines TYPE i,table_kind TYPE c.

DESCRIBE TABLE itabLINES no_of_linesOCCURS initial_linesKIND table_kind.

* other variant:no_of_lines = lines( itab ).

TYPE-POOL: sydes.• sydes_kind-undefined• sydes_kind-standard• sydes_kind-sorted• sydes_kind-hashed

table_kind

Number of lines in the internal table

Number of lines reserved when table

was first created

Table kind

Constants used to evaluate the

return value

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_KIND-STANDARD, SYDES_KIND-SORTED, or SYDES_KIND-HASHED.

n Since SAP R/3 Basis Release 6.10, there is also a built-in function, lines. n 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.

Page 384: TAW 10 part 2 of 2

© SAP AG TAW10 14-18

SAP AG 2002

Dynamic Type Descriptions for RTTI Classes

Hierarchy of description classes:

CL_ABAP_TYPEDESCRCL_ABAP_TYPEDESCR

CL_ABAP_OBJECTDESCRCL_ABAP_OBJECTDESCR

CL_ABAP_COMPLEXDESCRCL_ABAP_COMPLEXDESCR

CL_ABAP_DATADESCRCL_ABAP_DATADESCR

CL_ABAP_CLASSDESCRCL_ABAP_CLASSDESCR

CL_ABAP_ELEMDESCRCL_ABAP_ELEMDESCR

CL_ABAP_TABLEDESCRCL_ABAP_TABLEDESCR

CL_ABAP_INTFDESCRCL_ABAP_INTFDESCR

CL_ABAP_REFDESCRCL_ABAP_REFDESCR

CL_ABAP_STRUCTDESCRCL_ABAP_STRUCTDESCR

l Pass the data object to the static method DESCRIBE_BY_DATA of the class CL_ABAP_TYPEDESCR

l Get the reference to the appropriate description object

l Evaluate the public attributes of this object

Ascertaining the type attributes of a data object at runtime:

Rules:

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

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

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

Page 385: TAW 10 part 2 of 2

© SAP AG TAW10 14-19

SAP AG 2002

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.

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.

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

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

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

n For more information and syntax examples, refer to the online documentation, either under the keyword RTTI or the class CL_ABAP_TYPEDESCR.

Page 386: TAW 10 part 2 of 2

© SAP AG TAW10 14-20

SAP AG 2002

l Use dynamic attributes in suitable ABAP statements

l Use data objects generated at runtime

l Ascertain the attributes of data objects at runtime

You are now able to:

Dynamic Programming: Unit Summary

Page 387: TAW 10 part 2 of 2

© SAP AG TAW10 14-21

Exercise 1 – Optional

Unit: Dynamic Programming

Topic: Casting Types

At the conclusion of these exercises, you will be able to:

• Use field symbols to cast types

• Perform calculations on dates

Change your program so that the default value for the key date is calculated differently. It should be the first day of the following month.

Program: ZBC401_##_CASTING

Template: SAPBC401_TABS_PROCESS_DATA

Model solution: SAPBC401_DYNS_CASTING

1-1 Copy your solution to the last exercise from the unit Using Internal Tables ZBC401_##_PROCESS_DATA or the corresponding model solution SAPBC401_TABS_PROCESS_DATA and give it the new name ZBC401_##_CASTING.

1-2 Define a structure type (we suggest the name: st_date) with three components: Year, month, and day. Assign an appropriate type to each component. Define a field symbol based on this type (suggested name: <fs_date>).

1-3 In the LOAD-OF-PROGRAM event block: Copy today’s 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.

Page 388: TAW 10 part 2 of 2

© SAP AG TAW10 14-22

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.

2-2 Get to know the source code and runtime behavior of this program. Then implement the following concept: At runtime, the program should generate an internal table whose line type is compatible with the selected transparent table. The former should then be filled with the complete contents of the latter using a dynamic SQL statement. The internal table filled in this way should then be passed to a SAP Grid Control instance.

2-3 Define a reference for the internal table that will be generated (we suggest the name ref_itab).

2-4 At program runtime, generate the internal table. At this time, it is known which line type must be used. The table must be a standard table with a non-unique standard key.

Page 389: TAW 10 part 2 of 2

© SAP AG TAW10 14-23

2-5 Assign a generically-typed field symbol to the generated internal table (suggested name: <fs_itab>), so that its contents can be accessed.

2-6 Before calling the screen, insert an Open SQL statement that copies the complete contents of the selected transparent table into the internal table using an array fetch. If an error occurs, make sure the program terminates.

2-7 Generate a SAP Grid Control instance within the PBO module that you have created, INIT_CONTROLS_0100. Again, if an error occurs, make sure the program terminates.

The relevant class is called CL_GUI_ALV_GRID.

2-8 Pass the internal table filled in this way to this SAP Grid Control instance. If an error occurs, make sure the program terminates.

The relevant method is called SET_TABLE_FOR_FIRST_DISPLAY. You need only pass values to two parameters: The line type to I_STRUCTURE_NAME and the name of the internal table to IT_OUTTAB.

Page 390: TAW 10 part 2 of 2

© SAP AG TAW10 14-24

Solution 1 - Optional

Unit: Dynamic Programming

Topic: Casting Types

REPORT sapbc401_dyns_casting.

TYPE-POOLS col.

TYPES:

BEGIN OF st_flight_c,

... END OF st_flight_c,

BEGIN OF st_flight,

...

END OF st_flight, BEGIN OF st_date,

year(4) TYPE n, month(2) TYPE n,

day(2) TYPE n, END OF st_date.

CONSTANTS c_number TYPE i VALUE 30.

DATA:

datastring TYPE string,

set_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

Page 391: TAW 10 part 2 of 2

© SAP AG TAW10 14-25

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). " date in the past ENDIF.

START-OF-SELECTION. ...

Page 392: TAW 10 part 2 of 2

© SAP AG TAW10 14-26

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 Model solution: SAPBC401_DYNS_CREATE_DATA_SQL REPORT sapbc401_dyns_create_data_sql. DATA: ok_code LIKE sy-ucomm, popans. DATA: ref_docking TYPE REF TO cl_gui_docking_container, ref_alv TYPE REF TO cl_gui_alv_grid. DATA ref_itab TYPE REF TO data. FIELD-SYMBOLS <fs_itab> TYPE ANY TABLE. PARAMETERS pa_tab TYPE dd02l-tabname DEFAULT 'SPFLI'.

Page 393: TAW 10 part 2 of 2

© SAP AG TAW10 14-27

START-OF-SELECTION. CREATE DATA ref_itab TYPE STANDARD TABLE OF (pa_tab) WITH NON-UNIQUE DEFAULT KEY. ASSIGN ref_itab->* TO <fs_itab>. SELECT * FROM (pa_tab) INTO TABLE <fs_itab>. IF sy-subrc <> 0. MESSAGE a000(rfw) WITH text-ndt. ENDIF. CALL SCREEN 100. *&--------------------------------------------------------* *& Module clear_ok_code OUTPUT * *&--------------------------------------------------------* MODULE clear_ok_code OUTPUT. CLEAR ok_code. ENDMODULE. " clear_ok_code OUTPUT *&--------------------------------------------------------* *& Module STATUS_0100 OUTPUT * *&--------------------------------------------------------* MODULE status_0100 OUTPUT. SET PF-STATUS 'ST100'. SET TITLEBAR 'T100'. ENDMODULE. " STATUS_0100 OUTPUT *&--------------------------------------------------------* *& Module init_controls_0100 OUTPUT * *&--------------------------------------------------------* MODULE init_controls_0100 OUTPUT. IF ref_docking IS INITIAL. CREATE OBJECT ref_docking EXPORTING * SIDE = DOCK_AT_LEFT extension = 2000 EXCEPTIONS OTHERS = 6 . IF sy-subrc <> 0. MESSAGE a015(rfw). ENDIF. CREATE OBJECT ref_alv EXPORTING i_parent = ref_docking EXCEPTIONS error_cntl_create = 1 error_cntl_init = 2 error_cntl_link = 3 error_dp_create = 4 OTHERS = 5 .

Page 394: TAW 10 part 2 of 2

© SAP AG TAW10 14-28

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

Page 395: TAW 10 part 2 of 2

© SAP AG TAW10 14-29

titel = text-bak cancel_display = ' ' IMPORTING answer = popans. CASE popans. WHEN 'J'. LEAVE TO SCREEN 0. WHEN 'N'. ENDCASE. WHEN OTHERS. ENDCASE.

Page 396: TAW 10 part 2 of 2

© SAP AG TAW10 15-1

SAP AG 2003

Case Study

Page 397: TAW 10 part 2 of 2

© SAP AG TAW10 15-2

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.

Page 398: TAW 10 part 2 of 2

© SAP AG TAW10 15-3

Pushbutton Function code Function

Display SHOW Displays a list of all customers on the waiting list for the selected flight

Create CREATE Creates a waiting list for the selected flight

Delete DELETE Deletes the waiting list for the selected flight

Move up FIRST Deletes the first person on the waiting list for the selected flight

Waiting list status

STATWL Displays the number of persons on the waiting list for the selected flight

Add ADD Adds the selected customer to the waiting list for the selected flight

Delete DEL Deletes the selected customer from the waiting list for the selected flight

Position POS Displays the position of the selected customer in the waiting list for the selected flight

Customer status STATCU Displays whether the selected customer is a private or business customer (you can find the corresponding information in the custtype field of table scustom.)

Display all move-up customers

LOG Displays all customers who moved up the waiting list for a flight

Status log STATPR Displays the number of customers who moved up the waiting list for a flight

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.

1-2 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:

Page 399: TAW 10 part 2 of 2

© SAP AG TAW10 15-4

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

Page 400: TAW 10 part 2 of 2

© SAP AG TAW10 15-5

Solutions

Unit: Case Study

Topic: Case Study

1-2 UML class diagram

1-3 Program listing

Page 401: TAW 10 part 2 of 2

© SAP AG TAW10 15-6

1 *&---------------------------------------------------------------------*

2 *& Report TAW10_CSS1_WAITLIST *

3 *& *

4 *&---------------------------------------------------------------------*

5 *& *

6 *& *

7 *&---------------------------------------------------------------------*

8

9 REPORT taw10_css1_waitlist .

10

11 *---------------------------------------------------------------------*

12 * INTERFACE if_taw10_status

13 *---------------------------------------------------------------------*

14 *

15 *---------------------------------------------------------------------*

16 INTERFACE if_taw10_status.

17 METHODS display_status.

18 ENDINTERFACE. "if_taw10_status

19

20

21 *---------------------------------------------------------------------*

22 * CLASS cl_taw10_customer DEFINITION

23 *---------------------------------------------------------------------*

24 *

25 *---------------------------------------------------------------------*

26 CLASS cl_taw10_customer DEFINITION.

27

28 PUBLIC SECTION.

29 METHODS constructor IMPORTING im_id TYPE s_customer

30 im_name TYPE s_custname

31 im_street TYPE s_street

32 im_city TYPE city

33 im_app_date TYPE d.

34

Page 402: TAW 10 part 2 of 2

© SAP AG TAW10 15-7

35 METHODS get_attributes EXPORTING ex_cust TYPE taw10_typd_cust.

36

37 DATA: id TYPE s_customer READ-ONLY.

38

39 INTERFACES if_taw10_status.

40

41 PRIVATE SECTION.

42 DATA: name TYPE s_custname,

43 street TYPE s_street,

44 city TYPE city,

45 app_date TYPE d.

46

47 ENDCLASS. "cl_taw10_customer DEFINITION

48

49

50 *---------------------------------------------------------------------*

51 * CLASS cl_taw10_customer IMPLEMENTATION

52 *---------------------------------------------------------------------*

53 *

54 *---------------------------------------------------------------------*

55 CLASS cl_taw10_customer IMPLEMENTATION.

56 METHOD constructor.

57 id = im_id.

58 name = im_name.

59 street = im_street.

60 city = im_city.

61 app_date = im_app_date.

62 ENDMETHOD. "constructor

63

64 METHOD get_attributes.

65 ex_cust-id = id.

66 ex_cust-name = name.

67 ex_cust-street = street.

68 ex_cust-city = city.

69 ex_cust-app_date = app_date.

70 ENDMETHOD. "get_attributes

71

72 METHOD if_taw10_status~display_status.

73 DATA custtype TYPE s_custtype.

74 CONSTANTS: bcust(1) TYPE c VALUE 'B',

Page 403: TAW 10 part 2 of 2

© SAP AG TAW10 15-8

75 pcust(1) TYPE c VALUE 'P'.

76

77 SELECT SINGLE custtype FROM scustom INTO (custtype)

78 WHERE id = id.

79

80 IF sy-subrc = 0.

81 CASE custtype.

82 WHEN bcust.

83 MESSAGE i015(taw10) WITH id 'Business customer'(001).

84 * Customer &1 is &2.

85 WHEN pcust.

86 MESSAGE i015(taw10) WITH id 'Private customer'(002).

87 * Customer &1 is &2.

88 ENDCASE.

89 ENDIF.

90

91 ENDMETHOD. "if_taw10_status~display_status

92

93 ENDCLASS. "cl_taw10_customer IMPLEMENTATION

94

95

96

97

98

99 *---------------------------------------------------------------------*

100 * CLASS cl_taw10_waitlist DEFINITION

101 *---------------------------------------------------------------------*

102 *

103 *---------------------------------------------------------------------*

104 CLASS cl_taw10_waitlist DEFINITION.

105 PUBLIC SECTION.

106

107 TYPES itt_wait_list

108 TYPE STANDARD TABLE OF REF TO cl_taw10_customer WITH DEFAULT

109 KEY.

110

111 METHODS constructor IMPORTING im_carrid TYPE sflight-carrid

112 im_connid TYPE sflight-connid

113 im_fldate TYPE sflight-fldate.

114

Page 404: TAW 10 part 2 of 2

© SAP AG TAW10 15-9

115 METHODS add IMPORTING im_customer TYPE REF TO cl_taw10_customer

116 RAISING cx_taw10_cust_in_list.

117

118 METHODS delete IMPORTING im_customer TYPE REF TO cl_taw10_customer

119 RAISING cx_taw10_cust_not_in_list.

120

121 METHODS get_pos IMPORTING im_customer TYPE REF TO cl_taw10_customer

122 EXPORTING ex_pos LIKE sy-tabix

123 RAISING cx_taw10_cust_not_in_list.

124

125 METHODS get_wait_list EXPORTING ex_wait_list TYPE itt_wait_list.

126 METHODS get_first RAISING cx_taw10_empty_list.

127

128

129 DATA:

130 carrid TYPE sflight-carrid READ-ONLY,

131 carrid TYPE sflight-carrid READ-ONLY,

132 fldate TYPE sflight-fldate READ-ONLY.

133

134 INTERFACES if_taw10_status.

135 EVENTS first_got EXPORTING value(ex_cust) TYPE REF TO

136 cl_taw10_customer.

137

138 PRIVATE SECTION.

139

140 DATA wait_list TYPE itt_wait_list.

141

142 ENDCLASS. "cl_taw10_waitlist DEFINITION

143

144

145

146 *---------------------------------------------------------------------*

147 * CLASS cl_taw10_waitlist IMPLEMENTATION

148 *---------------------------------------------------------------------*

149 *

150 *---------------------------------------------------------------------*

151 CLASS cl_taw10_waitlist IMPLEMENTATION.

152 METHOD constructor.

153 carrid = im_carrid.

Page 405: TAW 10 part 2 of 2

© SAP AG TAW10 15-10

154 connid = im_connid.

155 fldate = im_fldate.

156 ENDMETHOD. "constructor

157

158 METHOD get_wait_list.

159 ex_wait_list = wait_list.

160 ENDMETHOD. "get_wait_list

161

162 METHOD add.

163 READ TABLE wait_list WITH KEY

164 table_line->id = im_customer->id TRANSPORTING NO FIELDS.

165

166 IF sy-subrc <> 0.

167 INSERT im_customer INTO TABLE wait_list.

168 ELSE.

169

170 RAISE EXCEPTION TYPE cx_taw10_cust_in_list

171 EXPORTING

172 * TEXTID =

173 * PREVIOUS =

174 customer = im_customer->id

175 carrid = carrid

176 connid = connid

177 fldate = fldate.

178

179 ENDIF.

180 ENDMETHOD. "add

181

182

183 METHOD get_first.

184 DATA r_cust TYPE REF TO cl_taw10_customer.

185

186 READ TABLE wait_list INTO r_cust INDEX 1.

187 IF sy-subrc <> 0.

188

189 RAISE EXCEPTION TYPE cx_taw10_empty_list

190 EXPORTING

191 * TEXTID =

192 * PREVIOUS =

193 carrid = carrid

194 connid = connid

195 fldate = fldate.

Page 406: TAW 10 part 2 of 2

© SAP AG TAW10 15-11

196

197 ELSE.

198 DELETE wait_list INDEX 1.

199 RAISE EVENT first_got EXPORTING ex_cust = r_cust.

200 ENDIF.

201 ENDMETHOD. "get_first

202

203

204 METHOD delete.

205 DELETE wait_list

206 WHERE table_line->id = im_customer->id.

207 IF sy-subrc <> 0.

208

209 RAISE EXCEPTION TYPE cx_taw10_cust_not_in_list

210 EXPORTING

211 * TEXTID =

212 * PREVIOUS =

213 customer = im_customer->id

214 carrid = carrid

215 connid = connid

216 fldate = fldate.

217

218 ENDIF.

219 ENDMETHOD. "delete

220

221

222 METHOD get_pos.

223 READ TABLE wait_list

224 WITH KEY table_line->id = im_customer->id

225 TRANSPORTING NO FIELDS.

226

227 IF sy-subrc = 0.

228 ex_pos = sy-tabix.

229 ELSE.

230

231 RAISE EXCEPTION TYPE cx_taw10_cust_not_in_list

232 EXPORTING

233 * TEXTID =

234 * PREVIOUS =

235 customer = im_customer->id

236 carrid = carrid

237 connid = connid

Page 407: TAW 10 part 2 of 2

© SAP AG TAW10 15-12

238 fldate = fldate.

239

240 ENDIF.

241

242 ENDMETHOD. "get_pos

243

244

245 METHOD if_taw10_status~display_status.

246 DATA n_o_lines LIKE sy-tabix.

247 n_o_lines = lines( wait_list ).

248

249 MESSAGE i014(taw10) WITH carrid connid fldate n_o_lines.

250 * The waiting list for flight &1 &2 &3 contains &4 entries.

251 ENDMETHOD. "if_taw10_status~display_status

252

253 ENDCLASS. "cl_taw10_waitlist IMPLEMENTATION

254

255

256

257 *---------------------------------------------------------------------*

258 * CLASS cl_taw10_display_log DEFINITION

259 *---------------------------------------------------------------------*

260 *

261 *---------------------------------------------------------------------*

262 CLASS cl_taw10_display_log DEFINITION.

263 PUBLIC SECTION.

264 METHODS display_log.

265

266 PROTECTED SECTION.

267 DATA: it_log TYPE taw10_typd_cust_list.

268

269 ENDCLASS. "cl_taw10_display_log DEFINITION

270

271

272 *---------------------------------------------------------------------*

273 * CLASS cl_taw10_display_log IMPLEMENTATION

274 *---------------------------------------------------------------------*

275 *

Page 408: TAW 10 part 2 of 2

© SAP AG TAW10 15-13

276 *---------------------------------------------------------------------*

277 CLASS cl_taw10_display_log IMPLEMENTATION.

278

279 METHOD display_log.

280 DATA n_o_lines LIKE sy-tabix.

281

282 n_o_lines = lines( it_log ).

283

284 IF n_o_lines > 0.

285 SORT it_log BY id.

286 DELETE ADJACENT DUPLICATES FROM it_log COMPARING id.

287 CALL FUNCTION 'TAW10_DISPLAY_DATA'

288 EXPORTING

289 im_list = it_log.

290 ELSE.

291 MESSAGE 'There are no move-up customers available.'(003) TYPE 'I'.

292 ENDIF.

293 ENDMETHOD. "display_log

294

295 ENDCLASS. "cl_taw10_display_log IMPLEMENTATION

296

297

298 *---------------------------------------------------------------------*

299 * CLASS cl_taw10_log DEFINITION

300 *---------------------------------------------------------------------*

301 *

302 *---------------------------------------------------------------------*

303 CLASS cl_taw10_log DEFINITION INHERITING FROM cl_taw10_display_log.

304 PUBLIC SECTION.

305 METHODS get_cust FOR EVENT first_got OF cl_taw10_waitlist

306 IMPORTING ex_cust.

307

308 INTERFACES if_taw10_status.

309

310 ENDCLASS. "cl_taw10_log DEFINITION

311

312 *---------------------------------------------------------------------*

313 * CLASS cl_taw10_log IMPLEMENTATION

Page 409: TAW 10 part 2 of 2

© SAP AG TAW10 15-14

314 *---------------------------------------------------------------------*

315 *

316 *---------------------------------------------------------------------*

317 CLASS cl_taw10_log IMPLEMENTATION.

318 METHOD get_cust.

319 DATA wa_cust TYPE taw10_typd_cust.

320

321 ex_cust->get_attributes( IMPORTING ex_cust = wa_cust ).

322 INSERT wa_cust INTO TABLE it_log.

323 ENDMETHOD. "get_cust

324

325

326 METHOD if_taw10_status~display_status.

327 DATA: n_o_lines LIKE sy-tabix,

328 c_n_o_lines TYPE string,

329 text TYPE string.

330

331 SORT it_log BY id.

332 DELETE ADJACENT DUPLICATES FROM it_log COMPARING id.

333

334 n_o_lines = lines( it_log ).

335 c_n_o_lines = n_o_lines.

336 CONCATENATE 'Number of move-up customers:'(004)

337 c_n_o_lines INTO text SEPARATED BY space.

338

339 MESSAGE text TYPE 'I'.

340

341 ENDMETHOD. "if_taw10_status~display_status

342

343 ENDCLASS. "cl_taw10_log IMPLEMENTATION

344

345

346

347 DATA ok_code LIKE sy-ucomm.

348 TABLES: sdyn_conn, scustom.

349

350 DATA: r_customer TYPE REF TO cl_taw10_customer,

351 r_cust TYPE REF TO cl_taw10_customer,

352 r_waitlist TYPE REF TO cl_taw10_waitlist,

353 r_log TYPE REF TO cl_taw10_log,

354 r_exc TYPE REF TO cx_root.

Page 410: TAW 10 part 2 of 2

© SAP AG TAW10 15-15

355

356 DATA r_if_status TYPE REF TO if_taw10_status.

357

358 DATA: waitlist_buffer TYPE TABLE OF REF TO cl_taw10_waitlist,

359 waitlist TYPE TABLE OF REF TO cl_taw10_customer.

360

361 DATA: wa_cust TYPE taw10_typd_cust,

362 it_wait_list TYPE taw10_typd_cust_list.

363

364 DATA: n_o_lines TYPE i,

365 wa_sflight TYPE sflight,

366 text TYPE string.

367

368

369

370 LOAD-OF-PROGRAM.

371 CREATE OBJECT r_log.

372 SET HANDLER r_log->get_cust FOR ALL INSTANCES.

373

374

375 START-OF-SELECTION.

376

377

378 CALL SCREEN 100.

379

380 INCLUDE taw10_css1_waitlist_o01.

381 INCLUDE taw10_css1_waitlist_i01.

Page 411: TAW 10 part 2 of 2

© SAP AG TAW10 15-16

1 *&---------------------------------------------------------------------*

2 *& Include TAW10_CSS1_WAITLIST_O01

3 *

4 *&---------------------------------------------------------------------*

5

6

7 *&---------------------------------------------------------------------*

8 *& Module STATUS_0100 OUTPUT

9 *&---------------------------------------------------------------------*

10 * text

11 *----------------------------------------------------------------------*

12 MODULE status_0100 OUTPUT.

13 SET PF-STATUS 'DYNPRO_100'.

14 SET TITLEBAR 'TITLE_100'.

15

16 ENDMODULE. " STATUS_0100 OUTPUT

17

18

19

20 *&---------------------------------------------------------------------*

21 *& Module clear_ok_code OUTPUT

22 *&---------------------------------------------------------------------*

23 * text

24 *----------------------------------------------------------------------*

25 MODULE clear_ok_code OUTPUT.

26 CLEAR ok_code.

27 ENDMODULE. " clear_ok_code OUTPUT

Page 412: TAW 10 part 2 of 2

© SAP AG TAW10 15-17

1 *----------------------------------------------------------------------*

2 ***INCLUDE TAW10_CSS1_WAITLIST_I01 .

3 *----------------------------------------------------------------------*

4

5

6 *&---------------------------------------------------------------------*

7 *& Module check_and_create_cust INPUT

8 *&---------------------------------------------------------------------*

9 * text

10 *----------------------------------------------------------------------*

11 MODULE check_and_create_cust INPUT.

12 SELECT SINGLE name street city FROM scustom

13 INTO CORRESPONDING FIELDS OF scustom

14 WHERE id = scustom-id.

15 IF sy-subrc = 0.

16 CREATE OBJECT r_customer EXPORTING im_id = scustom-id

17 im_name = scustom-name

18 im_street = scustom-street

19 im_city = scustom-city

20 im_app_date = sy-datum.

21 ELSE.

22 CLEAR: scustom-name, scustom-city.

23 MESSAGE e000(taw10) WITH scustom-id.

24 * Customer number & does not exist. Correct your entry!

25 ENDIF.

26 ENDMODULE. " check_and_create_cust INPUT

27

28

29 *&---------------------------------------------------------------------*

30 *& Module user_command_0100 INPUT

31 *&---------------------------------------------------------------------*

32 * text

33 *----------------------------------------------------------------------*

34 MODULE user_command_0100 INPUT.

35

36 CASE ok_code.

37 WHEN 'BACK'.

Page 413: TAW 10 part 2 of 2

© SAP AG TAW10 15-18

38 LEAVE TO SCREEN 0.

39

40 WHEN 'CREATE'.

41 READ TABLE waitlist_buffer INTO r_waitlist WITH KEY

42 table_line->carrid = sdyn_conn-carrid

43 table_line->connid = sdyn_conn-connid

44 table_line->fldate = sdyn_conn-fldate.

45

46 IF sy-subrc <> 0.

47 CREATE OBJECT r_waitlist EXPORTING im_carrid = sdyn_conn-carrid

48 im_connid = sdyn_conn-connid

49 im_fldate = sdyn_conn-fldate.

50 INSERT r_waitlist INTO TABLE waitlist_buffer.

51 MESSAGE s005(taw10) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

52 * Waiting list for flight &1 &2 &3 created successfully!

53 ELSE.

54 MESSAGE s001(taw10) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

55 * Waiting list for flight &1 &2 &3 already exists!

56 ENDIF.

57

58 WHEN 'SHOW'.

59 CLEAR it_wait_list.

60 READ TABLE waitlist_buffer INTO r_waitlist WITH KEY

61 table_line->carrid = sdyn_conn-carrid

62 table_line->connid = sdyn_conn-connid

63 table_line->fldate = sdyn_conn-fldate.

64

65 IF sy-subrc = 0.

66 r_waitlist->get_wait_list( IMPORTING ex_wait_list = waitlist ).

67 n_o_lines = lines( waitlist ).

68

69 IF n_o_lines > 0.

70 LOOP AT waitlist INTO r_cust.

71 r_cust->get_attributes( IMPORTING ex_cust = wa_cust ).

72 INSERT wa_cust INTO TABLE it_wait_list.

73 ENDLOOP.

74

75 CALL FUNCTION 'TAW10_DISPLAY_DATA'

Page 414: TAW 10 part 2 of 2

© SAP AG TAW10 15-19

76 EXPORTING

77 im_list = it_wait_list.

78

79 ELSE.

80 MESSAGE s003(taw10)

81 WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

82 * The waiting list for flight &1 &2 &3 does not contain any entries.

83 ENDIF.

84

85 ELSE.

86 MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

87 * No waiting list exists for flight &1 &2 &3!

88 ENDIF.

89

90

91 WHEN 'DELETE'.

92 DELETE waitlist_buffer

93 WHERE table_line->carrid = sdyn_conn-carrid

94 AND table_line->connid = sdyn_conn-connid

95 AND table_line->fldate = sdyn_conn-fldate.

96

97 IF sy-subrc = 0.

98 MESSAGE s006(taw10) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

99 * Waiting list for flight &1 &2 &3 deleted successfully!

100 ELSE.

101 MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

102 * No waiting list exists for flight &1 &2 &3!

103 ENDIF.

104

105

106 WHEN 'FIRST'.

107 READ TABLE waitlist_buffer INTO r_waitlist WITH KEY

108 table_line->carrid = sdyn_conn-carrid

109 table_line->connid = sdyn_conn-connid

110 table_line->fldate = sdyn_conn-fldate.

111

112 IF sy-subrc = 0.

113 TRY.

Page 415: TAW 10 part 2 of 2

© SAP AG TAW10 15-20

114 r_waitlist->get_first( ).

115 MESSAGE s007(taw10) WITH sdyn_conn-carrid sdyn_conn-connid

116 sdyn_conn-fldate.

117 * The first wait end from the waiting list for flight &1 &2 &3

118 * was deleted.

119

120 CATCH cx_taw10_empty_list INTO r_exc.

121 text = r_exc->get_text( ).

122 MESSAGE text TYPE 'I'.

123 ENDTRY.

124

125 ELSE.

126 MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

127 * No waiting list exists for flight &1 &2 &3!

128

129 ENDIF.

130

131

132 WHEN 'ADD'.

133 IF scustom-id IS INITIAL.

134 MESSAGE s008(taw10).

135 * Please select a valid customer number!

136 EXIT.

137 ENDIF.

138

139 READ TABLE waitlist_buffer INTO r_waitlist WITH KEY

140 table_line->carrid = sdyn_conn-carrid

141 table_line->connid = sdyn_conn-connid

142 table_line->fldate = sdyn_conn-fldate.

143 IF sy-subrc = 0.

144 TRY.

145 r_waitlist->add( r_customer ).

146 MESSAGE s010(taw10)

147 WITH scustom-id sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

148 * Customer &1 added to the waiting list for flight &2 &3 &4

149

150 CATCH cx_taw10_cust_in_list INTO r_exc.

151 text = r_exc->get_text( ).

152 MESSAGE text TYPE 'I'.

153 ENDTRY.

Page 416: TAW 10 part 2 of 2

© SAP AG TAW10 15-21

154

155 ELSE.

156 MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

157 * No waiting list exists for flight &1 &2 &3!

158 ENDIF.

159

160

161 WHEN 'DEL'.

162 IF scustom-id IS INITIAL.

163 MESSAGE s008(taw10).

164 * Please select a valid customer number!

165 EXIT.

166 ENDIF.

167

168 READ TABLE waitlist_buffer INTO r_waitlist WITH KEY

169 table_line->carrid = sdyn_conn-carrid

170 table_line->connid = sdyn_conn-connid

171 table_line->fldate = sdyn_conn-fldate.

172 IF sy-subrc = 0.

173

174 TRY.

175 r_waitlist->delete( r_customer ).

176 MESSAGE s012(taw10)

177 WITH scustom-id sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

178 * Customer &1 was deleted from the waiting list for flight &2 &3 &4!

179

180 CATCH cx_taw10_cust_not_in_list INTO r_exc.

181 text = r_exc->get_text( ).

182 MESSAGE text TYPE 'I'.

183 ENDTRY.

184

185 ELSE.

186 MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

187 * No waiting list exists for flight &1 &2 &3!

188 ENDIF.

189

190

191 WHEN 'POS'.

192

Page 417: TAW 10 part 2 of 2

© SAP AG TAW10 15-22

193 DATA pos LIKE sy-tabix.

194 DATA flight TYPE string.

195 DATA fldate(10) TYPE c.

196

197 IF scustom-id IS INITIAL.

198 MESSAGE s008(taw10).

199 * Please select a valid customer number!

200 EXIT.

201 ENDIF.

202

203 READ TABLE waitlist_buffer INTO r_waitlist WITH KEY

204 table_line->carrid = sdyn_conn-carrid

205 table_line->connid = sdyn_conn-connid

206 table_line->fldate = sdyn_conn-fldate.

207 IF sy-subrc = 0.

208

209 TRY.

210 r_waitlist->get_pos( EXPORTING im_customer = r_customer

211 IMPORTING ex_pos = pos ).

212

213 WRITE sdyn_conn-fldate TO fldate.

214 CONCATENATE sdyn_conn-carrid sdyn_conn-connid fldate

215 INTO flight SEPARATED BY space.

216 MESSAGE i013(taw10) WITH scustom-id flight pos.

217 * Customer &1 is on the waiting list for flight &2 at position &3

218

219 CATCH cx_taw10_cust_not_in_list INTO r_exc.

220 text = r_exc->get_text( ).

221 MESSAGE text TYPE 'I'.

222 ENDTRY.

223

224 ELSE.

225 MESSAGE s002(taw10) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

226 * No waiting list exists for flight &1 &2 &3!

227 ENDIF.

228

229

230 WHEN 'STATWL' OR 'STATCU' OR 'STATPR'.

231 IF ok_code = 'STATWL'.

232 READ TABLE waitlist_buffer INTO r_waitlist WITH KEY

233 table_line->carrid = sdyn_conn-carrid

Page 418: TAW 10 part 2 of 2

© SAP AG TAW10 15-23

234 table_line->connid = sdyn_conn-connid

235 table_line->fldate = sdyn_conn-fldate.

236

237 IF sy-subrc = 0.

238 r_if_status = r_waitlist.

239 ELSE.

240 MESSAGE s002(taw10)

241 WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate.

242 * No waiting list exists for flight &1 &2 &3!

243 EXIT.

244 ENDIF.

245 ENDIF.

246

247 IF ok_code = 'STATCU'.

248 IF scustom-id IS INITIAL.

249 MESSAGE s008(taw10).

250 * Please select a valid customer number!

251 EXIT.

252 ENDIF.

253

254 r_if_status = r_customer.

255

256 ENDIF.

257

258 IF ok_code = 'STATPR'.

259 r_if_status = r_log.

260 ENDIF.

261

262 r_if_status->display_status( ).

263

264 WHEN 'LOG'.

265 r_log->display_log( ).

266

267 ENDCASE.

268

269

270 ENDMODULE. " user_command_0100 INPUT

271

272

273 *&---------------------------------------------------------------------*

274 *& Module check_flight INPUT

Page 419: TAW 10 part 2 of 2

© SAP AG TAW10 15-24

275 *&---------------------------------------------------------------------*

276 * text

277 *----------------------------------------------------------------------*

278 MODULE check_flight INPUT.

279 SELECT SINGLE * FROM sflight INTO wa_sflight

280 WHERE carrid = sdyn_conn-carrid

281 AND connid = sdyn_conn-connid

282 AND fldate = sdyn_conn-fldate.

283

284 IF sy-subrc <> 0.

285 MESSAGE e004(taw10).

286 * Please select a valid flight

287 ENDIF.

288 ENDMODULE. " check_flight INPUT

289

290

291 *&---------------------------------------------------------------------*

292 *& Module exit INPUT

293 *&---------------------------------------------------------------------*

294 * text

295 *----------------------------------------------------------------------*

296 MODULE exit INPUT.

297

298 CASE ok_code.

299 WHEN 'CANCEL'.

300 CLEAR: scustom, sdyn_conn.

301 LEAVE TO SCREEN 100.

302 WHEN 'EXIT'.

303 LEAVE PROGRAM.

304

305 ENDCASE.

306

307 ENDMODULE. " exit INPUT

Page 420: TAW 10 part 2 of 2

© SAP AG TAW10 16-1

SAP AG 2003

l Description of Certification

l Example Questions

Contents:

Preparation for Certification

Page 421: TAW 10 part 2 of 2

© SAP AG TAW10 16-2

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 participant’s 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

Page 422: TAW 10 part 2 of 2

© SAP AG TAW10 16-3

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 LUW’s 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

Page 423: TAW 10 part 2 of 2

© SAP AG TAW10 16-4

Business Transaction Events Business Add-Ins Modifications

Key for certification weighting:

+ = 1 - 10%

++ = 11 - 20%

+++ = More than 20%

Page 424: TAW 10 part 2 of 2

© SAP AG TAW10 16-5

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

Page 425: TAW 10 part 2 of 2

© SAP AG TAW10 16-6

Answer 2: Correct Answer 3: Incorrect Answer 4: Correct Answer 5: Incorrect

Page 426: TAW 10 part 2 of 2

© SAP AG TAW10 16-7

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 user’s 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

Page 427: TAW 10 part 2 of 2

© SAP AG TAW10 16-8

Answer2: Correct Answer3: Correct Answer4: Incorrect Answer5: Incorrect

Page 428: TAW 10 part 2 of 2

© SAP AG TAW10 16-9

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

Page 429: TAW 10 part 2 of 2

© SAP AG TAW10 16-10

Answer 1: Incorrect Answer 2: Incorrect Answer 3: Correct

Page 430: TAW 10 part 2 of 2

© SAP AG TAW10 16-11

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

Page 431: TAW 10 part 2 of 2

© SAP AG TAW10 16-12

Answer 1: Incorrect Answer 2: Correct Answer 3: Correct Answer 4: Correct

Page 432: TAW 10 part 2 of 2

© SAP AG TAW10 16-13

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

Page 433: TAW 10 part 2 of 2

© SAP AG TAW10 16-14

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