BC401 Partner
Use
Date Training Center Instructors
SAP
Education Website
Partner
Participant Handbook Course Version: 2004 Q1 Course Duration: 5 Day(s) Material Number: 50065633
An SAP course - use it to learn, reference it for work
Only
Internal
Use
SAP
mySAP Technology
Internal
Only
ABAP Objects
Copyright Copyright © 2004 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. Some software products marketed by SAP AG and its distributors contain proprietary software components of other software vendors.
Partner SAP Use
•
ORACLE® is a registered trademark of ORACLE Corporation.
•
INFORMIX®-OnLine for SAP and INFORMIX® Dynamic ServerTM are registered trademarks of Informix Software Incorporated.
•
UNIX®, X/Open®, OSF/1®, and Motif® are registered trademarks of the Open Group.
•
Citrix®, the Citrix logo, ICA®, Program Neighborhood®, MetaFrame®, WinFrame®, VideoFrame®, MultiWin® and other Citrix product names referenced herein are trademarks of Citrix Systems, Inc.
•
HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C®, World Wide Web Consortium, Massachusetts Institute of Technology.
•
JAVA® is a registered trademark of Sun Microsystems, Inc.
•
JAVASCRIPT® is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
•
SAP, SAP Logo, R/2, RIVA, R/3, SAP ArchiveLink, SAP Business Workflow, WebFlow, SAP EarlyWatch, BAPI, SAPPHIRE, Management Cockpit, mySAP.com Logo and mySAP.com are trademarks or registered trademarks of SAP AG in Germany and in several other countries all over the world. All other products mentioned are trademarks or registered trademarks of their respective companies.
Disclaimer THESE MATERIALS ARE PROVIDED BY SAP ON AN "AS IS" BASIS, AND SAP EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR APPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, WITH RESPECT TO THESE MATERIALS AND THE SERVICE, INFORMATION, TEXT, GRAPHICS, LINKS, OR ANY OTHER MATERIALS AND PRODUCTS CONTAINED HEREIN. IN NO EVENT SHALL SAP BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES OF ANY KIND WHATSOEVER, INCLUDING WITHOUT LIMITATION LOST REVENUES OR LOST PROFITS, WHICH MAY RESULT FROM THE USE OF THESE MATERIALS OR INCLUDED SOFTWARE COMPONENTS.
Only
Internal
IBM®, DB2®, OS/2®, DB2/6000®, Parallel Sysplex®, MVS/ESA®, RS/6000®, AIX®, S/390®, AS/400®, OS/390®, and OS/400® are registered trademarks of IBM Corporation.
Partner
•
SAP
Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint® and SQL Server® are registered trademarks of Microsoft Corporation.
Use
•
Internal
Only
Trademarks
About This Handbook This handbook is intended to complement the instructor-led presentation of this course, and serve as a source of reference. It is not suitable for self-study.
Internal
Only
Typographic Conventions
Type Style
Description
Example text
Words or characters that appear on the screen. These include field names, screen titles, pushbuttons as well as menu names, paths, and options.
Use
Partner
American English is the standard used in this handbook. The following typographic conventions are also used.
SAP Use
Example text
Emphasized words or phrases in body text, titles of graphics, and tables
EXAMPLE TEXT
Names of elements in the system. These include report names, program names, transaction codes, table names, and individual key words of a programming language, when surrounded by body text, for example SELECT and INCLUDE.
Partner Only
Internal
SAP
Also used for cross-references to other documentation both internal (in this documentation) and external (in other locations, such as SAPNet).
08-03-2004
© 2004 SAP AG. All rights reserved.
iii
Partner
BC401
Type Style
Description
Example text
Screen output. This includes file and directory names and their paths, messages, names of variables and parameters, and passages of the source text of a program.
Example text
Exact user entry. These are words and characters that you enter in the system exactly as they appear in the documentation.
<Example text>
Variable user entry. Pointed brackets indicate that you replace these words and characters with appropriate entries.
Use
Icons in Body Text The following icons are used in this handbook. Meaning
SAP
SAP
Icon
For more information, tips, or background
Use Internal
Exception or caution Procedures
Only
Indicates that the item is displayed in the instructor’s presentation.
© 2004 SAP AG. All rights reserved.
Partner
Note or further explanation of previous point
iv
Internal
Only
About This Handbook
08-03-2004
Contents Course Overview ............................................................................. vii
The Object-Oriented Programming Model .............................................. 93 Analysis and Design with UML........................................................... 106 Fundamental Object-Oriented Syntax Elements ...................................... 120
Use
Partner
Unit 2: Introduction to Object-Oriented Programming .............................. 91
Internal
Only
Course Goals................................................................................ viii Course Objectives .......................................................................... viii
Unit 1: Completing the Procedural Parts of ABAP Objects ..........................1 Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20 ................................................................................ 3 Optimized Working with Internal Tables ................................................. 22
SAP Use
Unit 4: Object-Oriented Repository Objects ..........................................305 Global Classes and Interfaces ........................................................... 307 Special Object-Oriented Programming Techniques ................................... 352 Persistent Objects in ABAP Objects for SAP Web Application Server 6.20 ...... 369
Unit 5: Exception Handling and Dynamic Programming ...........................381
Appendix 1: Calling Programs and Passing Data
.................................465
Index ............................................................................................483
08-03-2004
© 2004 SAP AG. All rights reserved.
v
Only
Exception Handling in ABAP Objects for the SAP Web Application Server 6.20 . 383 Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20 ........................................................................................... 422
Partner
Internal
Inheritance and Casting................................................................... 185 Interfaces and Casting .................................................................... 226 Events ....................................................................................... 263
SAP
Unit 3: Object-Oriented Concepts and Programming Techniques ...............183
Contents
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
vi
© 2004 SAP AG. All rights reserved.
08-03-2004
Course Overview Only
Furthermore, you will become familiar with the tools in the ABAP Workbench that are used for object-oriented programming with ABAP Objects.
Only
Use Internal
Many of the programming techniques, tools, and syntax elements in this course are already available as of SAP R/3 4.6A. The ones that are not are available as of SAP Web AS 6.10. There are only minimal differences between SAP Web AS 6.10 and SAP Web AS 6.20 and which relate to ABAP Objects and ABAP Workbench.
Target Audience This course is intended for the following audiences: • •
08-03-2004
Development project managers ABAP Objects developers
© 2004 SAP AG. All rights reserved.
Partner
The SAP technology component SAP Web Application Server, or SAP Web AS for short, is embedded in the SAP NetWeaver solution and is therefore the technical basis for nearly all SAP solutions. That means that you can use the knowledge and skills you gain in this course for all solutions that were developed with ABAP Objects, not just for developing within SAP ERP.
SAP
SAP
The course’s third part will introduce you to programming techniques that partially use object-oriented elements of ABAP Objects, but can also be used in procedural contexts.
Use
Partner
The first part of the course will introduce you to the procedural parts of ABAP Objects, as far as they are not covered in the sections that have been left out. The focus is on the second part of the course, which provides a step-by-step, extensive introduction to object-oriented development in ABAP Objects. This also includes an introduction to modeling.
Internal
This course will give you a comprehensive and detailed introduction into the programming techniques and the associated syntax of the ABAP Objects language. The only information that is not covered belongs to separate subject areas – like dialog programming, database access, and so on – that are already completely contained in other courses.
vii
Course Overview
BC401
Course Prerequisites Required Knowledge • • •
Programming experience SAPTEC (SAP NetWeaver: Application Platform Fundamentals) BC400 (ABAP Workbench - Concepts & Tools)
Only
This course will prepare you to:
Partner
After completing this course, you will be able to:
Course Objectives •
Use Internal
SAP Software Component Information The information in this course pertains to the following SAP Software Components and releases: •
viii
SAP Web AS 6.20
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
• • •
Partner
• • •
Name and use the syntax elements for Unicode-compatible character string processing Use internal tables to optimum effect Use fundamental elements of object-oriented modeling in UML Create ABAP Objects programs that contain all useful object-oriented programming techniques Use the relevant tools to create object-oriented Repository objects Define, raise, and handle class-based exceptions Name and use the syntax elements for dynamic programming
SAP
• •
Use
Understand the details of object-oriented syntax elements in ABAP Objects and use these effectively Create object-oriented models of business applications Use the tools in the ABAP Workbench to develop object-oriented applications
SAP
•
Internal
Course Goals
Unit 1 Only
Unit Overview
The first lesson deals exhaustively with a topic that was completely new in the SAP Web AS 6.10.
SAP Use
Partner
Unit Objectives After completing this unit, you will be able to:
• • • •
Describe the checking procedure that determines whether an ABAP Objects program can be executed in an SAP Unicode system Consider the special requirements for string processing in an SAP Unicode system Define internal tables Perform operations on internal tables Identify table kinds and use them appropriately in different situations
Only
Internal
•
Unit Contents Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20 ........................................................ 3 Exercise 1: Unicode-Compatible Character String Processing ........... 13 Lesson: Optimized Working with Internal Tables ................................ 22 Exercise 2: Internal Tables with an Unstructured Row Type............... 57
08-03-2004
© 2004 SAP AG. All rights reserved.
SAP
The second lesson also contains a complete topic, but some of the contents will already be familiar to you. How much of the material you recognize will depend on the courses you have attended and the extent of your programming experience with ABAP Objects.
Use
Partner
In this unit, we will first deal with the purely procedural elements of the ABAP Objects programming language. That is, you can use the syntax elements introduced here either in or outside of an object-oriented context.
Internal
Completing the Procedural Parts of ABAP Objects
1
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Exercise 3: Table Kinds......................................................... 63 Exercise 4: Data Processing and Transfer to Modularization Units (Optional) ......................................................................... 71
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
2
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20 Lesson Overview
Only
Lesson Objectives • •
Describe the checking procedure that determines whether an ABAP Objects program can be executed in an SAP Unicode system Consider the special requirements for string processing in an SAP Unicode system
Use
Partner
After completing this lesson, you will be able to:
SAP
SAP
Business Example You need to develop a Unicode-enabled ABAP Objects program in the SAP Web AS 6.20.
Use Internal
If other characters are to be processed, then you will need to load a different character set table. In this way, parallel, text-based processing in one system by users from different cultures is not possible without extra work being involved. Exchanging text-based data between systems in which different character set tables are valid will also cause problems. For this reason, the Unicode character set table has been defined. It is large enough to represent all the characters in the world. With a bit sequence length of 16, we now have 65,536 different codes. The Unicode character set according to ISO/IEC 10646 is supported since SAP Web AS 6.10.
© 2004 SAP AG. All rights reserved.
3
Only
For internal representation of characters, software systems use bit sequences with fixed length. This length specifies the number of characters to be displayed altogether. The assignment between characters and bit sequence is done using the character set table. For example, the ASCII character set (length of 8 bits) consists of 256 characters.
Partner
System-Internal Representation of Characters Under Unicode
08-03-2004
Internal
In this unit, we will first introduce the terms used. After that, we will describe how you can find out whether or not you need to take any actions because of the Unicode-enablement of the SAP Web AS 6.20 and, if so, which actions these are.
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
SAP
In ABAP Objects, however, it is also possible to perform byte sequence processing. In many cases, the statements for this are the same as for string processing; however, they have different additions. Here, therefore, you need the correct decision in order to get semantically correct results. This will be discussed in more detail later in this unit.
Partner
Use
SAP
To execute the relevant syntax checks, you must set the indicator Unicode Checks Active in the program attributes. This is the standard setting in Unicode systems. In a Unicode system, you can only execute programs that have the Unicode indicator set.
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
As of SAP Web AS 6.10, you can develop Unicode-compatible applications using ABAP Objects. The runtime system ensures Unicode-compatible internal representation of its character sets. Therefore, as long as you perform “safe” string processing – that is, you do not allow information on the internal length of a character to flow into your programs – you do not need to take care of anything further.
Often, however, you want to or have to reuse old source texts in which the above limitations have not been heeded. In such cases, you may have to make certain adjustments. Here, you will be supported, for the most part, by the ABAP Workbench. The syntax check has been extended to include an optional check for Unicode compatibility.
4
Use
Partner
Only
Internal
Figure 1: Unicode Character Set Table
BC401
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20
If the Unicode indicator is set for a program, the syntax check and program are executed in accordance with the rules described in the SAP Library section about Unicode. (This is irrespective of whether it is in a Unicode or a non-Unicode system).
Only SAP Use Internal
Up to now, all arguments were interpreted implicitly in string processing as a field of the type C. As of SAP Web AS 6.10, there is a distinction between character-type and byte-type arguments. With the exception of statements that are obsolete anyway, character string commands in their standard form always expect character-type arguments for compatibility reasons. The statements are then converted by the system, character by character. For documentation reasons, you can use the optional addition IN CHARACTER MODE for these variants.
08-03-2004
© 2004 SAP AG. All rights reserved.
5
Only
Terms used: The following predefined data types are interpreted in Unicode programs as character-type: C, N, D, T, STRING, as well as structure types that contain - either directly or in substructures - solely components of these types (see also generic predefined data type CLIKE). In non-Unicode systems, a character of this type is one byte, and in Unicode systems, it is as long as a character on the relevant platform. Variables of the types X and XSTRING are described as byte-type.
Partner
Character and Byte Processing
SAP
If you wish to exchange data between Unicode and non-Unicode systems from SAP Web AS 6.10 onwards, you can use the statements EXPORT ... TO DATA BUFFER and IMPORT ... FROM DATA BUFFER, respectively. Your data is exported in XSTRING variables, but the internal Unicode-relevant additional information is also transferred. You can now exchange this byte sequence with other systems. The data is again extracted from the byte sequence with the additional information and represented internally, platform-based.
Use
The standard class CL_ABAP_CHAR_UTILITIES contains numerous characters, also CHARSIZE, that - at runtime - contain the length of a character, measured in bytes.
Internal
In programming terms, there are at least two ways to find out the internal length of a character in a certain platform: The predefined function CHARLEN() returns the length of the first character of the argument, measured in bytes.
Partner
If the Unicode indicator is not set, the program can only be executed in a non-Unicode system. For such programs, 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.
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Figure 2: Character String and Byte Sequence Processing
SAP Use Internal
The XSTRLEN function returns the length of byte sequence. It always expects byte-type variables and returns for type XSTRING the current length and for type X the defined length in bytes; null bytes at the end of fields are counted. Remember: The operators CO, CN, CA, NA, CS, NS, CP, and NP compare the contents of character-type data objects.
6
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
The STRLEN function always expects character-type variables and returns their length in characters. With variables of type C, only the occupied length is relevant - that is, unlike with variables of the STRING type, trailing blanks are not counted.
Partner
Functions and Compare Operators
SAP
Exceptions to this simple rule exist only for the statements that are already obsolete anyway. The standard variant DESCRIBE FIELD ... LENGTH ... returns, for example, the internal length of a character string, that is, the number of bytes; with variables of type STRING, it even returns the length of the reference after it - hence always eight! Only if you have the optional addition IN BYTE MODE will the length in bytes be returned for STRING variables as well. And only if you have the optional addition IN CHARACTER MODE will the number of characters be returned. This kind of non-Unicode-compatible statement would be recognized as an error if the Unicode check was active. However, it should, if at all possible, be avoided. In such cases, use the predefined functions STRLEN and XSTRLEN instead.
Use
Partner
In short, only if you want to have explicit byte processing must you use the addition IN BYTE MODE. Do not use it if you want to process character strings.
Internal
Only
The corresponding variants of these statements for byte sequence processing are recognizable by the addition IN BYTE MODE. With this addition, the statements expect solely byte-type arguments and are also converted byte by byte.
BC401
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20
For the contents of byte-type data objects, six further operators have been defined for SAP Web AS 6.10; they are distinguished from the originals by the prefix BYTE.
Use
Partner
Only
Internal SAP
SAP
Figure 3: Lengths and Compares
To check whether the conversion is allowed at all, the system first creates the Unicode fragment view of the structures by grouping together adjacent components and alignment gaps. There are separate groups for character, byte, and numeric types (I,P,F). 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.
Only
Internal
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 at specific addresses - for example, a memory address divisible by four, without remainder.) 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 referred to as alignment.
Partner
Use
Conversion Rules for Structures
If the fragments of the source and initial structures now match the type and length in the length of the shorter structure, conversion is allowed; if not, an error in the Unicode check will result. If the target structure is longer than the
08-03-2004
© 2004 SAP AG. All rights reserved.
7
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
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 values; alignment gaps are filled with null bytes.
Use
Partner
Only
Internal
Use
Only
Internal
If the structure is the target, the character-type parts of the remainder are filled with space characters and all other components with type-specific initial values. The conversion is not allowed if the structure is not purely character-type and the elementary data object is not type C.
Partner
The following rules apply for conversion of a structure into an elementary data object and vice versa: If the elementary data object is of type C, but the structure is not completely character-type, then conversion is only allowed when the structure starts with a character-type group and this group is at least as long as the elementary data object. The conversion then takes place between the first character-type group of the structure and the elementary data object.
SAP
SAP
Figure 4: Conversion Between Flat Structures
8
© 2004 SAP AG. All rights reserved.
08-03-2004
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20
Internal
Partner
Only
BC401
Figure 5: Conversion Between Structures and Elementary Data Objects
Use
Hint: Internal tables can be converted if row types can be converted.
SAP Use
Partner
Access with Offset and Length Specification Remember: Accesses to character and byte-type elementary data objects are allowed using offset and length specifications. For character-type variables, offset and length are interpreted character by character. If you have types X and XSTRING, the values for offset and length are interpreted byte by byte.
Only
Internal
SAP
You should try to avoid copying structure contents in this manner as much as possible. Instead, copy component by component. This way, no actions at all are required.
08-03-2004
© 2004 SAP AG. All rights reserved.
9
BC401
SAP
SAP
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 starting from the beginning of the structure. This means that the access will cause an error if the offset and length area contains both character-type and non-character-type components. If an offset/length access to a structure is allowed in a Unicode program, both offset and length specifications are always interpreted as characters.
Use
Partner
Figure 6: Access Using Offset and Length Specification for Elementary Data Objects
Internal
Only
Unit 1: Completing the Procedural Parts of ABAP Objects
Only
Internal
Use
Partner
Figure 7: Access Using Offset and Length Specification for Structures
10
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20
Where possible, you should try to avoid accessing contents of structures in this manner. Bear in mind that processing component by component and using character string operations is generally safer and more readable.
General Recommendations:
•
We recommend therefore that, as of now, you generally program “in a Unicode-compatible manner”; the indicator for Unicode Checks Active must always be set. In this manner, you avoid on the one hand generally unsafe techniques and obsolete statements; on the other hand, if you change your system to Unicode later on, no further checks or adjustments will be required.
Use
Partner
•
Always use the most current variants for (obsolete) statements. You will be supported to a large extent by the SAP Library. Program “safely” - that is, access structures component by component, provided there are no reasons to do otherwise. Also avoid offset/length access to entire structures.
Internal
Only
It should now be clear that you can avoid all the problems listed here very easily if you adhere strictly to the following during string processing or when working with structures:
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
11
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
12
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20
Exercise 1: Unicode-Compatible Character String Processing Exercise Objectives
Only
Business Example Assume that a data record of a specific flight is stored as an unstructured character string in the memory.
SAP Use Internal
For now, we will focus on a formatted list output.
Task 1: 1.
Only
Copy the template. Copy template: SAPBC401_DTOT_SPLIT_STRING Program name: ZBC401_##_SPLIT_STRING (Where ## is your two-digit group number). 2.
Activate your copy (or copies).
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
Partner
Using Unicode-compatible character string processing, the fragments of this character string are to be copied into structured data objects so that they can be processed further on the basis of the transparent table SFLIGHT.
SAP
Note: In practice, there are a few ways that this situation could arise. Typically, it may occur after data has been transferred from a different system or when data has been transferred remotely. Here, these cases are simulated by calling a function module that creates such data records based on the flight data model.
Use
Partner
Internal
After completing this exercise, you will be able to: • Define structure types locally in the program • Define elementary and complex data elements • Split strings • Use conversion rules • Display the contents of data objects in lists
13
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Task 2: Familiarize yourself with the program and its existing functions. Pay special attention to the content of the data object DATASTRING after the function module call. Use the ABAP Debugger to do this, and/or display the character string in a list.
Only
Task 3:
1.
Remove the two leading separators from the character string first. Hint: Use the SHIFT statement.
SAP
Hint: Use the statements FIND and SPLIT. Split the contents of auxiliary variable SET_STRING at the separators into structure WA_FLIGHT_C. The structure is defined as 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.
Task 4: Display the structured flight data as a list. 1.
As a test, display the fields of the structure WA_FLIGHT_C in a list.
2.
In the resulting list, you should have observed that some of the fields were displayed without formatting – for example, the PRICE field. Now improve this: Continued on next page
14
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
2.
Partner
Use
For this, SET_STRING has to be defined appropriately.
SAP
Then copy the initial part up to the two closing separators to the auxiliary variable SET_STRING. Assume that there can be more characters after the two closing separators; these should remain in DATASTRING.
Use
Partner
Split a character string into its individual elements and copy it into structured data objects.
Internal
Hint: Think of the function module itself as a “black box”. A deeper understanding of how it works is not part of this exercise.
BC401
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20
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 processed further. Use the predefined structure WA_FLIGHT. The structure is defined as local program structure type ST_FLIGHT. You still have to comment out the components of this structure type and assign them an appropriate type.
Internal
Only
Display the contents of the structure WA_FLIGHT in a list.
Use
Partner
Hint: Use the appropriate formatting options for the WRITE statement for the FLDATE and PRICE fields.
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
15
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Solution 1: Unicode-Compatible Character String Processing Task 1: Copy the template. 1.
Copy template: SAPBC401_DTOT_SPLIT_STRING
Only
(Where ## is your two-digit group number). Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_DTOS_SPLIT_STRING 2.
Activate your copy (or copies). a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
SAP Use
Task 3: Split a character string into its individual elements and copy it into structured data objects. 1.
Remove the two leading separators from the character string first. Hint: Use the SHIFT statement.
Continued on next page
16
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Hint: Think of the function module itself as a “black box”. A deeper understanding of how it works is not part of this exercise.
Partner
Familiarize yourself with the program and its existing functions. Pay special attention to the content of the data object DATASTRING after the function module call. Use the ABAP Debugger to do this, and/or display the character string in a list.
SAP
Task 2:
Use
Partner
a)
Internal
Program name: ZBC401_##_SPLIT_STRING
BC401
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20
Then copy the initial part up to the two closing separators to the auxiliary variable SET_STRING. Assume that there can be more characters after the two closing separators; these should remain in DATASTRING. For this, SET_STRING has to be defined appropriately. Hint: Use the statements FIND and SPLIT.
Only
2.
See the source code extract from the model solution
Split the contents of auxiliary variable SET_STRING at the separators into structure WA_FLIGHT_C.
a)
See the source code extract from the model solution
Use
Partner
The structure is defined as 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.
Internal
a)
Task 4: Display the structured flight data as a list.
SAP
As a test, display the fields of the structure WA_FLIGHT_C in a list. a)
See the source code extract from the model solution
In the resulting list, you should have observed that some of the fields were displayed without formatting – for example, the PRICE field. Now improve this:
Internal
Display the contents of the structure WA_FLIGHT in a list. Hint: Use the appropriate formatting options for the WRITE statement for the FLDATE and PRICE fields. a)
See the source code extract from the model solution Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
17
Only
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 processed further. Use the predefined structure WA_FLIGHT. The structure is defined as local program structure type ST_FLIGHT. You still have to comment out the components of this structure type and assign them an appropriate type.
Partner
Use
2.
SAP
1.
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Result Source code extract:
SAPBC401_DTOS_SPLIT_STRING sapbc401_dtos_split_string.
Internal
Only
REPORT
TYPES: 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,
Use
Partner
BEGIN OF st_flight_c,
SAP
SAP
paymentsum(22) TYPE c, seatsmax_b(10) TYPE n, seatsocc_b(10) TYPE n, seatsmax_f(10) TYPE n,
Use
Partner
seatsocc_f(10) TYPE n, END OF st_flight_c,
BEGIN OF st_flight, TYPE c,
connid(4)
TYPE n,
fldate
TYPE d,
price(9)
TYPE p DECIMALS 2,
currency(5)
TYPE c,
Only
Internal
carrid(3)
planetype(10) TYPE c, seatsmax
TYPE i,
seatsocc
TYPE i,
END OF st_flight. DATA: datastring
TYPE string,
set_string
TYPE string,
Continued on next page
18
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20
wa_flight_c TYPE st_flight_c, wa_flight
TYPE st_flight.
START-OF-SELECTION.
Internal
Only
CALL FUNCTION ’BC401_GET_SEP_STRING’ * EXPORTING *
IM_NUMBER
= ’1’
*
IM_TABLE_NAME
= ’SFLIGHT’
*
IM_SEPARATOR
= ’#’
IM_UNIQUE
= ’X’
Partner
*
IMPORTING ex_string
= datastring
no_data
= 1
OTHERS
= 2.
Use
EXCEPTIONS
SAP
SAP
IF sy-subrc <> 0. MESSAGE a038(bc401). ENDIF.
Partner
Use
SHIFT datastring BY 2 PLACES. FIND ’##’ IN datastring. IF sy-subrc <> 0. MESSAGE a702(bc401).
Internal
ENDIF. SPLIT datastring AT ’##’ INTO set_string datastring.
Only
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
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
19
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
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.
Internal
Only
MOVE-CORRESPONDING wa_flight_c TO wa_flight.
WRITE: / wa_flight-carrid, wa_flight-connid,
Partner
wa_flight-fldate DD/MM/YYYY, wa_flight-price CURRENCY wa_flight-currency, wa_flight-currency,
Use
wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc.
SAP
SAP Only
Internal
Use
Partner
20
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20
Lesson Summary You should now be able to: • Describe the checking procedure that determines whether an ABAP Objects program can be executed in an SAP Unicode system • Consider the special requirements for string processing in an SAP Unicode system
Only
Internal
Related Information
Use
Partner
... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
21
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Lesson: Optimized Working with Internal Tables Lesson Overview
Only
Therefore, this lesson goes far beyond the material that you may have covered in other courses about internal tables.
After completing this lesson, you will be able to:
Internal Tables as Dynamic Data Objects
Use internal tables for data processing in your program. Choose the most suitable table kinds and the method of processing that is best for the runtime.
Internal
Internal tables are dynamic data objects that can hold any number of rows of a fixed type. The number of rows in an internal table is limited only by the capacity of the specific system with which you are working. You can define the row type of an internal table to include elementary, structured, or even table-type, and can be as complex as you want to make it.
22
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal tables are data objects that allow you to store datasets with a fixed structure in memory. The data is stored row by row in memory. Each row has the same structure. You can also refer to each component in a row as a column in the internal table. You refer to each row in the internal table as a table row or table entry.
Partner
Business Example
SAP
SAP
Define internal tables Perform operations on internal tables Identify table kinds and use them appropriately in different situations
Use
• • •
Use
Partner
Lesson Objectives
Internal
This lesson covers nearly all aspects of working with internal tables. It contains all necessary information, starting with the definition of this special data type through to recommendations for using different table kinds and methods of access – specifically in light of runtime requirements. Also, virtually all syntactic possibilities are listed here for the first time.
Lesson: Optimized Working with Internal Tables
Internal
Only
BC401
Figure 8: Attributes of Internal Tables
Row type The row type defines the attributes of the individual columns. You normally enter a structure type, but any data type is possible.
SAP Use
•
Key access – like database tables – works via field contents.
•
For index access, unlike for database tables, the system assigns row numbers to certain kinds of internal tables. This means that you can sometimes use the index to access rows in the table. Example: Read-access to the data record with index 5 returns the fifth data record from the internal table.
The table kind is another characteristic of internal tables. Internal tables can be divided into three table kinds, depending on the possible access types.
08-03-2004
© 2004 SAP AG. All rights reserved.
23
Only
Internal
Example: Using the search term UA 0007 for read access to an internal table with the unique key CARRID CONNID and data as specified above will result in exactly one data record.
Partner
Access type
SAP
Key definition The key columns and their sequence determine the criteria by which the system identifies table rows. You can define the key as either UNIQUE or NON-UNIQUE. The uniqueness of the key must be compatible with the access type you have chosen for the table. If the key is unique, there can be no duplicate entries in the table.
Use
Partner
The data type of an internal table is fully specified by its:
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Standard tables The row number is maintained internally. Both index and key access are possible. Sorted tables Data records are sorted by the key and stored in these tables. Their index is also maintained internally. Both index and key access are possible.
Only
Use
Partner
Internal
Hashed tables The runtime-optimized data records are maintained here. This requires a unique key. Hashed tables only allow for key access.
• • •
Standard tables are usually used with index access. Sorted tables are ideally used with unique keys and fixed sorting. For hashed tables, runtime optimization generally occurs only with read access and a unique key.
Defining Internal Tables For internal tables, as for other forms of data objects, there are three fundamentally different possible combinations for specifying the data object’s type:
24
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
On a case-by-case basis, the table kind is decided by which access types will primarily be used with the table entries.
Partner
Use
SAP
SAP
Figure 9: Link Between Table Kind and Access Type
BC401
Lesson: Optimized Working with Internal Tables
Possibilities for Specifying the Type of an Internal Table • • •
with an implicit (bound) type with a local, explicitly defined type with a global, explicitly defined type
Only
Use
Partner
Internal
We fill focus on the first two possibilities, since we think that the creation of a table kind in the ABAP Dictionary is very easy once the concepts in this section are familiar.
This must be followed by a row type to determine the nesting depth of the internal table. It can be defined locally or globally or it can be a data object. You specify the table key using WITH key_def. key_def includes the names of all the key fields in order and specifies whether the key is to be UNIQUE or NON-UNIQUE
08-03-2004
© 2004 SAP AG. All rights reserved.
25
Only
Internal
There are three syntax additions that you use to specify a table kind for your internal table: STANDARD TABLE, SORTED TABLE and HASHED TABLE.
Partner
Use
SAP
SAP
Figure 10: Definition of Tables or Table Kinds In a Local Program
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
. •
The combination of the table kind and the key definition is not arbitrary, because of the special support that certain table kinds receive with specific types of read access. You can use any of the following combinations:
Partner
For standard tables Only non-unique
Use
For sorted tables Unique or non-unique
There is a standard type for internal tables. You can use a shorter syntax to define it.
Use
Interpretation of the Short Syntax by the Runtime System DATA itab_name TYPE [STANDARD] TABLE OF line_type [WITH NON-UNIQUE DEFAULT KEY].
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
DATA itab_name TYPE TABLE OF line_type.
Partner
Shorter Syntax for the Definition of Standard Tables with a Bound Type
SAP
SAP
For hashed tables Only unique
26
Internal
Only
•
Either create a user-defined key by naming the key fields after 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). Alternatively, use the pseudo-component table_line, if you are specifying a table without a structured row type, or if the entire row is being used as the key.
BC401
Lesson: Optimized Working with Internal Tables
Use
Partner
Only
Internal
SAP
Only
Internal
Partner
The DEFAULT KEY short form means that all non-numeric fields are used to create the key. They are used in the sequence in which they occur in the row type. In this case, the keys CARRID, CONNID, and DISTID are defined. The key is non-unique.
SAP
The above example shows the definition of an internal table (TT_DISTANCE) using a local table kind (TT_DISTANCE_TY), which itself uses a local row type (S_DISTANCE_TY). Therefore, the defined internal standard table has the columns CARRID, CONNID, DISTANCE, and DISTID.
Use
Figure 11: Standard Table With a Local, Explicitly Defined Type – Example
08-03-2004
© 2004 SAP AG. All rights reserved.
27
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
SAP Use
28
Allocation step
No addition
With the addition INITIAL SIZE n
0
8 bytes
8 bytes
1
8 - 16 KB
Row width * n bytes
2
8 - 16 KB
2 * row width * n bytes
every additional step
8 - 16 KB
8 - 16 KB
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Memory Allocation and Initial Size
Partner
For table kinds defined in a program, you can use the optional INITIAL SIZE addition to specify the number of rows that the runtime system should reserve when it instantiates the data object.
SAP
The above example shows the definition of a sorted table and a hashed table. Both tables have the same row type as the standard table on the previous slide. Note that the contents of the tables are in a different order. For sorted tables, the sequence of the entries in the internal table is determined by the sequence of the fields in the key definition.
Use
Partner
Only
Internal
Figure 12: Sorted and Hashed Table – Examples
BC401
Lesson: Optimized Working with Internal Tables
Specifying the number of rows is useful when your internal table is part of another internal table’s row type (nested internal tables). However, if your table needs more rows 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.)
Use
Partner
Only
Internal
SAP
Internal Table Operations
To keep the syntax patterns clear, we will start by assuming that we are dealing with an internal table with no header line and that data is exchanged using a row-compatible query area. Access using field symbols will be examined separately later.
08-03-2004
© 2004 SAP AG. All rights reserved.
29
Only
Internal
This section contains a detailed summary of the syntactical possibilities for managing data records using internal tables. Whether you are using key access or index access is specified individually for each statement.
Partner
Use
Incomplete table kinds are known as generic. You can only use them to assign types to table-type interface parameters.
SAP
Figure 13: Generic Table Kinds
standard table The data record is appended to the internal table, just as with the APPEND statement.
You can use these statements for inserting with all three types of tables. The technical implementation of the statements varies slightly according to the table kind.
SAP Use
With a unique key, and if the data record is already present, the record is not inserted and the return value SY-SUBRC is set to 4.
You can only use the COLLECT statement with internal tables whose non-key fields are all numeric (type I, P, or F). The COLLECT statement adds the work area to an internal entry with the same type or, if there is none, adds a new entry to the table. It searches for the entry according to the table kind and defined key. If it finds an entry in the table, it adds all numeric fields that are not part of the key to the existing values. If it does not, the content of the query area is inserted as a new entry.
30
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
When index tables are inserted successfully, the system field SY-TABIX is set to the insert position.
Partner
hashed table The data record is appended, but an entry is made in the hash index.
SAP
Sorted table With a unique key, the table is sorted ascendingly in accordance with the key definition. With a non-unique key, the data record is included before any duplicate data records that may be present.
Use
Figure 14: Inserting With Key Access
Internal
Only
BC401
Partner
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Lesson: Optimized Working with Internal Tables
Use
Partner
Only
Internal
Figure 15: Appending and Inserting with Index Access
SAP Use
Caution: When you use these statements, you must ensure that the sort sequence remains untouched. Therefore, we recommend using index access only with standard tables. This statement is an easy way to make a ranked list: APPEND wa INTO rank_itab SORTED BY f.
08-03-2004
© 2004 SAP AG. All rights reserved.
31
Only
Internal
Hint: If you want to insert a set of rows from an index table into another index table, you should use the INSERT LINES OF variant instead.
Partner
Within a loop, the INSERT statement adds the data record before the current record in the table.
SAP
When you are inserting and you specify an index that is more than one greater than the current number of rows, nothing is inserted and the SY-SUBRC return value is set to 4.
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
The data record in the query area wa is sorted descendingly by the maximum length as specified by INITIAL SIZE and inserted into the ranked list rank_itab. However, this only happens if the data record fits into the list according to sort criterion f. Caution: This means that a different data record may be removed from the ranked list. In this case – unlike all other cases – the INITIAL SIZE addition sets the length of the internal table.
Use
Partner
Only
Internal
If no row could be found for the key or the logical condition, nothing is changed or deleted and the return value SY-SUBRC is set to 4. In the TRANSPORTING addition, you can restrict the data transport to selected components. You can program almost any logical expression after WHERE. The only restriction is that the first field in each comparison must be a component of the row structure (see the corresponding Open SQL statements). You can pass component names dynamically. This statement is an easy way to delete duplicates:
32
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
If you use these key accesses with the variants FROM wa, the key fields in the work area must be filled.
Partner
Use
SAP
SAP
Figure 16: Changing and Deleting With Key Access
BC401
Lesson: Optimized Working with Internal Tables
DELETE ADJACENT DUPLICATES FROM itab [ COMPARING {f_1 .. f_n} | ALL FIELDS } ] .
Only
The best way to delete the entire internal table is to use any of the following three statements:
Partner SAP Use
Only
Internal
Partner
CLEAR For internal tables without a header line, it has the same effect as REFRESH. Unlike for other data objects, no initial values are inserted into the internal table.
SAP
FREE Removes all data records and releases the memory they were using. If new data records are inserted later, the system allocates new memory to them.
Use
REFRESH Removes all data records but reserves the memory they were using for future insertions, presuming the memory is not required elsewhere in the system.
Internal
If there are rows with identical key field contents that are directly below each other, all but the first row is removed. The exclusive comparison of the key fields can be removed using the COMPARING addition. If you used SORT to sort by the desired fields, there are definitely only unique data records left, as you instructed.
Figure 17: Changing and Deleting with Index Access
08-03-2004
© 2004 SAP AG. All rights reserved.
33
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
The statements listed here can be used freely with both standard and sorted tables. When you are changing or deleting and you specify an index that is greater than the current number of rows, nothing is changed or deleted and the SY-SUBRC return value is set to 4. When you change a single row, you can specify the fields that you want to change using the TRANSPORTING addition.
Only
Use
Partner
Hint: If you want to delete a set of rows from an internal table, use the variants DELETE itab FROM .. TO .. or WHERE .. instead of a loop.
Internal
Within a loop, MODIFY changes the current data record.
SAP
SAP
Use
The STABLE addition means that the relative order of records with the same sort key is not changed. The AS TEXT addition selects the culture-specific sort sequence. For example, the sort is not case sensitive.
34
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
In the standard form, the SORT statement sorts ascendingly. Thus, the ASCENDING addition is optional. For a descending sort, use the DESCENDING addition. Along with the AS TEXT addition, these can be used independently for each sort criterion (c1 to cn).
Partner
Figure 18: Sorting Standard and Hashed Tables
Lesson: Optimized Working with Internal Tables
Figure 19: Reading with Key Access
If you use the WITH TABLE KEY addition in the second variant, you must also specify the key fully. Otherwise, the system searches according to the sequence of fields that you have specified, using a binary search where possible.
SAP Use
After a successful search, the total number of rows in the table is written into the system field SY-TFILL and the rows length is written into the system field SY-TLENG. When index tables are searched successfully, the system field SY-TABIX is set to the found position. You can use the COMPARING addition to check that specified field contents of the found data records and the query area are identical. Caution: When the search is successful but the field contents are different, the return value SY-SUBRC is set to 2.
08-03-2004
© 2004 SAP AG. All rights reserved.
35
Only
Internal
If there are duplicate records that match your search criteria, the first data record that is found is displayed.
Partner
Caution: In this case, you must sort the table by the relevant fields first. Otherwise, the data record might not be found, even though it is contained in the table.
SAP
Hint: You can force the system to use a binary search with a standard table using the BINARY SEARCH addition.
Use
Partner
To read individual data records using the first variant, all fields of query area WA_1 that are also key fields of the internal table ITAB must be filled. WA_1 and WA_2 may be identical.
Internal
Only
BC401
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
In the TRANSPORTING addition, you can restrict the data transport to selected fields.
Use
Partner
Alternatively, you can use field symbols or references to access data. To do so, use ASSIGNING
or REFERENCE INTO ref_line. This will be discussed in more detail later.
Internal
Only
Instead of the target clause INTO wa [ COMPARING ] [ TRANSPORTING ] , you can also use TRANSPORTING NO FIELDS . Then no more data is transported. This variant can also be used for existence checks.
SAP Use
Only
Internal
When you are changing or deleting and you specify an index that is more than the maximum number of rows, nothing is read and the SY-SUBRC return value is set to 4.
Partner
The statement listed here can be used freely with both standard and sorted tables. The specified additions and the return value function as described above.
SAP
Figure 20: Reading a Single Record with Index Access
Figure 21: Loop Processing with Key Access
In the LOOPAT ... ENDLOOP structure, the statements within the loop are applied to each data record in turn. The INTO addition copies entries one at a time into the work area.
36
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
The system places the index of the current loop pass in the system field SY-TABIX. When the loop has finished, SY-TABIX has the same value that it had before the loop started. Inserting and deleting rows within a loop affects the subsequent loop passes.
Only SAP
SAP
Hint: You can use AT NEW ... ENDAT to achieve control level processing in loops with internal tables. For more information, see the SAP Library and/or the ABAP keyword documentation about AT.
Use
Alternatively, you can use field symbols or references to access data. To do so, use ASSIGNING or REFERENCE INTO ref_line. This will be discussed in more detail later.
Internal
Instead of the target clause INTO wa, you can also use TRANSPORTING NO FIELDS . Then no more data is transported. This variant can also be used for existence checks or counting.
Partner
Use WHERE to specify virtually any logical condition for the search results. If no data records match these conditions, nothing is read and the SY-SUBRC return value is set to 4.
The statement listed here can be used freely with both standard and sorted tables. Using FROM to specify the starting index, TO to specify the stopping index, and WHERE, you can set very flexible limits for the search results. If you specify an index after FROM that is more than the maximum number of rows, nothing is read and the SY-SUBRC return value is set to 4. Once again, the additions and return value function as described above.
08-03-2004
© 2004 SAP AG. All rights reserved.
37
Only
Internal
Use
Partner
Figure 22: Loop Processing with Index Access
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Use
Partner
Only
Internal
Figure 23: Internal Tables With or Without Header Line – Comparison
SAP Use Internal
Within object-oriented contexts, you can only use internal tables without a header line. You can always address the body of an internal table itab explicitly by using the following syntax: itab[] This syntax is always valid, whether the internal table has a header line or not.
38
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
However, internal tables with a header line do offer shorter syntax in several statements (APPEND, INSERT, MODIFY, COLLECT, DELETE, READ, LOOP AT).
Partner
The way in which the system interprets the name depends on the context. For example, the MOVE statement applies to the header line, but the SEARCH statement applies to the body of the table. To avoid confusion, you are recommended to use internal tables without header lines. This is particularly important when you use nested tables.
SAP
You can define internal tables either with (addition WITH HEADER LINE) or without header lines. An internal table with a header line consists of a work area (header line) and the actual table body. You address both objects using the same name.
BC401
Lesson: Optimized Working with Internal Tables
Example for Using an Internal Table with a Header Line DATA itab1 TYPE TABLE OF i WITH HEADER LINE. DATA itab2 LIKE itab1.
itab1
= itab2.
" <- just the header line contents!
itab1[] = itab2[]. " <- just the table contents
Use
Partner
Only
Internal
SAP
SAP
You can use the SORT statement to sort standard and hashed tables. Sorted tables are sorted by the runtime system. You can use key accesses with any table kind, but their effect differs. A key access with INSERT has the same effect on standard tables as an APPEND, that is, the relevant row is appended to the end of the table. In a sorted table, however, the record is inserted in accordance with the sort sequence. In hashed table, the row is appended, but the system also changes the hash index internally.
08-03-2004
© 2004 SAP AG. All rights reserved.
39
Only
Internal
Standard and sorted tables can be accessed using index access (APPEND, INSERT ... INDEX, LOOP AT ... FROM ... TO, and so on). However, be careful with INSERT and APPEND. If the sort sequence is violated, a runtime error occurs.
Partner
Use
Figure 24: Overview of Fundamental Operations
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
As a rule, index access to an internal table is quickest. However, it sometimes makes more sense to access data using key values. A unique key is only possible with sorted and hashed tables. If you then want to use key access, make your program code independent of the table kind. This enables generic specification of the kind and eases maintenance.
Using Field Symbols and References with Internal Tables
Only
In ABAP Objects, references can only be copied, deleted, or dereferenced. The latter means that you tell the system that instead of addressing the reference directly, you want to address the object that the reference “points” to. Use the dereferencing operator ref->* to do this.
SAP
Following are a number of interesting variants for using the aforementioned access possibilities in conjunction with internal tables.
SAP
Technically, field symbols are simply reference variables that have already been dereferenced. For compatibility reasons, they exist in parallel to the reference variables and are used differently in terms of syntax.
Use
Partner
A reference is the address of a (data) object in the memory. It “points” to the (data) object. This type of reference is held in a reference variable.
Internal
The pointer concept in ABAP Objects has evolved throughout several release cycles. Now, we form a distinction between field symbols, references, and dereferenced references.
Only
Internal
Use
Partner
40
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
SAP Use
Only
Internal
Normally, the type of field symbols and references should always be compatible with the row type of the internal table. However, generic types are also possible in dynamic programming. In this case, the CASTING addition can not be used.
Partner
Even after they have been sorted, field symbols and references still point to the assigned row.
SAP
Using some of the previously explained statements, you can use both field symbols and references to point to individual rows of internal tables. Then you can access the data records using the field symbols or the dereferencing operator. Or you can also use references to the data records directly, for example to copy the records to other reference variables.
Use
Partner
Only
Internal
Figure 25: Using Field Symbols and References for Row Access
08-03-2004
© 2004 SAP AG. All rights reserved.
41
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Use
Partner
Only
Internal
Figure 26: References When Reading and Loop Processing
SAP Use Internal
•
•
You can only change the contents of key fields if the table is a standard table. You cannot reassign field symbols within the loop. There, the statements ASSIGN do TO and UNASSIGN will cause runtime errors. The SUM statement is not available for control level processing. Note: The SUM statement adds all of the numeric fields in the work area.
42
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
•
Partner
However, there are also certain restrictions when you use this referencing technique:
SAP
When you read a table row using READ TABLE or a series of table rows using LOOP AT, you can assign the rows of the internal table to a field symbol using the addition ASSIGNING . The field symbol then points to the row that you assigned, allowing you to access it directly. Consequently, the system does not have to copy the entry from the internal table to the work area and back again.
BC401
Lesson: Optimized Working with Internal Tables
The same applies for the variant REFERENCE INTO ref_name. You can use it to have a reference point to the rows. This technique is particularly useful for accessing a lot of table rows or nested tables within a loop. Copying values to and from the work area in this kind of operation is particularly runtime-intensive. Note that these access methods are also very helpful for dynamic programming.
Use
Partner
Only
Internal
SAP
SAP
Use Internal
08-03-2004
© 2004 SAP AG. All rights reserved.
43
Only
If you use one of these three statements for exchanging data through a query area with the internal table, you can also make a field symbol or a reference point to the row you are working on by using the optional additions ASSIGNING or REFERENCE INTO ref_name.
Partner
Figure 27: References to Inserted or Changed Single Rows
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
SAP Use
Considerations for Runtime Requirements Choosing the right type of table is one of the most important factors for improving the runtime. To illustrate this fact, we will take a very simplified look at how hash management is integrated into the runtime system.
44
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
If you use the optional addition REFERENCE INTO ref_name, ref_name points to a row in the table that also contains a pointer. In both cases, if you dereference at one level, you first access the original object. But, in the second case, you only access its address.
Partner
Data exchange through a query area using the previously explained statements therefore takes the form of copying the references to or from the internal table.
SAP
In the course of object-oriented programming in ABAP Objects, you will often use this table pattern to keep object references in internal tables. Typically, you will define single-column internal tables, whose row type will be a reference to (data) objects.
Use
Partner
Only
Internal
Figure 28: Referencing vs. Copying a Reference – Comparison
Lesson: Optimized Working with Internal Tables
Figure 29: Data Management for Hashed Tables
Partner SAP Use Internal
Data records are not inserted into the table in a sorted order. As with standard tables, you can sort hashed tables using the SORT statement: Sorting the table can be useful if you later want to use a loop to access the table. This rule for using hashed tables is illustrated in the following graphic. It shows all table kinds and all possible cases of single-record read access.
08-03-2004
© 2004 SAP AG. All rights reserved.
45
Only
Using a hash technique means that the access time no longer depends on the total number of entries in the table. The access time is therefore very short. Hashed tables are therefore particularly useful for large tables with which you predominantly use read access.
Partner
If a single record is accessed using a fully specified key, the hash function can use the key immediately to determine the address of the hashed table entry. That is where the address of the actual data record is stored.
SAP
The function is not injective, that is, there can be several data records stored at a single address. This is implemented internally as a chained list. Thus, the system may still have to search through such an area sequentially. However, the chained list can contain no more than two entries. If a new key leads to the same hashed table address for a third time, the system uses a changed hash function and rebuilds the management from scratch. The graphic illustrates the simplest case, that is, in which there is only one data record stored at each address.
Use
Access to a hashed table is implemented using a hash algorithm. Simplified, this means that the data records are distributed randomly but evenly over a particular memory area. Their addresses are stored in a separate table, the hash table. The hash function uses the key data to calculate the address where the hashed table entry is located.
Internal
Only
BC401
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Use
Partner
Only
Internal
Figure 30: Completely Qualified Key vs. Partially Qualified Key with Single-Record Access
SAP Use
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 then use READ TABLE itab FROM wa. Assuming that none of the following cases are present, the runtime system carries out the syntax variant READ TABLE ... WITH KEY (reading an entry with any conditions) for all table kinds in a sequential search: For sorted tables, if the values of the first n key fields (n being less than or equal to the number of all key fields) are =
46
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
If the table is a standard table, the runtime system performs a sequential search.
Partner
Note: The binary search algorithm is a standard IT process and should be familiar. Sufficient explanations can be found in standard text books or on the Internet.
SAP
Whenever you want to read individual table rows by declaring a complete key, use READ TABLE ... WITH TABLE KEY. (This achieves the fastest single-record access with a key.) The runtime system supports this syntax variant especially for sorted and hashed tables.
BC401
Lesson: Optimized Working with Internal Tables
(no gaps), then a binary search is carried out even without the TABLE addition to the search clause. Similarly, the hash algorithm is used for hashed tables. For the previously mentioned technical reasons, this is only possible with a fully specified key.
Use
Partner
Caution: You must then use SORT to ensure that the data records are sorted by the criteria that correspond to the search clause. Otherwise, the data record might not be found, even though it is contained in the internal table.
Internal
Only
Hint: For standard tables, you can use the optional addition BINARY SEARCH to make the system do a binary search.
SAP
SAP
Use
Partner
Internal
Figure 31: Mass Processing and Table Kinds
Only
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 row in the table. This is known as a “table scan.” Sorted tables are the only exception to this rule. For them only, the runtime system can carry out runtime optimization under the following condition: In the WHERE clause, only 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 rows that match the condition in the WHERE clause.
08-03-2004
© 2004 SAP AG. All rights reserved.
47
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
SAP Use
The same applies to LOOP ... INTO compared with LOOP ... ASSIGNING or LOOP ... REFERENCE INTO.
Internal
48
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Using field symbols or references for nested internal tables is always recommended: Because the entire inner internal table is copied when you use query areas – assuming that the TRANSPORTING addition does not prevent this – the savings in runtime are proportional to the length of the inner internal table.
Partner
If you then use MODIFY to change the row, the use of field symbols or references already pays off as of a row length of 100 bytes.
SAP
You can use a READ TABLE ... ASSIGNING or READ TABLE ... REFERENCE INTO statement instead of READ TABLE ... INTO. This offers better performance at runtime for pure read access with a row width greater than or equal to 1000 bytes.
Use
Partner
Only
Internal
Figure 32: Access to Nested Tables Using Field Symbols
BC401
Lesson: Optimized Working with Internal Tables
Use
Partner
Only
Internal
Figure 33: Partial Sequential Loop Through Standard Tables
SAP
SAP
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.
Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
49
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
You can use the following algorithm to program the runtime behavior of sorted tables. 1. 2.
Sort the internal table using the desired search criteria of your loop. Use single-record read access with the addition BINARY SEARCH to determine the row number of the first row that matches your search criteria.
Only
3.
Program an index-controlled loop, starting with the row number that you just determined.
Caution: If you combine the starting row number and the original search criterion (FROM startline WHERE cityfrom = ’FRANKFURT’)
SAP
SAP
the rest of the internal table after the starting row will also be processed!
Use
Partner
Within the loop, terminate the loop if it leaves the desired control level.
Internal
Since you are usually not yet interested in the data record itself, you may wish to use the addition TRANSPORTING NO FIELDS.
An alternative to the termination criterion could be: READ TABLE ... INTO ... WITH KEY cityfrom = ’NEW YORK’
Partner
Use
TRANSPORTING NO FIELDS BINARY SEARCH.
Internal
endline = sy-tabix - 1.
Then the loop could be completely index-controlled: LOOP AT ... INTO ...
ENDLOOP.
Because the SORT and READ TABLE statements require additional runtime, this process is only beneficial if the loop is repeated several times with the same criterion, although the search values do not have to be the same. In that case, the runtime savings would be nearly proportional to the length of the internal table.
50
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
FROM startline TO endline. ...
BC401
Lesson: Optimized Working with Internal Tables
Summary and Application Example As described in the previous section, the choice of the table kind is a major factor for the program’s runtime requirements. However, this is not the only selection criterion. Certain programming methods can also save runtime (for example, the BINARY SEARCH addition). There may also be other factors that favor a certain table type. Following is a summary of the characteristics of all three table kinds, which you can use to help you choose the appropriate kind.
Only Partner SAP Use Internal
Only
51
Partner
© 2004 SAP AG. All rights reserved.
SAP
08-03-2004
Use
sorted table When you choose to use a sorted table, it will normally be because you want to define a unique key. If you decide you need to sort the table or use a binary search, you can always program these functions by hand. A hashed table also defines a unique key, but unlike a sorted table, the data is sorted and then inserted. Also, the initial data is built up faster. Thus, if you have a table with few entries but lots of accesses that change the contents, a sorted table may be more efficient than a hashed table in terms of runtime. A typical use is the preparation and execution of database changes by mass processing. The most efficient way of doing this is to create a local copy of the data in the program, make the changes to the copy, and then write all of its data records back to the database table. When you are dealing with large amounts of data, this method both saves runtime and reduces the load on the database server. Consequently, when you access the internal table, you should already use the unique key to ensure that the data record is unique. Automatic sorting can also bring further advantages.
Internal
standard table Standard tables are best when you are access data using an index, that is, the order of the the data records is important but the sorting and the uniqueness are not crucial. If you decide you need to sort the table or access it using the key or a binary search, you can always program these functions by hand. Ranked sequence management is an example of a typical use. However, you will often be forced to use this table kind for compatibility reasons.
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Only Partner SAP
SAP
In this example, the user should be able to enter a departure city, for which all possible flights and connecting flights are then listed.
Use
Finally, we will look at a fully programmed syntax example that demonstrates the use of nested internal tables and access through a field symbol.
Internal
hashed table The hash algorithm calculates the address of an entry based on the key. This means that, with larger tables, the access time is reduced significantly in comparison with a binary search. But when you use a loop with a hashed table, the whole table has to be scanned. Because the data records are usually totally unsorted, a sorted table may be more useful if you have a loop over the beginning of a key. Alternatively, you could also sort the hashed table. This table kind is only beneficial if you want to keep large amounts of data locally in the program and you mostly access it only to read it. You must ensure that you design your hashed table so that it is possible to specify the full key when you access it from your program. All in all, this leaves us with the typical use for hashed tables: Use them for buffering or bundling large amounts of data from several database tables when an ABAP Dictionary view or a nested SELECT statement is not possible. (Open SQL joins side step the table buffer of the database interface, anyway.)
Only
Internal
Use
Partner
52
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
Use
Partner
Only
Internal
Figure 34: Definition of Nested Tables in the Application Example
SAP Use
Only
Internal
Partner
Note: In order to allow loop access using field symbols, the buffer table and the inner internal table should have the same type. Furthermore, we want to sort the table by various criteria at a later stage. Consequently, use standard tables, not sorted tables.
SAP
We will define an inner table (COFL_LIST) and an outer table (TRAVEL_LIST) with corresponding query areas. A further internal table (CONN_LIST) buffers and sorts all of the flight connections.
08-03-2004
© 2004 SAP AG. All rights reserved.
53
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
SAP Use
Only
Internal
Partner
First, the flight connections starting in the city entered in PA_START are assigned to the field symbol . We are only interested in the arrival city of each flight connection. This is the first entry in a row of the outer table TRAVEL_LIST. Before the arrival city can be sorted and inserted, the inner table WA_TRAVEL-COFL_LIST must be filled with the names of the cities that can be reached from there. To do this, we use an inner loop within which the program looks for the corresponding flight connections and appends them to the internal table. Then we sort by the CITYTO and CARRID fields.
SAP
We also need to define three field symbols with the row types of the internal tables.
Use
Partner
Only
Internal
Figure 35: Loop Processing with Field Symbols for Inserting New Data
54
© 2004 SAP AG. All rights reserved.
08-03-2004
Lesson: Optimized Working with Internal Tables
Figure 36: Loop Processing with Field Symbols for Output
Partner
The output is generated by a nested loop through the outer and internal tables.
Use
Using this control level processing, only the new arrival cities are written into the list.
Internal
Only
BC401
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
55
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
56
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
Exercise 2: Internal Tables with an Unstructured Row Type Exercise Objectives
Only
Business Example
Extend your program in such a way that each data record of the character string is stored in a separate row of an internal table. Then separate the individual data records into single components and output them as before.
SAP
Copy the template. Make sure that there is more than one data record in the character string.
Use
Copy template: SAPBC401_DTOS_SPLIT_STRING or ZBC401_##_SPLIT_STRING
Partner
1.
Program name: ZBC401_##_SPLIT_ITAB
Internal
(Where ## is your two-digit group number). 2.
SAP
Task 1:
Use
Partner
The character string that was used in this lesson’s previous exercise now needs to contain more than one data record.
Internal
After completing this exercise, you will be able to: • Define single-column tables of the data type STRING • Split character strings in internal tables • Process internal tables in loops
Activate your copy (or copies). Familiarize yourself with the program and its existing functions. Use the function module BC401_GET_SEP_STRING to create 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.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
57
Only
3.
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Task 2: Define a single-column internal table of the type Standard. The column component is to have the data type STRING (suggested name: IT_SETS).
2.
Change the SPLIT statement so that a partial character string that contains a data record is always placed into a row of its internal table.
3.
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.
Use
Partner
1.
Internal
Only
Use an internal table to separate the data records and extend the list output.
SAP
SAP Only
Internal
Use
Partner
58
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
Solution 2: Internal Tables with an Unstructured Row Type Task 1: Copy the template. Make sure that there is more than one data record in the character string. Copy template: SAPBC401_DTOS_SPLIT_STRING or ZBC401_##_SPLIT_STRING
Internal
Only
1.
Program name: ZBC401_##_SPLIT_ITAB (Where ## is your two-digit group number).
Partner
a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
2.
Use
Model solution: SAPBC401_TABS_SPLIT_ITAB Activate your copy (or copies). Familiarize yourself with the program and its existing functions.
SAP
Use the function module BC401_GET_SEP_STRING to create 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.
Internal
a)
See the source code extract from the model solution
Task 2:
Partner
Use
3.
Carry out this step in the usual manner. Additional information is available in the SAP Library.
SAP
a)
Use an internal table to separate the data records and extend the list output. Define a single-column internal table of the type Standard. The column component is to have the data type STRING (suggested name: IT_SETS). a) 2.
See the source code extract from the model solution
Change the SPLIT statement so that a partial character string that contains a data record is always placed into a row of its internal table. a)
See the source code extract from the model solution Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
59
Only
1.
Unit 1: Completing the Procedural Parts of ABAP Objects
3.
BC401
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. a)
See the source code extract from the model solution
Result
Internal
Only
Source code extract:
SAPBC401_TABS_SPLIT_ITAB
Partner
REPORT
sapbc401_tabs_split_itab.
TYPES: 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,
SAP
mandt(3)
Use
SAP
BEGIN OF st_flight_c,
Partner
Use
paymentsum(22) TYPE c, seatsmax_b(10) TYPE n, seatsocc_b(10) TYPE n, seatsmax_f(10) TYPE n,
Internal
seatsocc_f(10) TYPE n, END OF st_flight_c,
carrid(3)
TYPE c,
connid(4)
TYPE n,
fldate
TYPE d,
price(9)
TYPE p DECIMALS 2,
currency(5)
TYPE c,
Only
BEGIN OF st_flight,
planetype(10) TYPE c, seatsmax
TYPE i,
seatsocc
TYPE i,
END OF st_flight.
Continued on next page
60
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
CONSTANTS c_number TYPE i VALUE 30.
DATA: datastring
TYPE string,
set_string
TYPE string,
wa_flight_c TYPE st_flight_c, TYPE st_flight.
Internal
Only
wa_flight
DATA: it_sets TYPE STANDARD TABLE OF string WITH NON-UNIQUE DEFAULT KEY
Partner
INITIAL SIZE c_number.
Use
START-OF-SELECTION. CALL FUNCTION ’BC401_GET_SEP_STRING’ EXPORTING
SAP
= c_number
*
IM_TABLE_NAME
= ’SFLIGHT’
*
IM_SEPARATOR
= ’#’
IM_UNIQUE
= ’X’
*
SAP
im_number
IMPORTING
Use
Partner
ex_string
= datastring
Internal
EXCEPTIONS no_data
= 1
OTHERS
= 2.
IF sy-subrc <> 0. MESSAGE a038(bc401).
Only
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.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
61
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
LOOP AT it_sets INTO set_string.
SPLIT set_string AT ’#’ INTO wa_flight_c-mandt wa_flight_c-carrid
Internal
Only
wa_flight_c-connid wa_flight_c-fldate wa_flight_c-price wa_flight_c-currency wa_flight_c-planetype
Partner
wa_flight_c-seatsmax wa_flight_c-seatsocc wa_flight_c-paymentsum.
Use
MOVE-CORRESPONDING wa_flight_c TO wa_flight.
WRITE: /
SAP
SAP
wa_flight-carrid, wa_flight-connid, wa_flight-fldate DD/MM/YYYY, wa_flight-price CURRENCY wa_flight-currency, wa_flight-currency,
Partner
Use
wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc.
Only
Internal
ENDLOOP.
62
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
Exercise 3: Table Kinds Exercise Objectives After completing this exercise, you will be able to: • Select the appropriate kinds of internal table • Process data using internal tables
Only
The character string that was used in this lesson’s previous exercise will now contain duplicate data records.
Use
Partner
Extend your program so that the various data records are sorted and kept in internal tables. Any data records that appear twice are to be sorted into a separate internal table.
Task 1:
SAP
SAP
Copy the template. Make sure there are non-unique data records in the character string. 1.
Internal
Business Example
Copy template: SAPBC401_TABS_SPLIT_ITAB or ZBC401_##_SPLIT_ITAB
(Where ## is your two-digit group number). 2.
Activate your copy (or copies).
3.
Use the function module BC401_GET_SEP_STRING to create a character string with non-unique data records. For these, assign the constant value SPACE to the parameter IM_UNIQUE. Note: This will create more data records that were not specified initially.
4.
Test your program.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
63
Only
Internal
Familiarize yourself with the program and its existing functions.
Partner
Use
Program name: ZBC401_##_TABKIND
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Task 2: Use an internal table to buffer the structured data records and adapt the list output. Define an internal table so that it can contain flight data sorted by airline, flight number, and flight date (suggested name: IT_FLIGHTS).
2.
Insert the separated data records (contents of the structure WA_FLIGHT) into this internal table, instead of displaying them. Hint: You can still use the output statement later.
3.
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.
4.
Display the contents of both internal tables in the list.
Use
Partner
Use the return value SY-SUBRC for the INSERT statement to ascertain whether or not a data record appears twice. To do so, you must have defined the key of your internal table accordingly.
Internal
Only
1.
SAP
SAP Only
Internal
Use
Partner
64
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
Solution 3: Table Kinds Task 1: Copy the template. Make sure there are non-unique data records in the character string. Copy template: SAPBC401_TABS_SPLIT_ITAB or ZBC401_##_SPLIT_ITAB
Internal
Only
1.
Program name: ZBC401_##_TABKIND (Where ## is your two-digit group number).
Partner
a)
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_TABS_TABKIND
Activate your copy (or copies).
Use
2.
Familiarize yourself with the program and its existing functions.
Use the function module BC401_GET_SEP_STRING to create a character string with non-unique data records. For these, assign the constant value SPACE to the parameter IM_UNIQUE. Note: This will create more data records that were not specified initially.
4.
See the source code extract from the model solution
Test your program. a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Only
Internal
a)
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
Partner
Use
3.
Carry out this step in the usual manner. Additional information is available in the SAP Library.
SAP
SAP
a)
65
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Task 2: Use an internal table to buffer the structured data records and adapt the list output. 1.
Define an internal table so that it can contain flight data sorted by airline, flight number, and flight date (suggested name: IT_FLIGHTS). a)
Insert the separated data records (contents of the structure WA_FLIGHT) into this internal table, instead of displaying them. Hint: You can still use the output statement later.
a)
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. a)
4.
Display the contents of both internal tables in the list.
Partner
a)
Use
See the source code extract from the model solution
See the source code extract from the model solution
Result
Internal
Source code extract:
SAPBC401_TABS_TABKIND
Only
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,
Continued on next page
66
SAP
SAP
3.
See the source code extract from the model solution
Use
Partner
Use the return value SY-SUBRC for the INSERT statement to ascertain whether or not a data record appears twice. To do so, you must have defined the key of your internal table accordingly.
Internal
Only
2.
See the source code extract from the model solution
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
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,
Internal
Only
seatsmax_f(10) TYPE n, seatsocc_f(10) TYPE n, END OF st_flight_c, BEGIN OF st_flight, TYPE c,
connid(4)
TYPE n,
fldate
TYPE d,
price(9)
TYPE p DECIMALS 2,
currency(5)
TYPE c,
Use
Partner
carrid(3)
seatsmax
TYPE i,
seatsocc
TYPE i,
SAP
SAP
planetype(10) TYPE c,
END OF st_flight. CONSTANTS c_number TYPE i VALUE 30.
Partner
Use
DATA: datastring
TYPE string,
set_string
TYPE string,
wa_flight
TYPE st_flight.
Only
Internal
wa_flight_c TYPE st_flight_c,
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
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
67
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
WITH NON-UNIQUE KEY carrid connid fldate INITIAL SIZE c_number.
Internal
Only
START-OF-SELECTION. CALL FUNCTION ’BC401_GET_SEP_STRING’
Partner
EXPORTING im_number
= c_number
*
IM_TABLE_NAME
= ’SFLIGHT’
*
IM_SEPARATOR
= ’#’
im_unique
= space
IMPORTING = datastring
Use
ex_string no_data
= 1
OTHERS
= 2.
SAP
SAP
EXCEPTIONS
IF sy-subrc <> 0. MESSAGE a038(bc401).
Partner
Use
ENDIF.
SHIFT datastring BY 2 PLACES IN CHARACTER MODE. FIND ’##’ IN datastring. IF sy-subrc <> 0.
Internal
MESSAGE a702(bc401). ENDIF.
Only
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
Continued on next page
68
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
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.
Internal
Only
INSERT wa_flight INTO TABLE it_flights. IF sy-subrc <> 0. INSERT wa_flight INTO TABLE it_doubles. ENDIF.
Partner
ENDLOOP.
Use
* output: *********
LOOP AT it_flights INTO wa_flight.
SAP
SAP
WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate DD/MM/YYYY, wa_flight-price CURRENCY wa_flight-currency,
Partner
Use
wa_flight-currency, wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc.
Only
Internal
ENDLOOP.
SKIP. WRITE: / ’doppelte Datensätze:’(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,
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
69
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc. ENDLOOP.
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
70
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
Exercise 4: Data Processing and Transfer to Modularization Units (Optional) Exercise Objectives
Only Partner
Now the flight data is to be sorted by the date of the flight and then displayed in different colors, according to a key date that is specified by the user.
SAP
Business Example
1.
Use
If desired, the data is to be displayed using SAP Grid Control.
Internal
After completing this exercise, you will be able to: • Select the appropriate types of internal table • Copy contents from tables with incompatible row types • Transfer contents from internal tables to modularization units
Task 1: Copy the template.
Program name: ZBC401_##_PROCESS_DATA
Use Internal
Task 2:
Activate your copy (or copies). Familiarize yourself with the program and its existing functions.
Change the sorting and color code of the list based on a user-specified key date. 1.
Make sure that the data is first displayed sorted by flight date.
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 any date as the key date. Error message 085 of the message class BC401 is to be displayed if the selected key date is in the past. Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
71
Only
2.
Partner
(Where ## is your two-digit group number).
SAP
Copy template: SAPBC401_TABS_TABKIND or ZBC401_##_TABKIND
Unit 1: Completing the Procedural Parts of ABAP Objects
3.
BC401
Ensure that the individual flight dates of the internal table IT_FLIGHTS are displayed in color according to the following criteria: Display flights that occurred in the past with the background color COL_NEGATIVE. Display flights that occurred between today’s date and the key date with the background color COL_TOTAL.
Only
Hint: Use the FORMAT COLOR col_... statement and load the type group COL.
Partner
You can reverse any color set using the FORMAT RESET statement.
Use
Task 3: If desired, display the data using SAP Grid Control.
SAP
Define a selection screen check box for displaying the data with the standard tool, SAP Grid Control (suggested name: PA_ALV).
SAP
1.
Internal
Display flights that occurred in the past with the background color COL_POSITIVE.
Only
Internal
Ensure that the data is only displayed in the usual ABAP list if the user does not check the SAP Grid Control box.
Partner
Use
Hint: Use the addition AS CHECKBOX.
Continued on next page
72
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
2.
Call the function module BC401_ALV_LIST_OUTPUT. If the function module raises an exception, terminate the program with message 702 of message class BC401. Note: If this happens, there is a problem with the system configuration.
Only SAP Use
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_FLIGHTS).
4.
The row 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 individual lines. 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. The criteria for the color coding should be the same as in the ABAP list. Always use COL_DOUBLES to display IT_DOUBLES.
Partner
3.
SAP Only
Internal
Use
Partner
Additional information about SAP Grid Control is available in the SAP Library, in the sample programs under Environment → Examples → Control Examples, and in the documents for course BC412 (ABAP Dialog Programming with EnjoySAP Controls).
Internal
Hint: 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.”
08-03-2004
© 2004 SAP AG. All rights reserved.
73
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Solution 4: Data Processing and Transfer to Modularization Units (Optional) Task 1: Copy the template. 1.
Copy template: SAPBC401_TABS_TABKIND or ZBC401_##_TABKIND
Only
(Where ## is your two-digit group number). Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_TABS_PROCESS_DATA 2.
Activate your copy (or copies). Familiarize yourself with the program and its existing functions. Carry out this step in the usual manner. Additional information is available in the SAP Library.
Task 2:
Use
1.
Make sure that the data is first displayed sorted by flight date. a)
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 any date as the key date. Error message 085 of the message class BC401 is to be displayed if the selected key date is in the past. a)
3.
See the source code extract from the model solution
Ensure that the individual flight dates of the internal table IT_FLIGHTS are displayed in color according to the following criteria: Display flights that occurred in the past with the background color COL_NEGATIVE. Continued on next page
74
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
2.
See the source code extract from the model solution
Partner
Change the sorting and color code of the list based on a user-specified key date.
SAP
SAP
a)
Use
Partner
a)
Internal
Program name: ZBC401_##_PROCESS_DATA
BC401
Lesson: Optimized Working with Internal Tables
Display flights that occurred between today’s date and the key date with the background color COL_TOTAL. Display flights that occurred in the past with the background color COL_POSITIVE. Hint: Use the FORMAT COLOR col_... statement and load the type group COL.
Only
a)
Internal
You can reverse any color set using the FORMAT RESET statement. See the source code extract from the model solution
Partner
Task 3: If desired, display the data using SAP Grid Control.
Use
1.
Define a selection screen check box for displaying the data with the standard tool, SAP Grid Control (suggested name: PA_ALV).
SAP
Ensure that the data is only displayed in the usual ABAP list if the user does not check the SAP Grid Control box. See the source code extract from the model solution
Only
Internal
Use
Partner
a)
SAP
Hint: Use the addition AS CHECKBOX.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
75
Unit 1: Completing the Procedural Parts of ABAP Objects
2.
BC401
Call the function module BC401_ALV_LIST_OUTPUT. If the function module raises an exception, terminate the program with message 702 of message class BC401. Note: If this happens, there is a problem with the system configuration.
Only
a)
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_FLIGHTS).
Use
b)
The row 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 individual lines. 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. The criteria for the color coding should be the same as in the ABAP list. Always use COL_DOUBLES to display IT_DOUBLES. a)
See the source code extract from the model solution
Result Source code extract: Continued on next page
76
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
4.
Carry out this step in the usual manner. Additional information is available in the SAP Library. See the source code extract from the model solution
Partner
a)
SAP
SAP
3.
See the source code extract from the model solution
Use
Partner
Additional information about SAP Grid Control is available in the SAP Library, in the sample programs under Environment → Examples → Control Examples, and in the documents for course BC412 (ABAP Dialog Programming with EnjoySAP Controls).
Internal
Hint: 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.”
BC401
Lesson: Optimized Working with Internal Tables
SAPBC401_TABS_PROCESS_DATA REPORT sapbc401_tabs_process_data.
TYPE-POOLS col.
...
Only
Internal
DATA: ... it_flights TYPE SORTED TABLE OF st_flight WITH UNIQUE KEY fldate carrid connid
Partner
INITIAL SIZE c_number, ...
Use
it_col_flights TYPE bc401_t_flights_color, it_col_doubles LIKE it_col_flights, wa_col_flight LIKE LINE OF it_col_flights.
SAP
SAP
... PARAMETERS: pa_date LIKE sy-datum, AS CHECKBOX DEFAULT ’X’.
Partner
Use
pa_alv
LOAD-OF-PROGRAM.
Internal
pa_date = sy-datum + 30.
AT SELECTION-SCREEN. IF pa_date < sy-datum.
Only
MESSAGE e085(bc401).
" date in the past
ENDIF.
START-OF-SELECTION. ... * output: *********
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
77
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
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.
Internal
Only
ELSE. wa_col_flight-color = col_positive. ENDIF. INSERT wa_col_flight INTO TABLE it_col_flights.
Partner
ENDLOOP.
LOOP AT it_doubles INTO wa_flight. MOVE-CORRESPONDING wa_flight TO wa_col_flight.
Use
wa_col_flight-color = col_background. INSERT wa_col_flight INTO TABLE it_col_doubles. ENDLOOP.
SAP
SAP
CALL FUNCTION ’BC401_ALV_LIST_OUTPUT’ EXPORTING it_list1
= it_col_flights
it_list2
= it_col_doubles
EXCEPTIONS
Partner
Use
control_error = 1 OTHERS
= 2.
IF sy-subrc <> 0. MESSAGE a702(bc401).
Internal
ENDIF.
ELSE.
Only
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: /
Continued on next page
78
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Optimized Working with Internal Tables
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.
Internal
Only
ENDLOOP.
FORMAT RESET.
SKIP.
Partner
WRITE: / ’doppelte Datensätze:’(dob) COLOR COL_HEADING. LOOP AT it_doubles INTO wa_flight.
Use
WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate DD/MM/YYYY,
SAP
SAP
wa_flight-price CURRENCY wa_flight-currency, wa_flight-currency, wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc.
Partner
Use
ENDLOOP.
Only
Internal
ENDIF.
08-03-2004
© 2004 SAP AG. All rights reserved.
79
Unit 1: Completing the Procedural Parts of ABAP Objects
BC401
Lesson Summary You should now be able to: • Define internal tables • Perform operations on internal tables • Identify table kinds and use them appropriately in different situations
Use
Partner
... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.
Internal
Only
Related Information
SAP
SAP Only
Internal
Use
Partner
80
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Unit Summary
Unit Summary
Only
Use
Partner
Internal
You should now be able to: • Describe the checking procedure that determines whether an ABAP Objects program can be executed in an SAP Unicode system • Consider the special requirements for string processing in an SAP Unicode system • Define internal tables • Perform operations on internal tables • Identify table kinds and use them appropriately in different situations
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
81
Unit Summary
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
82
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Test Your Knowledge
1.
What should you do with your existing programs after the upgrade from SAP R/3 4.6C to SAP Web AS 6.20?
2.
For which of the following predefined data types should you use the original variants of the standard string processing statements or the optional addition IN CHARACTER MODE?
Internal
Only
Test Your Knowledge
SAP
D C X T N STRING XSTRING
For which of the following predefined data types should you use the new compare operators BYTE-CO, BYTE-CA in compares? Choose the correct answer(s).
Internal
08-03-2004
A B C D E F G
D C X T N STRING XSTRING
© 2004 SAP AG. All rights reserved.
Only
□ □ □ □ □ □ □
Partner
Use
3.
A B C D E F G
SAP
□ □ □ □ □ □ □
Use
Partner
Choose the correct answer(s).
83
Test Your Knowledge
4.
BC401
In principle, there should be no conversion effort required for SAP R/3 4.6C to SAP Web AS 6.20 with respect to existing programs, provided there has generally always been “safe” programming for string processing (copying structures only component by component, avoiding offset/length access, and so on). Determine whether this statement is true or false.
Prior to SAP Web AS 6.10, copying of entire structure contents using MOVE was problem-free and very practical. It has only been the Unicode-enablement of SAP Web AS 6.20 that has caused problems so that this kind of programming is no longer possible.. Determine whether this statement is true or false.
□ □
As of SAP Web AS 6.10, the offset/length access generally causes a syntax error if the indicator Unicode Checks Active is set. Determine whether this statement is true or false.
7.
True False
Which of the following statements are correct? Choose the correct answer(s).
Internal
84
A B C D E F
Sorted tables can only contain non-unique keys. Standard tables can only contain non-unique keys. Sorted and hashed tables are index tables. Standard tables are index tables. The standard key is the key of a standard table. The standard key always contains all components of the row type.
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
□ □ □ □ □ □
Partner
Use
□ □
SAP
SAP
6.
True False
Use
Partner
5.
True False
Internal
Only
□ □
BC401
Test Your Knowledge
8.
Generic types are type definitions that are missing certain information. These missing type attributes are inherited from an actual parameter at runtime if you use the generic type for typing interface parameters. Determine whether this statement is true or false.
□ □
One way that generic table types enable dynamic programming is by not determining the table kind of a globally defined internal table until runtime. Determine whether this statement is true or false.
True False
10. Which of the following statements are correct?
SAP
C D
□ □
E F
11. SAP recommends using internal tables without header lines to make the syntax easier to read. This is particularly helpful with nested internal tables. Determine whether this statement is true or false.
□ □
08-03-2004
True False
© 2004 SAP AG. All rights reserved.
85
Only
Internal
□ □
Only key access works with hashed tables. Key access means that the search clause may only appear in the key fields of the internal table. Index access allows access using the row number. Single-record key access using READ TABLE can return several data records if you are using standard tables, because then the key is always non-unique. The SORT statement can sort standard tables. If you use INSERT ... INTO TABLE to insert a data record into a sorted table with a unique key, this will only work if the internal table contains no other data record with the same combination of values for the key components. Otherwise, the SY-SUBRC return value will be set to a number other than 0.
Partner
A B
SAP
□ □
Use
Choose the correct answer(s).
Use
Partner
□ □
Internal
Only
9.
True False
Test Your Knowledge
BC401
12. Which of the following statements are correct? A
□
B
□
C
□ □
D E
As far as possible, when you use key access, the runtime system always chooses the fastest possible variant, depending on the table kind. Hashed tables should not be used if you need to make many changes when you are accessing data. You can save lots of runtime by using field symbols and references, especially with nested internal tables. Binary searching is possible for standard tables. The fastest form of access in loop processing is usually through the row number.
Use
Partner
□
Internal
Only
Choose the correct answer(s).
SAP
SAP Only
Internal
Use
Partner
86
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Test Your Knowledge
Answers 1.
What should you do with your existing programs after the upgrade from SAP R/3 4.6C to SAP Web AS 6.20? Answer: In the program attributes, set the indicator Unicode Checks Active. Afterwards make sure the source code is syntactically correct.
Partner
2.
Internal
Only
Refer to the relevant section of the lesson. For which of the following predefined data types should you use the original variants of the standard string processing statements or the optional addition IN CHARACTER MODE? Answer: A, B, D, E, F Refer to the relevant section of the lesson.
SAP
SAP
For which of the following predefined data types should you use the new compare operators BYTE-CO, BYTE-CA in compares? Answer: C, G Refer to the relevant section of the lesson.
Use
Answer: True Refer to the relevant section of the lesson. 5.
Prior to SAP Web AS 6.10, copying of entire structure contents using MOVE was problem-free and very practical. It has only been the Unicode-enablement of SAP Web AS 6.20 that has caused problems so that this kind of programming is no longer possible.. Answer: False Refer to the relevant section of the lesson.
08-03-2004
© 2004 SAP AG. All rights reserved.
87
Only
Internal
In principle, there should be no conversion effort required for SAP R/3 4.6C to SAP Web AS 6.20 with respect to existing programs, provided there has generally always been “safe” programming for string processing (copying structures only component by component, avoiding offset/length access, and so on).
Partner
4.
Use
3.
Test Your Knowledge
6.
BC401
As of SAP Web AS 6.10, the offset/length access generally causes a syntax error if the indicator Unicode Checks Active is set. Answer: False Refer to the relevant section of the lesson.
7.
Which of the following statements are correct?
Only
Refer to the relevant section of the lesson.
Partner
8.
Generic types are type definitions that are missing certain information. These missing type attributes are inherited from an actual parameter at runtime if you use the generic type for typing interface parameters.
Use
Answer: True Refer to the relevant section of the lesson.
SAP
One way that generic table types enable dynamic programming is by not determining the table kind of a globally defined internal table until runtime.
Use
Partner
Answer: False Refer to the relevant section of the lesson.
Answer: A, C, E, F Refer to the relevant section of the lesson. 11. SAP recommends using internal tables without header lines to make the syntax easier to read. This is particularly helpful with nested internal tables. Answer: True Refer to the relevant section of the lesson.
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
10. Which of the following statements are correct?
88
SAP
9.
Internal
Answer: B, D
BC401
Test Your Knowledge
12. Which of the following statements are correct? Answer: A, B, C, E Refer to the relevant section of the lesson.
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
89
Unit Summary
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
90
© 2004 SAP AG. All rights reserved.
08-03-2004
Unit 2 Only
Unit Overview
SAP Use Internal
Only
Most of the content of the later unit deals with concepts that are entirely new to you. The syntax will play a much smaller part in these units.
Unit Objectives After completing this unit, you will be able to: • • • • •
08-03-2004
Explain the differences between procedural and object-oriented programming models List the advantages of the object-oriented programming model Name the most important diagram types in UML Create class diagrams Create sequence diagrams
© 2004 SAP AG. All rights reserved.
Partner
The contents of the first two lessons are essentially also applicable to other modern object-oriented languages. As of the third lesson, syntax elements that are specific to ABAP Objects are introduced. You will need to learn many of these syntax elements in short succession.
SAP
The second lesson is a compact introduction to modeling, the step in the software development process that immediately proceeds the actual programming. This will be demonstrated using the modeling standard UML. To begin with, you will only see the most basic and important elements. The lessons will succesively build upon this information, introducing the object-oriented programming concepts and the related UML notations in parallel. Therefore, this course will simultaneously teach you object-oriented modeling and programming.
Use
Partner
This unit will introduce you to the basics of object-oriented software development. The first lesson is an introduction to the new ways of thinking and the related concepts.
Internal
Introduction to Object-Oriented Programming
91
Unit 2: Introduction to Object-Oriented Programming
• • • •
BC401
Define classes Generate and delete objects Access attributes Call methods
Unit Contents
Only
Use
Partner
Internal
Lesson: The Object-Oriented Programming Model ............................. 93 Lesson: Analysis and Design with UML ......................................... 106 Exercise 5: UML Class Diagrams ............................................ 117 Lesson: Fundamental Object-Oriented Syntax Elements ..................... 120 Exercise 6: Local Classes ..................................................... 149 Exercise 7: Objects ............................................................ 155 Exercise 8: Method Calls ...................................................... 159 Exercise 9: Constructors ...................................................... 165 Exercise 10: Private Methods................................................. 171
SAP
SAP Only
Internal
Use
Partner
92
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: The Object-Oriented Programming Model
Lesson: The Object-Oriented Programming Model Lesson Overview
Only Partner
For now, it would not make sense to try to argue a conclusive point for or against the object-oriented approach. Before you can make a qualified decision, you need to get to know all object-oriented concepts and their advantages and disadvantages. Even if this sort of decision is made within your team or by your development manager, you should be able to contribute to the discussion.
Use
Lesson Objectives After completing this lesson, you will be able to:
SAP Use
As we can see from the programming language Simula 67, object-oriented programming was developed at approximately the same time as the logical and procedural programming models. In the past, Cobol and the procedural model – as in C or PASCAL – achieved dominance. Before ABAP, SAP originally used a macro assembler. Even today, many developers still have more experience with procedural programming than object-oriented programming. Therefore, this introduction to object-oriented programming also uses references to the procedural model in its explanations.
08-03-2004
© 2004 SAP AG. All rights reserved.
93
Only
Moving from the Procedural to the Object-Oriented Programming Model
You need to explain the basics of the object-oriented programming model and its advantages to your development project manager.
Partner
Business Example
Internal
•
Explain the differences between procedural and object-oriented programming models List the advantages of the object-oriented programming model
SAP
•
Internal
Based on your existing knowledge of procedural programming with ABAP, we will explain the object-oriented approach and encourage you to use it. The main emphasis will be on the explanation. At this stage, it is important to introduce you to the subject and its concepts, so that we can build on this knowledge later on.
Unit 2: Introduction to Object-Oriented Programming
BC401
Partner
Only
Internal
Figure 37: History of Selected Programming Languages
SAP Use
Partner Only
Internal
SAP
For the object-oriented part, only those object-oriented concepts that had proved their worth for enterprise application development in other languages, such as Java, C++, and Smalltalk, were adopted. As ABAP/4 did before, ABAP Objects also contains some unique, very advantageous concepts.
Use
ABAP was created with the intention of improving reporting. ABAP was developed relatively independently as an in-house programming language, although it was influenced by other programming languages like COBOL and PASCAL. ABAP/4 was then extended to form ABAP Objects. Therefore, ABAP Objects unites the object-oriented and procedural parts in one programming language.
Figure 38: Characteristics of the Procedural Programming Model
94
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: The Object-Oriented Programming Model
Data and functions are usually kept separate in the procedural programming model. Generally, global variables for a program contain data, subroutines contain functions. Essentially, every subprogram can access every variable. This means that the programming model itself does not support consistent access to some related parts of the data.
Use
Partner
Only
Internal
SAP
SAP
Use
Only
Internal
A typical procedural ABAP program consists of type definitions and data declarations, which describe the structure of the data the program uses when it is executed. Modularization units – for example, subroutines or function modules – can be encapsulated. However, on the main program level, there is no special protection for the data objects. Any variables can be accessed by any means.
Partner
Figure 39: Typical Procedural ABAP Program
08-03-2004
© 2004 SAP AG. All rights reserved.
95
Unit 2: Introduction to Object-Oriented Programming
BC401
SAP Use Internal
Therefore, a function group is a unit of data and functions that manages this data. Encapsulated access to data and services – a concept of the object-oriented programming model – can therefore be supported in the procedural part of ABAP Objects. For example, that explains how BAPIs could already be implemented as function modules and Business Objects could be implemented as function groups.
96
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Encapsulation also involves the idea that the implementation of a service can be hidden from the system’s other components, so that these cannot and do not make assumptions about the internal status of the modularization unit. This way, the design of these other components is not dependent on a specific implementation of the other modularization units.
Partner
Only function modules of the function groups can be called from the main program. In turn, the function modules can access the other components – particularly the global data – of the function groups. In other words, it is not possible to access the function group’s global data directly from the main program.
SAP
Every time a function module is called in a main program, its function group is loaded into the internal session. The function group remains active until the main program is finished. The main program and the function groups that were called in it are all stored in separate memory areas. Even if their data objects have the same names, they are not shared.
Use
Partner
Only
Internal
Figure 40: Encapsulating Data Using Function Groups
BC401
Lesson: The Object-Oriented Programming Model
SAP
SAP
The fictional function group S_VEHICLE provides a user or client with the services INC_SPEED, DEC_SPEED, and GET_SPEED. These services are the function group’s interface and access the global data object SPEED, which belongs to the whole function group.
Use
Partner
Only
Internal
Figure 41: Example of a Function Group
Only
Internal
Use
Partner
Figure 42: Example of Using a Function Group
08-03-2004
© 2004 SAP AG. All rights reserved.
97
Unit 2: Introduction to Object-Oriented Programming
BC401
The main program cannot access the function group’s data object SPEED directly.
SAP
SAP
If the main program is to work with several vehicles, this is not possible without extra programming and administration effort. Most importantly, one specific vehicle could no longer be represented by a whole function group.
Use
Partner
Only
Internal
Figure 43: Several Instances of One Function Group?
Only
Internal
Use
Partner
Figure 44: Multiple Instantiation in Object-Oriented Programming
The possibility of creating several runtime instances in a capsule for each program context is one of the key characteristics of object-oriented programming.
98
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: The Object-Oriented Programming Model
In this example, four vehicles were created, all of which have different characteristic instances. However, they all share the same data structure, the same range of functions, and the ability to protect their data against access from outside.
Use
Only
Internal
Partner
Like the function groups, the objects are also stored in the same internal session as the program that is being used. Also, all data areas are separated from each other and are therefore protected.
SAP
SAP
Use
Partner
Only
Internal
Figure 45: ABAP Main Memory and Encapsulation
08-03-2004
© 2004 SAP AG. All rights reserved.
99
Unit 2: Introduction to Object-Oriented Programming
BC401
SAP Use Internal
Some specific features of ABAP Objects only exist because of the guaranteed upwards compatibility of older ABAP language elements. Major differences in comparison to other object-oriented languages are in the development environment. You can use the ABAP Workbench’s entire range of functions with ABAP Objects.
100
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
The object-oriented concepts of ABAP Objects are essentially the same as those of other modern object-oriented languages like C++ or Java. A small number of concepts that did not prove to be successful in these other languages were not included in ABAP Objects. On the other hand, ABAP Objects also has helpful language elements that C++ and Java do not offer.
Partner
The Object-Oriented Programming Model of ABAP Objects
SAP
Unlike in procedural programming, the use of multiple instantiation in object-oriented programming allows you to create a direct abstraction of a real object. For this purpose, the established concept of encapsulation was systematically extended.
Use
Partner
Only
Internal
Figure 46: Data Management in the Procedural and Object-Oriented Models – Summary
BC401
Lesson: The Object-Oriented Programming Model
Partner
Only
Internal
Figure 47: ABAP Objects as a Compatible Extension of ABAP
SAP Use
For a list of obsolete language elements, refer to the ABAP keyword documentation. Each of the obsolete statements is also specifically noted as forbidden in the object-oriented context.
08-03-2004
© 2004 SAP AG. All rights reserved.
101
Only
Internal
However, it is also advisable to avoid obsolete statements in the purely procedural environment, as this creates source texts that are safer and more flexible. Nevertheless, as the language is upwardly compatible, it is not possible to prevent the use of such statements entirely.
Partner
In developing ABAP Objects, the ABAP language was cleaned up, in particular in the object-oriented contexts. This means that obsolete statements lead to syntax errors.
SAP
Type checks in the object-oriented contexts of ABAP Objects are stricter than those in the procedural contexts.
Use
ABAP Objects is not a new language, but has been designed as a systematic extension of ABAP. All of the extensions, including the old procedural parts, are upwardly compatible.
BC401
Internal
Figure 48: Client/Server Relationships Between Objects
Objects behave like client/server systems: When one object sends a message to another object, telling it to behave in a certain way, the first object can be seen as a client and the other as a server.
SAP
The client object must adhere to the server object’s “protocol” The protocol must be clearly described so that a potential client can follow it without problem
In principle, objects can perform both roles simultaneously: They can offer services to other objects while requesting services at the same time.
Internal
For example: The common task “data retrieval and output” should be distributed over at least two objects. One is responsible for data retrieval and one for output. As long as the data retrieval object does not change its protocol, its internal implementation can be altered, without any changes to the output object becoming necessary. Alternatively, the data retrieval object could even be replaced by a different object, providing that the new object uses the same protocol. These exchanges can also take place at runtime.
102
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
In object-oriented programming, the services are distributed amongst the objects in such a way as to avoid redundancies and so that each object offers exactly those services that are within its area of responsibility. If it needs any other services, it requests these from other objects. This is known as the principle of delegation of tasks.
Partner
Use
• •
SAP
To be able to separate requests and deliveries of services, the following must be true:
Use
Partner
Only
Unit 2: Introduction to Object-Oriented Programming
BC401
Lesson: The Object-Oriented Programming Model
SAP Use
To summarize, the object-oriented programming model of ABAP Objects is characterized by the following: Characteristics of the Object-Oriented Programming Model • • •
08-03-2004
Objects are a direct abstraction of the real world Objects are units made up of data and the functions belonging to that data Processes can be implemented realistically
© 2004 SAP AG. All rights reserved.
103
Only
Internal
event-controlling Instead of sending messages directly to specific objects, objects can also initiate events. Events can be triggered it it is not yet known at the time of development if objects will react, and if so, how they will react.
Partner
polymorphism In object-orientation, polymorphism is when instances of different classes respond differently to the same messages.
SAP
inheritance Inheritance defines the implementation relationships between classes, so that one class (the subclass) adopts the structure and behavior of another class (superclass), possibly also adapting or extending it.
Use
Partner
Only
Internal
Figure 49: Additional Concepts of the Object-Oriented Programming Model
Unit 2: Introduction to Object-Oriented Programming
BC401
Advantages of the Object-Oriented Programming Model over the Procedural Programming Model •
Improved software structure and consistency in the development process
• •
Partner
•
Reduced maintenance effort and less susceptibility to errors Better integration of the customer/user into the analysis, design, and maintenance process Easier and safer possibilities for extending the software
In object-oriented programming, analysis and design decisions have an even greater effect on the implementation than they do in procedural programming.
Internal
Only
The language used in the various phases of software development (analysis, specification, design, and implementation) is uniform. Communication is much easier when changing between phases.
Use
SAP
SAP
Internal
Use
Partner
Figure 50: The Software Development Process
104
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Therefore, you should already structure and formally standardize the analysis and design phase. This is done using modeling languages.
BC401
Lesson: The Object-Oriented Programming Model
Lesson Summary You should now be able to: • Explain the differences between procedural and object-oriented programming models • List the advantages of the object-oriented programming model
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
105
Unit 2: Introduction to Object-Oriented Programming
BC401
Lesson: Analysis and Design with UML Lesson Overview In this lesson, we will work out how you should approach the object-oriented solution to a business application problem, starting with the classification of your objects through to the definition of the relationships between them.
Internal
Only
We will be using parts of the UML modeling standard as a visual aid.
Lesson Objectives After completing this lesson, you will be able to: Name the most important diagram types in UML Create class diagrams Create sequence diagrams
Use
Partner
• • •
Business Example
Classification
Use
Only
Internal
All characteristics and behavior of these similar objects are now grouped into one central class. This class is used to describe every object that derives from it. A class is therefore a description of a quantity of objects that are typified by the same characteristics and the same behavior.
Partner
With object-oriented programming, we regard the real world as a collection of objects – for example, different airplanes, cars, and people. Some of these objects are very similar, that is, they can be described using the same attributes or characteristics and behave the same way.
SAP
SAP
A business application requirement is to be modeled before it is implemented.
106
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Analysis and Design with UML
Partner
Only
Internal
Figure 51: Classification of Objects
SAP Use
In German literature on the subject of object orientation, we often speak of “instances”. This simply means an object. Note: In the literal sense of the word “instance”, the meaning is slightly more specific. It means a concrete – that is, uniquely identifiable – instance of a class. In the following pages, we will make a distinction between instance and object.
08-03-2004
© 2004 SAP AG. All rights reserved.
107
Only
Internal
Two coffee cups have the same height and diameter, have the same handle, and are both white. Although their statuses are completely identical, they are clearly two separate coffee cups.
Partner
For example:
SAP
Consequently, an object has an identity, a status (number of characteristic instances), and a behavior. Do not confuse the concepts of identity and status. Identity is an attribute that distinguishes each object from all other objects of its class. Two different objects can have identical attribute values and still not be identical.
Use
For example, the vehicle “make x, ... serial number n”, is an object of class “car”. This object is therefore a concrete instance of its class.
Unit 2: Introduction to Object-Oriented Programming
BC401
Partner
Only
Internal
Figure 52: Classes as Abstraction Forms
SAP Use
Partner Only
Internal
SAP
This example concerns vehicles. Software for a vehicle enthusiast and software for a scrap-merchant contain different abstractions (classes) for these objects. So, depending on the type of abstraction, a class can contain very different aspects of the objects.
Use
In a software context, abstractions are simplified representations of complex relationships in the real world. A real, existing object is abstracted to the dimensions that are relevant for simulating the required section of the real world.
108
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Analysis and Design with UML
Use
Partner
Only
Internal
Figure 53: Classes and Objects – Comparison
SAP
Modeling in UML
Use
You can find the UML specifications on the OMG homepage at: http://www.omg.org UML describes a number of different diagram types in order to represent different views of a system. The following three types are of special importance in this context: Class diagrams Show the classes and the relationships between them, that is, a static view of a model
08-03-2004
© 2004 SAP AG. All rights reserved.
109
Only
Internal
UML is an industry standard. The Object Management Group (OMG) has been developing it since 1997. SAP uses UML as the company-wide standard for object-oriented modeling.
Partner
Unified Modeling Language (UML) is a worldwide standardized modeling language. It is used for the specification, construction, visualization, and documentation of models for software systems and enables uniform communication between users.
SAP
A sure understanding of the relationship between classes and objects is an absolute prerequisite for proceeding with the following lessons successfully.
Unit 2: Introduction to Object-Oriented Programming
BC401
Behavior diagrams Specifically show the timing sequence of the objects’ behaviors amongst each other Component diagrams Show the organization and dependencies of components
Use
Partner
The third aspect is realized in the Repository object package. In other words: Packages can be used to realize the structure of software components within SAP Web AS, according to the structure’s specification in a component diagram.
Internal
Only
Later, we will need to find concrete methods for realizing the first two aspects in the list in the programming language.
Internal
Attributes describe the data that can be stored in the objects of a class. They also determine the status of an object. Methods describe the functions that an object can perform. They therefore determine the object’s behavior.
110
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
A class is represented by a rectangle in UML notation. First, the class’s name is given, then its attributes, and finally its methods. However, you also have the option of omitting the attribute part and/or the method part.
Partner
Use
SAP
SAP
Figure 54: Representation of a Class
Lesson: Analysis and Design with UML
A class diagram describes all static relationships between the classes. There are two basic forms of static relationships: association In this example: A customer books a car at a rental car company.
SAP Use
Only
Internal
Partner
Note: As mentioned previously, classes can also be shown in class diagrams with their attributes and methods. Here, these have been left out to improve clarity.
SAP
Generalization / Specialization In this example: A car, a bus, and a truck are all vehicles.
Use
Partner
Figure 55: Example of a Class Diagram
Internal
Only
BC401
Figure 56: association
08-03-2004
© 2004 SAP AG. All rights reserved.
111
Unit 2: Introduction to Object-Oriented Programming
BC401
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 associations.
• • •
SAP
SAP
In this example, you could also require a cardinality of “at least one”, to indicate that only a person who actually makes a booking becomes a customer of the rental car company. On the other hand, the cardinality “any number” would allow for a more general definition of a customer.
Use
Partner
Each association has two roles, one for each direction of the association. Each role can be described with a name. Each role has a cardinality that shows how many instances can 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. Like all other elements of the model, cardinalities are dependent on the concrete situation that is being modeled.
Internal
Only
An association is usually a relationship between different classes (binary association). 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.
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 This name is written in italics above the line and can have an arrow to show the read direction
Only
Internal
Use
Partner
Figure 57: Aggregation and Composition
112
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Analysis and Design with UML
Aggregation and composition are specializations of association. They show that an object consists of other objects or contains other objects (composition part). The relationship can be described with the words “consists of” or “is a part of”. For example, a car partly consists of wheels.
Use
Only Partner
Composition is a specialization of aggregation. Composition means that the object contained cannot exist without the aggregate (for example, a car reservation cannot exist without the car rental). Therefore, the cardinality of the aggregate can only be exactly one. The lifetime of the individual parts is linked to the lifetime of the aggregate: Parts are created either with or after the aggregate, and they are destroyed either with or before the aggregate.
Internal
Aggregation and composition are displayed as a line between two classes that is labeled with a small rhombus. The rhombus indicates the aggregate, that is, the composition. Otherwise the notation conventions are the same as for associations.
In UML notation, composition is denoted by a filled-in rhombus.
SAP
SAP Only
Internal
Use
Partner
Figure 58: Generalization and Specialization
Generalization and specialization relationships are always bidirectional. Generalization can be described with the words “is a special.” Generalization/specialization relationships are indicated by a triangular arrow. This arrow always points to the more general class. The level of generalization increases in the direction of the arrow. Trees can be built up using several of these relationships.
08-03-2004
© 2004 SAP AG. All rights reserved.
113
Unit 2: Introduction to Object-Oriented Programming
BC401
Partner
• •
Creating and deleting objects Exchanging messages between objects
Use
An object is active when actions are executed An object is indirectly active if it is waiting for a subordinate procedure to end
Messages are shown as horizontal arrows between the object lines. The message is written above the arrow in the form nachricht (parameter) . There are various ways of representing the reply; in this example, it is shown as a dotted returning arrow. You can also include a description of the process and add comments to the object lifeline as required.
114
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
• •
Partner
The control focus is shown as a vertical rectangle on the object lifeline. The control focus shows the object’s “active” period:
SAP
In UML notation, the object lifeline is represented by dotted vertical lines with a box containing the object name at the top. An ’X’ marks the end of the lifeline.
Sequence diagrams are used to display certain processes or situations. Sequence diagrams focus on the time sequence of the behavior:
Use
SAP
Only
Internal
Figure 59: sequence diagram
Lesson: Analysis and Design with UML
Internal
Only
BC401
In delegation, two objects are involved in handling a request: The recipient of the request delegates the execution of the request to a delegate.
SAP
SAP
In this example, the driver (object DRIVER) sends the message GET_FUEL_LEVEL to the vehicle (object CAR). The receipt of this message causes the car to send a message to the tank (object TANK) to find out the tank’s contents. That is, the car delegates this task to the tank. If necessary, the car formats the information containing the current value of the tank contents before it passes it back to the driver.
Use
Partner
Figure 60: Delegation Principle in a Sequence Diagram
Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
115
Unit 2: Introduction to Object-Oriented Programming
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
116
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Analysis and Design with UML
Exercise 5: UML Class Diagrams Exercise Objectives After completing this exercise, you will be able to: • Design simple UML class diagrams • Model basic object classifications
Only
Internal
Business Example Modeling simple airplane management.
Partner
Task 1: Model some key classes for simple airplane management.
SAP
for the airline companies
LCL_AIRPLANE
for airplanes (general)
LCL_PASSENGER_PLANE
for passenger planes
LCL_CARGO_PLANE
for cargo planes
Include some appropriate attributes and methods for each class.
Partner
Use
LCL_CARRIER
SAP
2.
Your UML class diagram should contain the following classes:
Use
1.
Task 2: 1.
Choose suitable association types.
2.
Choose suitable cardinalities.
Only
Internal
Define relationships between your classes.
08-03-2004
© 2004 SAP AG. All rights reserved.
117
Unit 2: Introduction to Object-Oriented Programming
BC401
Solution 5: UML Class Diagrams Task 1: Model some key classes for simple airplane management.
LCL_CARRIER
for the airline companies
LCL_AIRPLANE
for airplanes (general)
LCL_PASSENGER_PLANE
for passenger planes
LCL_CARGO_PLANE
for cargo planes
a) b) 2.
Use the relevant sections of the lesson as a guide. Speak to your instructor if you have any questions.
Include some appropriate attributes and methods for each class. a) b)
Use the relevant sections of the lesson as a guide. Speak to your instructor if you have any questions.
SAP
SAP
Task 2: Define relationships between your classes.
Use
Choose suitable association types. a) b)
Use the relevant sections of the lesson as a guide. Speak to your instructor if you have any questions.
Choose suitable cardinalities. a) b)
Use the relevant sections of the lesson as a guide. Speak to your instructor if you have any questions.
Result A generalization/specialization relationship between LCL_AIRPLANE and LCL_PASSENGER_PLANE or LCL_CARGO_PLANE seems to be appropriate. The general attributes and methods should be contained in LCL_AIRPLANE. An aggregation should exist between LCL_AIRPLANE and LCL_CARRIER. The relevant cardinalities are debatable.
118
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
2.
Partner
1.
Use
Partner
Your UML class diagram should contain the following classes:
Internal
Only
1.
BC401
Lesson: Analysis and Design with UML
Lesson Summary You should now be able to: • Name the most important diagram types in UML • Create class diagrams • Create sequence diagrams
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
119
Unit 2: Introduction to Object-Oriented Programming
BC401
Lesson: Fundamental Object-Oriented Syntax Elements Lesson Overview In the course of this lesson, you will put your models into practice. First, you need to learn the fundamental object-oriented syntax elements.
Internal
Only
You will receive a step-by-step introduction to the definition of local classes and their basic uses, accompanied by several exercises.
Lesson Objectives After completing this lesson, you will be able to:
Partner
Define classes Generate and delete objects Access attributes Call methods
Use
• • • •
SAP
The concept of classes is the foundation for all object-oriented thinking. This section will explain and define the main components of a class.
SAP
You want to the implement classes, objects, and associations of your model in ABAP Objects.
Use
Business Example
Partner Only
Internal
Classes, Attributes, and Methods
120
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
SAP
SAP
This picture shows a vehicle as an example of a class. Using this example, we will examine the individual concepts. The node on the left shows that the public components of the class can be accessed “from outside.” On the other hand, private attributes of the class should not be accessible “from outside.”
Use
Partner
Only
Internal
Figure 61: Example of a Class
Only
Internal
Use
Partner
Figure 62: Defining Classes
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.
08-03-2004
© 2004 SAP AG. All rights reserved.
121
Unit 2: Introduction to Object-Oriented Programming
BC401
All components of the class are defined in the definition part. The components are attributes, methods, events, constants, types, and implemented interfaces. Only methods are implemented in the implementation part. The CLASS statement cannot be nested, that is, you cannot define a class within a class. Note: However, you can define auxiliary classes for global classes.
Use
Partner
Only
Internal
SAP
Attributes contain the data that can be stored in the objects of a class. Class attributes can be one of three types: elementary, structured, or table-type. They can consist of local or global data types or reference types.
122
MAKE
Vehicle make
MODEL
Type or model
SER_NO
Serial number
COLOR
Color
MAX_SEATS
Number of seats
R_MOTOR
Reference to class LCL_MOTOR
© 2004 SAP AG. All rights reserved.
Only
Internal
Examples of attributes for the class LCL_VEHICLE are:
Partner
Use
SAP
Figure 63: Example of Attributes
08-03-2004
Lesson: Fundamental Object-Oriented Syntax Elements
Internal
Figure 64: Definition of Attributes, Types, and Constants
In classes, you can only use the TYPE addition to refer to data types. You can only use the LIKE reference for local data objects.
SAP Use
Only
Internal
Partner
Using TYPE REF TO, an attribute can be typed as any reference. This will be discussed in more detail later.
SAP
The READ-ONLY addition means that a public attribute that was declared with DATA can be read from outside, but can only be changed by methods in the same class. You can currently only use the READ-ONLY addition in the public visibility section (PUBLIC SECTION) of a class declaration or in an interface definition.
Use
Partner
Only
BC401
08-03-2004
© 2004 SAP AG. All rights reserved.
123
Unit 2: Introduction to Object-Oriented Programming
BC401
Use
Partner
Only
Internal
Figure 65: Visibility Sections of Attributes
SAP
SAP
You can protect attributes against access from outside by characterizing them as private attributes. The private components of the class cannot be addressed directly from outside. They are not visible to the outside user.
Use
Conversely, if the public components of a class were incompatibly changed, every outside user would have to take these changes into account. Therefore, you should use public attributes very sparingly and/or avoid making subsequent incompatible changes to the public components.
124
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Using the private visibility section is also known as “information hiding” or encapsulation. In part, this is to protect the user of a class: Assume that the private components of a class are changed at some point; however, its interface remains the same. The public components of the class are the point of contact where outside users can access the class’s components, so they still work with the class as before, even after changes are made. The user does not “notice” the change. Only the internal implementation was changed.
Partner
Attributes that an outside user can access directly are public attributes. The public components of a class are sometimes collectively known as the class’s “interface”.
Internal
Note: The “friendship” concept is an exception to this rule.
Lesson: Fundamental Object-Oriented Syntax Elements
Internal
Figure 66: Accessing Private Attributes
Define private attributes in the PRIVATE SECTION of a class. Define public attributes in the PUBLIC SECTION.
SAP Use Internal
08-03-2004
© 2004 SAP AG. All rights reserved.
125
Only
To save runtime, individual attributes are sometimes defined in the public visibility section, but they must then be given the READ-ONLY addition.
Partner
For this example, imagine that the MAKE and MODEL attributes are public. The risk would be too large, since a user might forget to supply one of the two attributes or specify two inconsistent attributes. Instead, you could use a public method SET_TYPE to ensure that values are specified for both attributes. A strict syntax check governs method calls to check that all obligatory parameters are transferred. It would even be possible for the method itself to perform a consistency check (to see if a certain vehicle make produces the chosen model), and to raise an exception if an error occurs.
SAP
It is syntactically impossible to directly access private methods from outside. However, it is possible using public methods that output or change the attributes. This requires slightly more runtime (method call instead of value assignment) to allow for the encapsulation concept: In this case, the signature of the public method specifies exactly which values should be transferred and what type they should be. This relieves the outside user of all responsibility. The method itself is only responsible for ensuring that all private attributes are dealt with consistently.
Use
Partner
Only
BC401
BC401
Figure 67: Comparison of Instance Attributes with Static Attributes
Instance attributes Instance attributes are attributes that exist once per object, that is, once per runtime instance of the class. They are defined with the syntax element DATA.
SAP Use
Technical literature often refers to static attributes as “ class attributes” (compare to the CLASS-DATA syntax element). In ABAP Objects – like in C++ and Java – the official term is “static attribute.”
126
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Types and constants Central application data buffers Administration information, for example instance counters
Partner
• • •
SAP
Static attributes Static attributes exist once for each class and are visible for all runtime instances in that class. They are defined with the syntax element CLASS-DATA. Static attributes usually contain information that applies to all instances, such as:
Use
Partner
There are two kinds of attributes:
Internal
Only
Unit 2: Introduction to Object-Oriented Programming
Lesson: Fundamental Object-Oriented Syntax Elements
SAP Use
Only
Internal
Partner
Caution: Here, an integer data object is defined in order to count the instances. It is not possible to find out the number of created instances from the system.
SAP
The graphic shows an example of how the static attribute N_O_VEHICLES is related to the other program elements in the memory: It exists only once – in the loaded class – regardless of the number of instances of LCL_VEHICLE. Therefore, you can say that instances share their common attributes.
Use
Partner
Figure 68: Instance Attributes and Static Attributes in the Program Context
Internal
Only
BC401
08-03-2004
© 2004 SAP AG. All rights reserved.
127
Unit 2: Introduction to Object-Oriented Programming
BC401
SAP Use
All input parameters (IMPORTING and 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 transferred 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.
128
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
One method return value can be defined using the RETURN parameter. It must always be transferred as a value. In this case, you cannot then define the EXPORTING and CHANGING parameters. You can also use the RETURNING parameter to define functional methods. This will be discussed in more detail later.
Partner
Methods have a signature (interface parameters and exceptions) that enables them to receive values when they are called and pass values back to the calling program. Methods can have any number of IMPORTING, EXPORTING, and CHANGING parameters. All parameters can be passed by value or reference.
SAP
Methods are internal procedures in classes that determine the behavior of the objects. They can access all attributes in their class and can therefore change the state of other elements.
Use
Partner
Only
Internal
Figure 69: Methods – Syntax
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Like function modules, methods also support the SY-SUBRC return value, but only if the signature exceptions were defined using EXCEPTIONS. As of SAP Web AS 6.10, the RAISING addition can be used in its place to propagate class-based exceptions. The caller then handles these class-based exceptions without evaluating the SY-SUBRC return value.
SAP
SAP
Use
Partner
Only
Internal
Figure 70: Visibility Sections of Methods
Use
Only
Internal
Partner
Methods also have to be assigned to a visibility section. This determines whether the methods are called from outside the class or only from within the class. Thus, private methods only serve the purpose of internal modularization.
08-03-2004
© 2004 SAP AG. All rights reserved.
129
Unit 2: Introduction to Object-Oriented Programming
BC401
SAP
It is not possible to directly access private methods from outside. However, a private method can be called by a public method.
Use
Namespace: Within a class, attribute names, method names, event names, constant names, type names, and alias names all share the same namespace. As with subroutines and function modules, there is an additional local namespace within methods. This means that local declarations override those for the whole class.
130
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Caution: This is an introductory example. Later, you will learn more programming techniques for evaluating formal parameters.
Partner
In this example, INIT_TYPE is a private method that is called by the public method SET_TYPE. The instruction to initialize the attributes could exist in other contexts as well, so the definition of this private “auxiliary method” is worthwhile.
SAP
Define private methods in the PRIVATE SECTION of a class. Define public attributes in the PUBLIC SECTION.
Use
Partner
Only
Internal
Figure 71: Accessing Private Methods
Lesson: Fundamental Object-Oriented Syntax Elements
Internal
Figure 72: Comparison of Instance Methods with Static Methods
Instance methods are defined using the syntax keyword METHODS.
SAP Use
Only
Internal
Technical literature often refers to static methods as “ class methods” (compare to the CLASS-METHODS syntax element). In ABAP Objects – like in C++ and Java – the official term is “static method.”
Partner
In this example, only the static attribute N_O_VEHICLES can be accessed within the static method GET_N_O_VEHICLES. All other attributes of the class are instance attributes and can only appear within instance methods.
SAP
Static methods are defined at class level. The restriction that only static components can be accessed applies in the implementation part. This means that static methods do not need instances, that is, they can be accessed directly through the class. This will be discussed in more detail later. The methods are defined using the syntax keyword CLASS-METHODS.
Use
Partner
Only
BC401
08-03-2004
© 2004 SAP AG. All rights reserved.
131
Unit 2: Introduction to Object-Oriented Programming
BC401
Use
Partner
Only
Internal
Figure 73: Visibility Sections and UML Notation
SAP Use
Static components are marked with an underscore.
•
•
The input and output parameters and the parameters to be changed are shown in brackets after the method name. The types are always specified after a colon. For a function method, the method name and the brackets are followed by the event parameter, separated by a colon.
Objects: Instances of Classes You could use classes to write complete applications by only using static components. However, the reasoning behind object-oriented programming is to create and work with runtime instances of classes.
132
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
The method signature is represented as follows (optional):
Partner
UML also allows manufacturers of modeling tools to create their own symbols for visibility. Representation of visibility characteristics is optional and is normally only used for models that are close to implementation.
SAP
A UML class diagram lists the class name first and class attributes and methods below it. The visibility of components in a class is shown in UML using the characters + and -: Alternatively, public and private can be prefixed to the method.
Lesson: Fundamental Object-Oriented Syntax Elements
Internal
Figure 74: Overview of Instances of Classes
SAP
Which values may be written into which attributes is irrelevant. Technically, the object has an ID (in this case, 5) which is, however, not accessible.
Use
Only
Internal
Instantiation of class LCL_VEHICLE creates a vehicle object. The private attributes still contain the technical initial values.
Partner
For example:
SAP
A class contains the generic description of an object, that is, all characteristics that all objects of the class have in common. During the program runtime, the class is used to create discrete objects (instances) in the memory. This process is called instantiation. If this is the first time the class is accessed, the class is also loaded into the memory.
Use
Partner
Only
BC401
08-03-2004
© 2004 SAP AG. All rights reserved.
133
Unit 2: Introduction to Object-Oriented Programming
BC401
Use
SAP
SAP
DATA r_vehicle1 TYPE REF TO lcl_vehicle to define a reference variable, which is thereby typed as a pointer to objects of type lcl_vehicle. The null reference is the technical initial value of a reference variable. (“The pointer is pointing to nothing.”)
Use
Partner
Only
Internal
Figure 75: Definition of Reference Variables
Only
Internal
Use
Partner
Figure 76: Creating Objects
134
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
The statement CREATE OBJECT creates an object in the memory. Its attribute values are then either initial or assigned according to the VALUE specification.
Use
Partner
Only
Internal SAP
SAP
Figure 77: Reference Semantics of Object References
Reference variables can also be assigned to each other. For the above example, this would mean that after the MOVE statement, R_VEHICLE1 and R_VEHICLE2 point to the same object.
Only
Internal
Use
Partner
Figure 78: Garbage Collector
08-03-2004
© 2004 SAP AG. All rights reserved.
135
Unit 2: Introduction to Object-Oriented Programming
BC401
Independent references are references that have not been defined within a class. The Garbage Collector is a system routine that is automatically started whenever the runtime system does not have more important tasks to carry out. In this example, the reference to object (2)LCL_OBJECT is initialized. Afterwards, no references point to this object. Therefore, the Garbage Collector deletes it. Consequently, no references point to object (4)LCL_OBJECT anymore, so it is deleted as well.
Use
Partner
Only
Internal
Internal
136
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
If you want to keep several objects from the same class in your program, you can define an internal table that contains one column with the object references for this class. When you use a single-column internal table and you want to program logical conditions for the LOOP statement, you have to use the TABLE_LINE pseudo component. To do this, however, the relevant attributes need to be public.
Partner
Use
SAP
SAP
Figure 79: Reference Administration with Multiple Instantiation
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Use
Partner
Only
Internal
Figure 80: Aggregation Example
SAP Use
Accessing Attributes and Methods
Only
Internal
This section will teach you how to use classes and instances. That is, you will learn about the entire process, starting with the static connections of various instances, through to their practical effects.
Partner
References are transferred to objects in class LCL_VEHICLE to create the desired association.
SAP
The objects in the class LCL_WHEEL have their own identity. They can be created in this example, regardless of the existence of an object in the class LCL_VEHICLE.
08-03-2004
© 2004 SAP AG. All rights reserved.
137
Unit 2: Introduction to Object-Oriented Programming
BC401
SAP Use
Only
Internal
Partner
The example shows the shorter syntax for method calls – supported as of SAP Web AS 6.10 – in which the CALL-METHOD prefix is omitted.
SAP
An object that requires the services of another object sends a message to the object providing the services. This message names the operation to be executed. The implementation of this operation is known as a method. For the sake of simplicity, ’method’ will henceforth be used as a synonym for operation and message. Therefore, an object’s behavior is determined by its method. A method’s signature can also be used to exchange values.
Use
Partner
Only
Internal
Figure 81: Calling Methods
138
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Use
Partner
Only
Internal
Figure 82: Calling Instance Methods – Syntax
SAP Use
The RECEIVING, IMPORTING, and CHANGING parameters are mutually exclusive. Please see the section about functional methods for more details. Otherwise, the same rules apply here as they do for calling a function module.
Only
Internal
A shorter syntax is also supported as of SAP Web AS 6.10. In this case, CALL METHOD is omitted and the parameters are listed in brackets. There must be no space before the bracket, but there must be at least one space after the bracket. When you call a method that has only one import parameter, you can specify the actual parameter in the brackets without any other additions. When you call a method that only has import parameters, you can omit the EXPORTING addition.
Partner
08-03-2004
SAP
Instance methods are called with CALL METHOD ref->method_name .... When calling an instance method from within another instance method, you can omit the instance name ref. The method is automatically executed for the current object.
© 2004 SAP AG. All rights reserved.
139
Unit 2: Introduction to Object-Oriented Programming
BC401
Use
Partner
Only
Internal
Figure 83: Calling Static Methods – Syntax
SAP
Like static attributes, static methods are addressed with their class name, since they do not need instances.
Use
Only
Internal
Partner
As with instance methods, when you are calling a static method from within the class, you can omit the classname. Otherwise, the same rules apply here as for calling an instance method.
SAP
Static methods (also referred to as class methods) are called using CALL METHOD classname=>method_name ....
140
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Use
Partner
Only
Internal
Figure 84: Functional Methods
SAP Use
•
• • •
08-03-2004
Logical expressions (IF, ELSEIF, WHILE, CHECK, WAIT) Case conditions (CASE, WHEN) Arithmetic expressions and bit expressions (COMPUTE) Sources of values as a local copy (MOVE) Search clauses for internal tables, assuming that the operand is not a component of the table row (LOOP AT ... WHERE).
© 2004 SAP AG. All rights reserved.
Only
Internal
•
Partner
Functional methods can be called directly within various expressions:
SAP
Methods that have a RETURNING parameter are described as functional methods. This means that they can have neither an EXPORTING nor a CHANGING parameter. The RETURNING parameter must always be passed using the VALUE addition, that is, by value as a local copy.
141
Unit 2: Introduction to Object-Oriented Programming
BC401
Use
Partner
Only
Internal
Figure 85: Functional Methods – Examples
SAP Use
DATA number TYPE i. ...
Internal
CALL METHOD lcl_vehicle=>get_n_o_vehicles
Partner
The second example shows the call of a functional static method in the short form: The NUMBER data object is the actual parameter for the method’s RETURNING parameter. The detailed syntax is as follows:
SAP
In the first of these examples, two calls of functional instance methods represent the two addends of an addition.
RECEIVING re_count = number.
Only
142
© 2004 SAP AG. All rights reserved.
08-03-2004
Lesson: Fundamental Object-Oriented Syntax Elements
Internal
Partner
Only
BC401
You access public attributes from outside a class the same way as method calls: Static attributes are accessed using classname=>static_attribute. Instance attributes are accessed with ref->instance_attribute.
Use
Constructors
SAP
SAP
Figure 86: Accessing Public Attributes
Use
Only
Internal
Partner
There are two types of methods in ABAP Objects. They are generally not called explicitly with CALL METHOD (or the relevant short form), but are called implicitly. Constructors are the first type of method.
08-03-2004
© 2004 SAP AG. All rights reserved.
143
Unit 2: Introduction to Object-Oriented Programming
BC401
Use
Partner
Only
Internal
Figure 87: (Instance) Constructor
SAP
SAP
The constructor is a special instance method in a class and is always named CONSTRUCTOR. This abbreviated term actually means the instance constructor.
Only
Internal
Use
Partner
144
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
The constructor is automatically called at runtime with the CREATE OBJECT statement. Always consider the following points when you define constructors: • • •
Only
•
(The corresponding comments in the SAP Library and the menu paths outside of the ABAP Workbench are only contained in internal system calls.)
Use
Partner
Note: There is no destructor in ABAP Objects. That is, there is no instance method that is automatically called from the memory immediately before the object is deleted.
Internal
•
Each class can have no more than one (instance) constructor The constructor must be defined in the public area The constructor’s signature can only have importing parameters and exceptions When exceptions are raised in the constructor, instances are not created, so no main memory space is occupied Except for one exceptional case, you cannot normally call the constructor explicitly
SAP
SAP Only
Internal
Use
Partner
Figure 88: Constructor – Example
08-03-2004
© 2004 SAP AG. All rights reserved.
145
Unit 2: Introduction to Object-Oriented Programming
BC401
For example, a constructor is necessary when, after the instantiation of a class: • • • •
You need to allocate resources You need to initialize attributes that cannot be covered by the VALUE addition to the DATA statement You need to modify static attributes You need to send messages containing the information that a new object was created
Use
Partner
Only
Internal
Internal
• • • •
146
Creating an instance of this class (CREATE OBJECT) Accessing a static attribute of this class Calling a static method of this class Registering an event handler method for an event in this class
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
The static constructor is a special static method in a class and is always named CLASS_CONSTRUCTOR. It is executed no more than once per program (and class). The static constructor is called automatically before the class is first accessed, but before any of the following actions are executed for the first time:
Partner
Use
SAP
SAP
Figure 89: Example of a Static Constructor
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Always consider the following points when you define static constructors: • • • •
Each class has no more than one static constructor The static constructor must be defined in the public area The constructor’s signature cannot have importing parameters or exceptions The static constructor cannot be called explicitly
Only
Use
Partner
In some cases, you need to have a self-reference available. In ABAP Objects, self-references are always predefined, but they are only useful in certain contexts and only there are they syntactically available.
Internal
Self-Reference
SAP
SAP
You can address an object itself by using the predefined reference variable ME within its instance methods . Generally, you do not need to use the prefix me-> in such cases, but you may use it to improve readability. However, it is required when you want to show a distinction between local data objects and instance attributes with the same name.
08-03-2004
© 2004 SAP AG. All rights reserved.
147
Only
Internal
Use
Partner
Figure 90: Self-Reference
Unit 2: Introduction to Object-Oriented Programming
BC401
The following case shows another important use: When a “foreign” method is called, a client object is to export a reference to itself. ME can then be used as an actual parameter with EXPORTING or CHANGING.
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
148
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Exercise 6: Local Classes Exercise Objectives
Only
Task 1:
You are a developer for an airline corporation that owns several airline carriers. Start to develop an object-oriented program that can manage the airline carriers and their airlines.
Use
Create a new program. 1.
Create an executable program without a TOP include.
SAP
(Where ## is your two-digit group number).
Use
Program name: ZBC401_##_AIRPLANE
Internal
(Where ## is your two-digit group number).
Task 2:
Partner
Create an include program and include it in your ZBC401_##_MAIN main program.
SAP
Program name: ZBC401_##_MAIN
2.
Internal
Business Example
Partner
After completing this exercise, you will be able to: • Declare local classes • Define attributes • Define and implement methods
Declare a class for airplanes.
2.
Within your include program, declare the local class LCL_AIRPLANE. Define the two private instance attributes NAME (name of airplane), data type STRING PLANETYPE (type of airplane), data type SAPLANE-PLANETYPE and the private static attribute N_O_AIRPLANES (instance counter), data type I. Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
149
Only
1.
Unit 2: Introduction to Object-Oriented Programming
3.
BC401
Define the public instance method SET_ATTRIBUTES for setting the private instance attributes. Your signature should consist of two suitable import parameters that are defined compatibly to the two attributes. Implement the method in such a way that the two instance attributes are set. Define the public instance method DISPLAY_ATTRIBUTES for displaying the private instance attributes.
Hint: Use the statement TYPE-POOLS icon. to do this.
SAP
Define the public static method DISPLAY_N_O_AIRPLANES to display the private static attribute.
Note: So far, your class does not have a mechanism that ensures that the instance counter is increased each time an object is created. It is up to you to decide if you want to leave this out for now, of if you want to temporarily control the incrementation using the SET_ATTRIBUTES method.
150
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Implement the method in such a way that the value of the static attributes is output in the ABAP list.
Partner
Use
5.
SAP
Note: Strictly speaking, to adhere to the delegation principle, the reading of the attribute values and their output should not be implemented in the same method. However, do it here anyway because of time constraints.
Use
Partner
Implement the method in such a way that the values of the two instance attributes are output as an ABAP list. You can also output icons if the ICON type group is loaded.
Internal
Only
4.
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Solution 6: Local Classes Task 1: Create a new program. 1.
Create an executable program without a TOP include. Program name: ZBC401_##_MAIN
Only
a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Partner
Model solution: SAPBC401_AIRS_MAIN_A 2.
Create an include program and include it in your ZBC401_##_MAIN main program.
Use
Program name: ZBC401_##_AIRPLANE (Where ## is your two-digit group number). Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_AIRS_A See the source code extract from the model solution
Task 2: Declare a class for airplanes. Within your include program, declare the local class LCL_AIRPLANE. a) 2.
See the source code extract from the model solution
Define the two private instance attributes
Only
Internal
1.
NAME (name of airplane), data type STRING PLANETYPE (type of airplane), data type SAPLANE-PLANETYPE and the private static attribute N_O_AIRPLANES (instance counter), data type I. a)
See the source code extract from the model solution
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
Partner
Use
b)
SAP
SAP
a)
Internal
(Where ## is your two-digit group number).
151
Unit 2: Introduction to Object-Oriented Programming
3.
BC401
Define the public instance method SET_ATTRIBUTES for setting the private instance attributes. Your signature should consist of two suitable import parameters that are defined compatibly to the two attributes. Implement the method in such a way that the two instance attributes are set.
4.
See the source code extract from the model solution
Define the public instance method DISPLAY_ATTRIBUTES for displaying the private instance attributes.
Hint: Use the statement TYPE-POOLS icon. to do this.
SAP Use
Define the public static method DISPLAY_N_O_AIRPLANES to display the private static attribute. Implement the method in such a way that the value of the static attributes is output in the ABAP list. Note: So far, your class does not have a mechanism that ensures that the instance counter is increased each time an object is created. It is up to you to decide if you want to leave this out for now, of if you want to temporarily control the incrementation using the SET_ATTRIBUTES method. a)
See the source code extract from the model solution
Continued on next page
152
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
5.
See the source code extract from the model solution
Partner
a)
SAP
Note: Strictly speaking, to adhere to the delegation principle, the reading of the attribute values and their output should not be implemented in the same method. However, do it here anyway because of time constraints.
Use
Partner
Implement the method in such a way that the values of the two instance attributes are output as an ABAP list. You can also output icons if the ICON type group is loaded.
Internal
Only
a)
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Result Source code extract:
SAPBC401_AIRS_MAIN_A
Only
SAPBC401_AIRS_A
sapbc401_airs_main_a.
Internal
TYPE-POOLS icon.
Partner
REPORT
INCLUDE sapbc401_airs_a.
*&---------------------------------------------------------------------* Include
SAPBC401_AIRS_A
*
Use
*&
*&---------------------------------------------------------------------* *------------------------------------------------------------------* *
CLASS lcl_airplane DEFINITION
*
SAP
SAP
*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
Use
Partner
"-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
METHODS: set_attributes IMPORTING
Internal
im_name
TYPE string
im_planetype TYPE saplane-planetype, display_attributes.
Only
CLASS-METHODS: display_n_o_airplanes.
PRIVATE SECTION. "---------------------------------DATA: name
TYPE string,
planetype TYPE saplane-planetype.
CLASS-DATA: n_o_airplanes TYPE i.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
153
Unit 2: Introduction to Object-Oriented Programming
BC401
"lcl_airplane DEFINITION
ENDCLASS.
*------------------------------------------------------------------* *
CLASS lcl_airplane IMPLEMENTATION
*
*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.
name
= im_name.
planetype
= im_planetype.
*
doesn’t make sense so much -
*
only in order to get an effect
*
after calling display_n_o_airplanes:
Internal
Only
METHOD set_attributes.
Partner
n_o_airplanes = n_o_airplanes + 1. "set_attributes
ENDMETHOD.
Use
METHOD display_attributes. WRITE: / icon_ws_plane AS ICON, / ’Name des Flugzeugs:’(001), AT pos_1 name, / ’Flugzeugtyp’(002), AT pos_1 planetype.
SAP
SAP
"display_attributes
ENDMETHOD.
METHOD display_n_o_airplanes. WRITE: /, / ’Gesamtzahl der Flugzeuge’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
Use
"display_n_o_airplanes "lcl_airplane IMPLEMENTATION
Only
Internal
ENDCLASS.
Partner
ENDMETHOD.
154
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Exercise 7: Objects Exercise Objectives
Business Example
Task 1: Define reference variables. 1.
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise.
SAP
Define an internal table for buffering references to instances of the class LCL_AIRPLANE.
Task 2:
08-03-2004
1.
Create several instances of the local class LCL_AIRPLANE and buffer their references into the internal table.
2.
Follow the execution of the program in the ABAP Debugger.
© 2004 SAP AG. All rights reserved.
Only
Internal
Create airplane objects.
Partner
Use
2.
SAP
Define a reference variable for the instances of your class LCL_AIRPLANE.
Use
Partner
Create instances of your airplane type and ensure that their addresses are not lost.
Internal
Only
After completing this exercise, you will be able to: • Define reference variables • Instantiate objects • Process object references using an internal table
155
Unit 2: Introduction to Object-Oriented Programming
BC401
Solution 7: Objects Task 1: Define reference variables. 1.
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise.
Only
a) b)
Define an internal table for buffering references to instances of the class LCL_AIRPLANE. a)
See the source code extract from the model solution
Use
Partner
2.
Model solution: SAPBC401_AIRS_MAIN_B See the source code extract from the model solution
Task 2: Create airplane objects.
SAP
Create several instances of the local class LCL_AIRPLANE and buffer their references into the internal table. a)
See the source code extract from the model solution
SAP
1.
Internal
Define a reference variable for the instances of your class LCL_AIRPLANE.
Only
Internal
Use
Partner
Continued on next page
156
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
2.
Follow the execution of the program in the ABAP Debugger. a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Result Source code extract:
Only
REPORT
Internal
SAPBC401_AIRS_MAIN_B sapbc401_airs_main_b.
Partner
TYPE-POOLS icon. INCLUDE sapbc401_airs_a.
Use
DATA: r_plane TYPE REF TO lcl_airplane,
SAP
SAP
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION. *##############################
Partner
Use
CREATE OBJECT r_plane. APPEND r_plane TO plane_list.
CREATE OBJECT r_plane.
Internal
APPEND r_plane TO plane_list.
CREATE OBJECT r_plane.
08-03-2004
© 2004 SAP AG. All rights reserved.
Only
APPEND r_plane TO plane_list.
157
Unit 2: Introduction to Object-Oriented Programming
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
158
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Exercise 8: Method Calls Exercise Objectives
Business Example
Task 1: Call the methods of your class. 1.
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise.
SAP Use Internal
Use the SET_ATTRIBUTES method to set the attributes for all objects already created. Choose a unique name for the airplanes. When you are assigning airplane types, use the information in the SAPLANE table as a guide (for example, ’747-400’). Also use at least one invalid airplane type.
3.
Display the attribute values in the ABAP list using the DISPLAY_ATTRIBUTES method.
Only
2.
Task 2: Add a functional method to your class. 1.
In your class, define the public static functional method GET_N_O_AIRPLANES. The signature must only consist of the result parameter RE_COUNT, which must be a whole number. Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
Partner
Caution: For reasons explained in the first exercise, you may not notice any effects at the moment.
SAP
Call the static method DISPLAY_N_O_AIRPLANES twice: Once before and once after the instantiations.
Use
Partner
You need to fill the attributes of the “empty” airplane objects with suitable values.
Internal
Only
After completing this exercise, you will be able to: • Call non-functional methods • Define functional methods • Call functional methods:
159
Unit 2: Introduction to Object-Oriented Programming
2.
BC401
Call this method instead of DISPLAY_N_O_AIRPLANES and output the value to the ABAP list. Note: This means that you have followed the delegation principle.
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
160
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Solution 8: Method Calls Task 1: Call the methods of your class. 1.
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise.
Only
a) b)
Use the SET_ATTRIBUTES method to set the attributes for all objects already created. Choose a unique name for the airplanes. When you are assigning airplane types, use the information in the SAPLANE table as a guide (for example, ’747-400’). Also use at least one invalid airplane type. a)
Display the attribute values in the ABAP list using the DISPLAY_ATTRIBUTES method. a)
Partner
Use
3.
See the source code extract from the model solution
See the source code extract from the model solution
Add a functional method to your class. In your class, define the public static functional method GET_N_O_AIRPLANES. The signature must only consist of the result parameter RE_COUNT, which must be a whole number. a) 2.
See the source code extract from the model solution
Call this method instead of DISPLAY_N_O_AIRPLANES and output the value to the ABAP list. Note: This means that you have followed the delegation principle. a)
See the source code extract from the model solution Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
161
Only
Internal
Task 2: 1.
SAP
SAP
2.
Model solution: SAPBC401_AIRS_MAIN_C See the source code extract from the model solution
Use
Partner
Caution: For reasons explained in the first exercise, you may not notice any effects at the moment.
Internal
Call the static method DISPLAY_N_O_AIRPLANES twice: Once before and once after the instantiations.
Unit 2: Introduction to Object-Oriented Programming
BC401
Result Source code extract:
SAPBC401_AIRS_MAIN_C REPORT
sapbc401_airs_main_c.
Internal
Only
TYPE-POOLS icon.
INCLUDE sapbc401_airs_c. DATA: r_plane TYPE REF TO lcl_airplane, plane_list TYPE TABLE OF REF TO lcl_airplane,
Use
Partner
count TYPE i.
START-OF-SELECTION.
SAP
SAP
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_plane.
Use
Partner
APPEND r_plane TO plane_list. r_plane->set_attributes( im_name = ’LH Berlin’ im_planetype = ’A321’ ).
Internal
CREATE OBJECT r_plane. APPEND r_plane TO plane_list. r_plane->set_attributes( im_name = ’AA New York’ im_planetype = ’747-400’ ).
Only
CREATE OBJECT r_plane. APPEND r_plane TO plane_list. r_plane->set_attributes( im_name = ’US Hercules’ im_planetype = ’747-500’ ).
LOOP AT plane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP.
Continued on next page
162
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
* long syntax for functional call: * CALL METHOD lcl_airplane=>get_n_o_airplanes * *
RECEIVING re_count = count.
* a little bit shorter:
Internal
Only
* lcl_airplane=>get_n_o_airplanes( RECEIVING re_count = count ). * the shortest syntax for functional call: count = lcl_airplane=>get_n_o_airplanes( ).
SKIP 2.
Partner
WRITE: / ’Gesamtzahl der Flugzeuge’(ca1), count.
Use
SAPBC401_AIRS_C *&
Include
*&
Show functional static method get_n_o_airplanes
SAPBC401_AIRS_C
* *
SAP
SAP
*&---------------------------------------------------------------------*
*&---------------------------------------------------------------------* *------------------------------------------------------------------* *
CLASS lcl_airplane DEFINITION
*
*------------------------------------------------------------------*
Partner
Use
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION. "--------------------------------
Internal
CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: set_attributes IMPORTING TYPE string
Only
im_name
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,
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
163
Unit 2: Introduction to Object-Oriented Programming
BC401
planetype TYPE saplane-planetype. CLASS-DATA: n_o_airplanes TYPE i.
ENDCLASS.
"lcl_airplane DEFINITION
*------------------------------------------------------------------* *
CLASS lcl_airplane IMPLEMENTATION
*
Internal
Only
*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.
Partner
METHOD set_attributes. name
= im_name.
planetype
= im_planetype.
n_o_airplanes = n_o_airplanes + 1. ENDMETHOD.
"set_attributes
Use
METHOD display_attributes. WRITE: / icon_ws_plane AS ICON, / ’Name des Flugzeugs:’(001), AT pos_1 name,
SAP
ENDMETHOD.
SAP
/ ’Flugzeugtyp’(002), AT pos_1 planetype. "display_attributes
METHOD display_n_o_airplanes. WRITE: /, / ’Gesamtzahl der Flugzeuge’(ca1),
Partner
Use
AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. ENDMETHOD.
"display_n_o_airplanes
METHOD get_n_o_airplanes.
ENDCLASS.
164
"get_n_o_airplanes
Only
Internal
re_count = n_o_airplanes. ENDMETHOD.
"lcl_airplane IMPLEMENTATION
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Exercise 9: Constructors Exercise Objectives
Only
Task 1:
Make your program more realistic: The airplane objects receive their attributes as soon as they are created.
Internal
Business Example
Partner
After completing this exercise, you will be able to: • Define and implement instance constructors • Create instances of classes that contain an instance constructor
Define an instance constructor. Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. (Where ## is your two-digit group number).
SAP
Implement it so that the two instance attributes are set and the instance counter N_O_AIRPLANES is increased by one.
Use
If you previously used the SET_ATTRIBUTES method to increase the instance counter, remove the relevant statement from the method now.
Task 2:
08-03-2004
1.
Your CREATE OBJECT statements from the previous exercise should now be syntactically incorrect. Adapt and correct them.
2.
If necessary, remove the calls of the SET_ATTRIBUTES method.
3.
Follow the execution of the program in the ABAP Debugger.
© 2004 SAP AG. All rights reserved.
165
Only
Internal
Create airplane objects.
Partner
2.
SAP
Define a reference variable with a suitable signature for the instances of your class LCL_AIRPLANE.
Use
1.
Unit 2: Introduction to Object-Oriented Programming
BC401
Solution 9: Constructors Task 1: Define an instance constructor. 1.
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. (Where ## is your two-digit group number).
Only
Implement it so that the two instance attributes are set and the instance counter N_O_AIRPLANES is increased by one.
2.
Model solution: SAPBC401_AIRS_MAIN_D See the source code extract from the model solution
If you previously used the SET_ATTRIBUTES method to increase the instance counter, remove the relevant statement from the method now. a)
See the source code extract from the model solution
SAP
Create airplane objects. Your CREATE OBJECT statements from the previous exercise should now be syntactically incorrect. Adapt and correct them. a) 2.
If necessary, remove the calls of the SET_ATTRIBUTES method. See the source code extract from the model solution
Follow the execution of the program in the ABAP Debugger. a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Result Source code extract:
SAPBC401_AIRS_MAIN_D REPORT
sapbc401_airs_main_d.
Continued on next page
166
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
a) 3.
See the source code extract from the model solution
Partner
Use
1.
SAP
Task 2:
Use
Partner
a) b)
Internal
Define a reference variable with a suitable signature for the instances of your class LCL_AIRPLANE.
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
TYPE-POOLS icon. INCLUDE sapbc401_airs_d.
DATA: r_plane TYPE REF TO lcl_airplane,
Internal
Only
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION. *##############################
Partner
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_plane EXPORTING im_name = ’LH Berlin’
Use
im_planetype = ’A321’. APPEND r_plane TO plane_list.
SAP
SAP
r_plane->display_attributes( ).
CREATE OBJECT r_plane EXPORTING im_name = ’AA New York’ im_planetype = ’747-400’.
Partner
Use
APPEND r_plane TO plane_list. r_plane->display_attributes( ).
CREATE OBJECT r_plane EXPORTING im_name = ’US Hercules’
Internal
im_planetype = ’747-500’. APPEND r_plane TO plane_list.
Only
r_plane->display_attributes( ).
lcl_airplane=>display_n_o_airplanes( ).
SAPBC401_AIRS_D *&---------------------------------------------------------------------* *&
Include
SAPBC401_AIRS_D
*
*&---------------------------------------------------------------------*
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
167
Unit 2: Introduction to Object-Oriented Programming
BC401
*------------------------------------------------------------------* *
CLASS lcl_airplane DEFINITION
*
*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION. PUBLIC SECTION. "-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
im_name
Internal
Only
METHODS: constructor IMPORTING TYPE string
im_planetype TYPE saplane-planetype, display_attributes.
Partner
CLASS-METHODS: display_n_o_airplanes. PRIVATE SECTION. DATA: name
Use
"---------------------------------TYPE string,
planetype TYPE saplane-planetype.
SAP
ENDCLASS.
SAP
CLASS-DATA: n_o_airplanes TYPE i. "lcl_airplane DEFINITION
*------------------------------------------------------------------* *
CLASS lcl_airplane IMPLEMENTATION
*
Partner
Use
*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.
Internal
METHOD constructor. name
= im_name.
planetype
= im_planetype.
n_o_airplanes = n_o_airplanes + 1. "constructor
ENDMETHOD.
Only
METHOD display_attributes. WRITE: / icon_ws_plane AS ICON, / ’Name des Flugzeugs’(001), AT pos_1 name, / ’Type of airplane: ’(002), AT pos_1 planetype. ENDMETHOD.
"display_attributes
METHOD display_n_o_airplanes. WRITE: /, / ’Number of airplanes: ’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
Continued on next page
168
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
ENDMETHOD. ENDCLASS.
"display_n_o_airplanes "lcl_airplane IMPLEMENTATION
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
169
Unit 2: Introduction to Object-Oriented Programming
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
170
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Exercise 10: Private Methods Exercise Objectives
Only
Declare another method. 1.
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise.
SAP Use
Implement the method in such a way that the values for the export parameters can be determined by single-record access to the database table SAPLANE. If no values for that airplane type exist in that table, the following standard values should be used for the time being: Weight: 100,000, tank capacity: 10,000 Note: Strictly speaking, the correct unit of measurements should also be selected and exported. However, time constrains mean that you do not need to do it in this exercise.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
171
Only
Internal
2.
Partner
The signature must consist of an import parameter for the airplane type and two export parameters for the weight and the tank capacity. Use the transparent table SAPLANE as a guide for specifying the types of these formal parameters.
SAP
Within the class LCL_AIRPLANE, define the private instance method GET_TECHNICAL_ATTRIBUTES.
Use
Task 1:
An airplane object should be able to display additional technical data on request, so that a complete business application object is displayed for the user.
Internal
Business Example
Partner
After completing this exercise, you will be able to: • Use the delegation principle • Realize business application objects based on database contents
Unit 2: Introduction to Object-Oriented Programming
BC401
Task 2: The method DISPLAY_ATTRIBUTES should only be responsible for displaying the data. Call your method again to delegate the retrieval of the technical data.
2.
Follow the execution of the program in the ABAP Debugger.
3.
Are there any alternative solutions that fulfill the same purpose, but still adhere to the delegation principle? What are they?
Use
Partner
1.
Internal
Only
Call the method.
SAP
SAP Only
Internal
Use
Partner
172
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Solution 10: Private Methods Task 1: Declare another method. 1.
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise.
Only
a) b) 2.
Model solution: SAPBC401_AIRS_MAIN_E See the source code extract from the model solution
Implement the method in such a way that the values for the export parameters can be determined by single-record access to the database table SAPLANE.
SAP
SAP
If no values for that airplane type exist in that table, the following standard values should be used for the time being:
See the source code extract from the model solution
Task 2: Call the method. 1.
The method DISPLAY_ATTRIBUTES should only be responsible for displaying the data. Call your method again to delegate the retrieval of the technical data. a)
See the source code extract from the model solution
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
173
Only
Internal
Note: Strictly speaking, the correct unit of measurements should also be selected and exported. However, time constrains mean that you do not need to do it in this exercise.
Partner
Use
Weight: 100,000, tank capacity: 10,000
a)
Use
Partner
The signature must consist of an import parameter for the airplane type and two export parameters for the weight and the tank capacity. Use the transparent table SAPLANE as a guide for specifying the types of these formal parameters.
Internal
Within the class LCL_AIRPLANE, define the private instance method GET_TECHNICAL_ATTRIBUTES.
Unit 2: Introduction to Object-Oriented Programming
2.
Follow the execution of the program in the ABAP Debugger. a)
3.
BC401
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Are there any alternative solutions that fulfill the same purpose, but still adhere to the delegation principle? What are they? Answer:
Only
Not using the import parameter GET_TECHNICAL_ATTRIBUTES is an instance method. Therefore, during single-record access, the private attribute for the airplane type could be used in the WHERE clause. Private static method while preserving the signature This way the method could be seen as a central “data retrieval service” for all instances of the class.
•
Not using the method at all Instead, you could use other suitable private attributes, which the constructor could fill with values from the database table.
SAP
SAPBC401_AIRS_E
Source code extract:
*&---------------------------------------------------------------------* Include
SAPBC401_AIRS_E
*
Internal
*&---------------------------------------------------------------------* *------------------------------------------------------------------* *
CLASS lcl_airplane DEFINITION
*
Only
*------------------------------------------------------------------* 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,
Continued on next page
174
© 2004 SAP AG. All rights reserved.
Partner
Use
SAP
Result
*&
Use
Partner
•
Internal
•
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
display_attributes. CLASS-METHODS: display_n_o_airplanes.
PRIVATE SECTION. "----------------------------------
IMPORTING im_type
TYPE saplane-planetype
EXPORTING ex_weight
TYPE s_plan_wei
ex_tankcap
DATA: name
Internal
Only
METHODS: get_technical_attributes
TYPE s_capacity.
TYPE string,
Partner
planetype TYPE saplane-planetype. CLASS-DATA: n_o_airplanes TYPE i.
"lcl_airplane DEFINITION
Use
ENDCLASS.
*------------------------------------------------------------------* *
CLASS lcl_airplane IMPLEMENTATION
*
SAP
SAP
*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.
name
= im_name.
planetype
= im_planetype.
Partner
Use
METHOD constructor.
n_o_airplanes = n_o_airplanes + 1. ENDMETHOD.
"constructor
Internal
METHOD display_attributes. DATA: weight TYPE saplane-weight, cap TYPE saplane-tankcap.
Only
WRITE: / icon_ws_plane AS ICON, / ’Name des Flugzeugs’(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: / ’Wheight: ’(003), 20 weight, ’Tankcap: ’(004), 60 cap. ENDMETHOD.
"display_attributes
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
175
Unit 2: Introduction to Object-Oriented Programming
BC401
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)
Internal
Only
WHERE planetype = im_type. IF sy-subrc <> 0. ex_weight = 100000. ex_tankcap = 10000. ENDIF.
Partner
ENDMETHOD.
ENDCLASS.
"get_technical_attributes "lcl_airplane IMPLEMENTATION
Use
SAP
SAP Only
Internal
Use
Partner
176
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Fundamental Object-Oriented Syntax Elements
Lesson Summary You should now be able to: • Define classes • Generate and delete objects • Access attributes • Call methods
Only
Use
Partner
... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.
Internal
Related Information
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
177
Unit Summary
BC401
Unit Summary
Only
Use
Partner
Internal
You should now be able to: • Explain the differences between procedural and object-oriented programming models • List the advantages of the object-oriented programming model • Name the most important diagram types in UML • Create class diagrams • Create sequence diagrams • Define classes • Generate and delete objects • Access attributes • Call methods
SAP
SAP Only
Internal
Use
Partner
178
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Test Your Knowledge
Test Your Knowledge 1.
The object-oriented programming model was developed considerably later than the procedural one. It offers more possibilities to solve problems that previously could not be solved with purely procedural programming languages. Determine whether this statement is true or false.
Only
3.
What does encapsulation mean?
4.
In ABAP Objects, what is meant by the term class?
5.
What is the difference between a class’s static components and its instance components?
© 2004 SAP AG. All rights reserved.
Internal
Only
08-03-2004
Partner
Use
SAP
SAP
What does multiple instantiation mean?
Use
2.
Partner
True False
Internal
□ □
179
Test Your Knowledge
BC401
6.
In ABAP Objects, what is meant by the term constructor?
7.
You are defining a class. Must you always also define a constructor?
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
180
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Test Your Knowledge
Answers 1.
The object-oriented programming model was developed considerably later than the procedural one. It offers more possibilities to solve problems that previously could not be solved with purely procedural programming languages.
Internal
Only
Answer: False Refer to the relevant section of the lesson. 2.
What does multiple instantiation mean?
Partner
Answer: The ability to create and manage any number of runtime instances for each program context
3.
Use
Refer to the relevant section of the lesson. What does encapsulation mean?
SAP
Refer to the relevant section of the lesson.
Use
In ABAP Objects, what is meant by the term class?
Internal
Answer: A class is the technical description of identical objects. Among other things, it can contain attribute and method definitions. It usually also contains the methods’ implementations. Refer to the relevant section of the lesson.
Partner
4.
SAP
Answer: Gathering data and functions into reusable units from which users can only call certain functions and cannot access the data directly.
Only
08-03-2004
© 2004 SAP AG. All rights reserved.
181
Test Your Knowledge
5.
BC401
What is the difference between a class’s static components and its instance components?
Only
Refer to the relevant section of the lesson. In ABAP Objects, what is meant by the term constructor? Answer: A class’s constructor is a special method and is always named CONSTRUCTOR. It is normally only called by the runtime system, whenever an object of this class is created using CREATE OBJECT. Therefore, it is referred to more specifically as the instance constructor. Refer to the relevant section of the lesson.
SAP
You are defining a class. Must you always also define a constructor? Answer: No
Only
Internal
Use
Partner
Refer to the relevant section of the lesson.
SAP
7.
Use
Partner
6.
Internal
Answer: You have to access static components through the class. That means they can exist only once per program and class in the memory. An object must be instantiated to access them. You have to access instance components through the objects of the class. That means, they can exist any number of times per program and class in the memory.
182
© 2004 SAP AG. All rights reserved.
08-03-2004
Unit 3 Only
Unit Overview
Partner SAP
Unit Objectives
Use Internal
08-03-2004
Define inheritance relationships between classes Redefine methods Create narrowing cast assignments Create widening cast assignments Explain the concept of polymorphism with reference to interfaces Use cast assignments with inheritance to make generic calls Define and implement interfaces Implement interface methods Use interface references to make narrowing cast assignments Use interface references to make widening cast assignments Explain the term polymorphism with reference to interfaces Use cast assignments with interfaces to make generic calls Define and trigger events Handle events
© 2004 SAP AG. All rights reserved.
Only
• • • • • • • • • • • • • •
Partner
After completing this unit, you will be able to:
SAP
Every concept exists for a specific reason. It is important that you understand them all without exception so that you can use each of them effectively later on. You can only capitalize on the strengths of object-oriented programming if you use all of the concepts in the intended manner.
Use
This unit deals with the basic programming techniques common to all object-oriented languages. As far as these concepts are concerned, the only difference between ABAP Objects and other languages like Java or C++ is the syntax.
Internal
Object-Oriented Concepts and Programming Techniques
183
Unit 3: Object-Oriented Concepts and Programming Techniques
• •
BC401
Register and deregister event handling Explain the key differences between explicit method calls and event-controlled method calls
Unit Contents
Only
Use
Partner
Internal
Lesson: Inheritance and Casting ................................................. 185 Exercise 11: Class Hierarchies ............................................... 205 Exercise 12: Polymorphism ................................................... 215 Exercise 13: Aggregation and Generic Calls ............................... 219 Lesson: Interfaces and Casting ................................................... 226 Exercise 14: Interface Implementation ...................................... 241 Exercise 15: Aggregation, Generic Calls, and Polymorphism ............ 255 Lesson: Events...................................................................... 263 Exercise 16: Events in Superclasses ........................................ 273 Exercise 17: Events in Interfaces (optional) ................................ 287
SAP
SAP Only
Internal
Use
Partner
184
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
Lesson: Inheritance and Casting Lesson Overview
Internal
Only
In this lesson you will learn how to create class hierarchies using ABAP Objects. The first step will be to program the relevant relationship types that were devised in the modeling process. Then you will learn to identify a number of advantageous programming possibilities that inheritance provides.
Lesson Objectives After completing this lesson, you will be able to:
Partner SAP Internal
08-03-2004
© 2004 SAP AG. All rights reserved.
185
Only
Specialization (UML) 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 the implementations with inherited methods. In the latter case, the method name in the UML diagram is renamed within the subclass.
Partner
Realization of Generalization/Specialization Relationships Using Iheritance
You want to implement generalization/specialization relationships from your model in ABAP Objects.
SAP
Business Example
Use
Define inheritance relationships between classes Redefine methods Create narrowing cast assignments Create widening cast assignments Explain the concept of polymorphism with reference to interfaces Use cast assignments with inheritance to make generic calls
Use
• • • • • •
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
SAP Use
Only
Internal
Reversing the point of view is referred to as generalization.
Partner
Specialization is often described as an “is a” relationship. In this example, you would say: “A truck is a (specific) vehicle.”
SAP
Inheritance is an implementation relationship that emphasizes similarities of the classes. In the example above, the similarities of classes LCL_CAR, LCL_TRUCK, and LCL_BUS are extracted to a superclass, LCL_VEHICLE. Therefore, the components they have in common are only defined and implemented in the superclass. They also exist in all subclasses.
Use
Partner
Only
Internal
Figure 91: Example of Generalization/Specialization
186
© 2004 SAP AG. All rights reserved.
08-03-2004
Lesson: Inheritance and Casting
Internal
Figure 92: Characteristics of Generalization/Specialization
SAP Use Internal
08-03-2004
© 2004 SAP AG. All rights reserved.
187
Only
When you develop additional subclasses, you often have to adapt the superclass, too. Sometimes the creation of a subclass leads to additional requirements for the superclass, for example, when a subclass requires certain protected components or when the details of a superclass’s implementation are required to change the method implementations in subclasses. The developer of a (super)class cannot normally predict everything that the subclasses will later require from the superclass.
Partner
You need exact knowledge of the implementation of the superclass to decide whether the inherited components from the superclass are sufficient for the subclass or if they need to be extended. Generalization/specialization therefore provides very strong links between the superclass and the subclass.
SAP
If generalization/specialization is used properly, it provides a significantly better structure for your software, as common components only need to be stored once centrally (in the superclass). That is, subsequent changes are then automatically applied to subclasses. Therefore, you must not alter the semantics when you change a superclass.
Use
Partner
Only
BC401
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Partner
Only
Internal
Figure 93: Inheritance – Syntax
© 2004 SAP AG. All rights reserved.
08-03-2004
SAP Use Internal
Only
188
Partner
Inheritance is a “one-sided relationship”: subclasses know their direct superclasses, but (super)classes do not know their subclasses. In this example, the subclass also contains the ESTIMATE_FUEL method. The subclass also defines the GET_CARGO method.
SAP
Inheritance should be used to implement generalization and specialization relationships. A superclass is a generalization of its subclasses. The subclasses are in turn different specializations of their superclass. Only additions or changes are permitted in ABAP Objects, that is, in a subclass you can „never take something away from a superclass".
Use
In ABAP Objects, an inheritance relationship is defined for a subclass using the INHERITING FROM addition, followed by the superclass that is directly above the subclass. Inheritance hierarchies of varying complexity arise when this superclass inherits from another superclass above it. On the other hand, there is no multiple inheritance in ABAP Objects. That is, only one superclass can be specified directly above a class. However, you can use interfaces in ABAP Objects to simulate multiple inheritance.
BC401
Lesson: Inheritance and Casting
SAP Use Internal
08-03-2004
© 2004 SAP AG. All rights reserved.
189
Only
Within the redefined method’s implementation part, you can use the predefined prefix super->... to access components in the superclass directly above where you are working. You often need to do this when redefining a method to call the original method of the superclass.
Partner
When you use the REDEFINITION addition, you must specify a (new) implementation part for the inherited method. As the signature may not be changed, you do not need to define the method parameters and exceptions again.
SAP
Redefinition is when the implementation of an inherited instance method is changed for the subclass, without changing the signature. At the same time, the visibility section for the superclass must remain the same. (Therefore, redefinition is not possible without the PRIVATE SECTION.)
Use
Partner
Only
Internal
Figure 94: Redefining Methods
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Partner
Only
Internal
Figure 95: Preserving Semantics During Redefinition
Use
In this example, both redefined methods calculate the return code in different ways. The important point is that the method’s semantics stay the same.
SAP
SAP Only
Internal
Use
Partner
Figure 96: “Overloading” of the Constructor
Generally, redefining by the constructor would not be useful. Either the superclass’s constructor can be used without any need to change it or the subclass has been expanded and other parameters are now required in
190
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
the constructor’s signature. Therefore, in ABAP Objects inheritance, the constructor can only be “overloaded,” in the sense that both the signature and the implementation part can be adapted.
Only
Use
Partner
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.
Internal
The constructor of the superclass must be called within the constructor of the subclass. This is because of the specialization relationship: If a constructor was defined in the superclass, it contains implementations that will always be executed when an object is created in this superclass or its subclasses. However, only if the subclass’s constructor was not overloaded, can the runtime system ensure this automatically. In most cases, supplying consistent private attributes from the superclass is another prerequisite for calling the superclass constructor.
SAP
SAP Only
Internal
Use
Partner
Figure 97: Rules for Calling the Constructor
If a subclass has not overloaded its instance constructor, the constructor is left unchanged and is adopted by the superclass. Therefore, the implementation is executed from the superclass.
08-03-2004
© 2004 SAP AG. All rights reserved.
191
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
SAP Use
Only
Internal
Partner
When defining local classes in ABAP Objects, you must follow the syntactical sequence of PUBLIC SECTION, PROTECTED SECTION, PRIVATE SECTION.
SAP
Inheritance provides an extension of the visibility concept: There are protected components (PROTECTED SECTION). The visibility of these components is a “grey area” between public and private. Protected components are visible to all subclasses and the class itself.
Use
Partner
Only
Internal
Figure 98: Inheritance and Visibility
192
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
Use
Partner
Only
Internal
Figure 99: Protected vs. Private Section
Using the private visibility section, you can change superclasses without the need to know the subclasses. As long as the changes you make do not affect the sematics, you do not need to adapt the subclasses. This is because they only indirectly access the private components from the superclass.
Only
SAP Use
Partner
Internal
In this example, it is possible to access the protected attribute TANK in superclass LCL_VEHICLE directly from its subclass LCL_BUS. On the other hand, the only way to access the MAKE and MODEL attributes from the subclasses of LCL_VEHICLE is to use public methods.
There is only one static component per program context. To summarize:
08-03-2004
SAP
The fact that all components of a superclass are available to the subclass is not related to the component’s visibility. A subclass also receives the private components of its superclass. However, these cannot be addressed in the syntax of the subclass. Private components in superclasses can only be addressed indirectly, that is through public or protected methods from the superclass that can access private attributes. These restrictions are necessary to ensure that centralized maintenance is possible.
© 2004 SAP AG. All rights reserved.
193
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Static Components and Inheritance • •
A class that defines a public or protected static attribute shares this attribute with all its subclasses Static methods cannot be redefined
narrowing cast
Only
Use
Partner
Internal
Variables of the type “reference to superclass” can also refer to subclass instances at runtime.
Internal
The user can therefore address the subclass instance in the same way as the superclass instance. However, it is restricted to using only the inherited components. In this example, after the assignment, the methods GET_MAKE, GET_COUNT, DISPLAY_ATTRIBUTES, SET_ATTRIBUTES and ESTIMATE_FUEL of the instance LCL_TRUCK can only be accessed using the reference R_VEHICLE.
194
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
If you assign a subclass reference to a superclass reference, this ensures that all components that can be accessed syntactically after the cast assignment are actually available in the instance. The subclass always contains at least the same components as the superclass. After all, the name and the signature of redefined methods are identical.
Partner
Use
SAP
SAP
Figure 100: Narrowing Cast With Object References
BC401
Lesson: Inheritance and Casting
If there are any restrictions regarding visibility, they are left unchanged. It is not possible to access the specific components from the class LCL_TRUCK of the instance (GET_CARGO in the above example) using the reference R_VEHICLE. The view is thus generally narrowed (at least unchanged). That is why we describe this type of assignment of reference variables as narrowing cast. There is a switch from a view of several components to a view of a few components. The term upcast is also common.
Use
Partner
Only
Internal
SAP
SAP
Use
object_id<\PROGRAM=program_name\CLASS=dynamic_type>
In the example, LCL_VEHICLE is the static type of the variable R_VEHICLE. Depending on the cast assignment, the dynamic type is either LCL_BUS or LCL_TRUCK. In the ABAP Debugger, the dynamic type is shown in form of the object display
Only
Assignments between reference variables are possible whenever the static type of the target variables is more general or equal to the dynamic type of the source variables.
08-03-2004
© 2004 SAP AG. All rights reserved.
Partner
A reference variable always has two types at runtime: static and dynamic.
Internal
Figure 101: Static and Dynamic Types of References
195
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
SAP Use
Only
Internal
Partner
In the example shown here, a travel agency (LCL_RENTAL) needs to manage all imaginable kinds of vehicles in one list. This leads to the question of what type should be assigned to the internal table for the references to airplaine instances. You should also assume that the car rental company needs to be able to calculate only the required amount of fuel for all its vehicles. Correspondingly, the ESTIMATE_FUEL method is defined in the superclass LCL_VEHICLE and is redefined in all subclasses.
SAP
A typical use for narrowing cast assignments is to prepare for generic access: A user, who is not at all interested in the finer points of the instances of the subclasses but who simply wants to address the shared components, could use a superclass reference for this access.
Use
Partner
Only
Internal
Figure 102: Generic Access After Narrowing Cast Assignments
196
© 2004 SAP AG. All rights reserved.
08-03-2004
Lesson: Inheritance and Casting
Internal
Figure 103: Line Type of the Internal Table in the Applied Example
SAP
SAP
When objects of different classes (LCL_BUS, LCL_TRUCK, and LCL_CAR in the above example) are specified as type superclass references (LCL_VEHICLE in the above), they can be stored in an internal table. The shared components of the subclass objects can then be accessed uniformly. For this example, the method ADD_VEHICLE is therefore needed. This copies the references to the vehicle types in this internal table. Its import parameter is already typed as the reference to the superclass.
Use
Partner
Only
BC401
Only
Internal
Use
Partner
Figure 104: Narrowing Cast and Generic Access in the Applied Example
08-03-2004
© 2004 SAP AG. All rights reserved.
197
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
In this example, the narrowing cast assignment occurs when the vehicle reference is transfered to the formal parameter of the ADD_VEHICLE method. The shared component is generically accessed within the loop around the internal table containing all of the vehicle references: The ESTIMATE_FUEL method was inherited from the LCL_VEHICLE superclass and may have been redefined.
Use
Partner
Only
Internal
SAP
SAP
Use Internal
When an instance receives a message to execute a particular method, the method that implemented the class of this instance is executed. If the class has not been redefined in the method, the implementation from the superclass is executed.
198
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Which implementation is executed when ESTIMATE_FUEL is called now depends on which object the superclass reference R_VEHICLE currently refers to. The dynamic type and not the static type of the reference variable is used to search for the implementation of a method. Therefore, when r_vehicle->estimate_fuel is called, the implementation is not executed from LCL_VEHICLE (static type of R_VEHICLE) because the method was redefined in all vehicle classes.
Partner
Figure 105: Polymorphism – Generic Access Using the Superclass Reference
BC401
Lesson: Inheritance and Casting
When objects from different classes react differently to the same method calls, this is known as polymorphism. The possibility of polymorphism is one of the main strengths of inheritance: A client can handle different classes uniformly, irrespective of their implementation. The runtime system searches for the right implementation of a method on behalf of the client.
Only
Use
Partner
Internal
Polymorphism can be used to write programs that are highly generic, that is, they do not need to be changed significantly if use cases are added. For instance, this would make it very easy to add motor bikes to this example: You would simply have to define a new subclass of LCL_VEHICLE, which you could call LCL_MOTORBIKE. You would also have to redefine the inherited method ESTIMATE_FUEL. Without needing any more changes, your vehicle management system could then work with motorbikes as well and calculate the required fuel levels for them.
SAP
SAP
Using dynamic function modules, you can program generically in ABAP Objects, even without an object-oriented programming model. Compared with polymorphism through inheritance, this means that the source code is less self-explanatory and is more succeptible to errors. For example, the syntax check can only check that the function model is called correctly but not if the internal table contains a valid function module name for each vehicle.
08-03-2004
© 2004 SAP AG. All rights reserved.
199
Only
Internal
Use
Partner
Figure 106: Generic Calls in the Procedural Programming Model
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Widening Cast Variables of the type “reference to superclass” can also refer to subclass instances at runtime. You may now want to copy such a reference (back) onto a suitable variable of the type “reference to subclass”.
After assigning this type of reference (back) to a subclass reference to the implementing class, clients are no longer limited to inherited components: In the example given here, all components of the LCL_TRUCK instance can be accessed (again) after the assignment using reference R_TRUCK2.
Only
Use
Partner
Internal
If you want to assign a superclass reference to a subclass reference, you must use the widening cast assignment operator MOVE ... ?TO ... or its short form ?= . Otherwise, you would get a message stating that it is not certain that all components that can be accessed syntactically after the cast assignment are actually available in the instance. As a rule, the subclass class contains more components than the superclass.
The view is thus widened (at least unchanged). That is why we describe this type of assignment of reference variables as widening cast. There is a switch from a view of a few components to a view of more components. The term downcast is also common.
200
SAP
SAP
Use
Partner
Only
Internal
Figure 107: Widening Cast With Object References
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
Use
Partner
Only
Internal
Use
In this example, a car rental company (LCL_RENTAL) wants to determine the maximum capacity of its trucks, but it stores all types of vehicle references in an internal table that is typed as LCL_VEHICLE. Therefore, what happens if there is no truck reference in the superclass reference R_VEHICLE at runtime but the widening cast assignment operator tries to copy the reference to the now invalid reference R_TRUCK?
Partner Only
Internal
A typical use for widening cast assignments is when specific components of instances need to be addressed and their references are kept in variables that are typed on the superclass. A user who is interested in the finer points of the instances of a subclass cannot use the superclass reference for this access because it only allows access to the shared components.
SAP
SAP
Figure 108: Specific Access After Widening Cast Assignments
08-03-2004
© 2004 SAP AG. All rights reserved.
201
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
SAP Use Internal
This final section does not examine whether or not inheritance should be used as a programming technique over a number of alternatives. As early as the modeling phase, you should be able to see if there is a generalization/specialization relationship between certain classes. If there is, you can use inheritance to represent this in ABAP Objects.
202
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Using Inheritance
Partner
This exception of error class CX_SY_MOVE_CAST_ERROR can be identified using TRY-ENDTRY and the CATCH statement. Another way of preventing this runtime error would be to use runtime type identification (RTTI) classes. They can be used to determine the dynamic type at runtime and to set a condition for the cast.
SAP
In contrast to the narrowing cast assignment, it is possible that the static type of the target variable (R_TRUCK) is neither more general than nor the same as the dynamic type of the source variable (R_VEHICLE), namely when R_VEHICLE contains bus or sports car references. That is why with this kind of cast, the runtime system checks, before the assignment, whether the current content of the source variable corresponds to the type requirements of the target variable. Otherwise, an exception that can be handled is triggered, and the original value of the target variable remains the same.
Use
Partner
Only
Internal
Figure 109: Widening Cast Assignment and Exception Handling in the Application Example
Lesson: Inheritance and Casting
Figure 110: Using Inheritance
Use
Partner
In that case, you need to adhere to the relevant concepts of inheritance. For example, the semantics must be preserved when you redefine methods. Furthermore, inherited components must be used as intended in the superclass.
Internal
Only
BC401
SAP
SAP
If you misunderstand the statement “is a (specific)”, you run the risk of identifying wrong places in which to use inheritance. Sometimes the need for another attribute for a class is incorrectly answered with a specialization. For example:
08-03-2004
© 2004 SAP AG. All rights reserved.
203
Only
Internal
Use
Partner
Figure 111: Examples: Misuse of Inheritance
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
In some cases, specialization relationships are identified that do not allow for the semantics to be preserved. For example:
SAP Use
Only
Internal
Partner
For the same reasons, simple inheritance of the source text – that is, using inheritance only because some required functions were found in a (super)class – is also impossible.
SAP
The class Square inherits from the class Rectangle. If you try to define methods for the rectangle that change the width and height separately, these methods would not make sense when applied to the square. Even if the methods had been redefined to change the lengths of the sides in uniform, the semantics would be different.
Use
Partner
Note: Such attributes are often also defined as reference variables to a superclass of role classes. There is one description class for each role. To change the role of an instance, you then exchange the references to the corresponding role description instances. Specialist literature also refers to this as a “role design pattern”.
Internal
Only
A superclass Car contains the subclasses Red Car, Blue Car, and so on. The statement “A red car is a specific car” is only correct at first glance. However, there are no cars without a color. At best, there are some cars that have not been painted. Therefore, every car needs the attribute Color, assuming that it is relevant to the application. Therefore, the attribute should already have been defined in the superclass, or there is no longer an authorization for subclasses of this type. There would also be contradictions with reality when you try to implement a method for painting the cars.
204
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
Exercise 11: Class Hierarchies Exercise Objectives
Internal
Only
After completing this exercise, you will be able to: • Define subclasses • Redefine superclass methods in subclasses • Use visibility sections effectively
Business Example
Task 1: In the class LCL_AIRPLANE, define the local subclass LCL_PASSENGER_PLANE for passenger planes. Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_AIRS_MAIN_E (where ## is your two-digit group number).
The class must have a private instance attribute MAX_SEATS with the same type as the table field SFLIGHT-SEATSMAX.
3.
Define and implement an instance constructor that assigns values to all instance attributes in the class.
4.
Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed using the WRITE statement.
Task 2: In the class LCL_AIRPLANE, define the local subclass LCL_CARGO_PLANE for cargo planes. 1.
The class must have a private instance attribute MAX_CARGO with the same type as the table field SCPLANE-CARGOMAX.
2.
Define and implement an instance constructor that assigns values to all instance attributes in the class. Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
205
Only
Internal
2.
Partner
Use
If applicable, enter the source code for your new class in the include program.
SAP
SAP
1.
Use
Partner
Your airplane management program is to be refined further. Put specific airplanes in relation to their general airplane class.
Unit 3: Object-Oriented Concepts and Programming Techniques
3.
BC401
Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed using the WRITE statement.
Task 3:
Partner
In the main program, define a suitably typed reference variable for each of your new classes.
2.
Call the static method DISPLAY_N_O_AIRPLANES (before instantiating any objects).
3.
Use the two references to create an instance of each of the subclasses LCL_PASSENGER_PLANE and LCL_CARGO_PLANE. Decide for yourself how to fill the attributes.
4.
Call the DISPLAY_ATTRIBUTES method for both instances.
5.
Call the static method DISPLAY_ATTRIBUTES a second time.
Use
1.
Task 4:
SAP
2.
Could the method GET_TECHNICAL_ATTRIBUTES be called directly from the redefined method DISPLAY_ATTRIBUTES of the subclasses?
Only
Internal
Observe the program flow in the ABAP Debugger, paying special attention to the call of the DISPLAY_ATTRIBUTES method.
Partner
1.
SAP
Analyze your program.
Use
Internal
Only
Create instances of your new classes and display their attributes.
206
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
Solution 11: Class Hierarchies Task 1: In the class LCL_AIRPLANE, define the local subclass LCL_PASSENGER_PLANE for passenger planes. Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_AIRS_MAIN_E (where ## is your two-digit group number). If applicable, enter the source code for your new class in the include program.
b) 2.
The class must have a private instance attribute MAX_SEATS with the same type as the table field SFLIGHT-SEATSMAX. a)
SAP
Define and implement an instance constructor that assigns values to all instance attributes in the class. a)
See the source code extract from the model solution
Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed using the WRITE statement. a)
See the source code extract from the model solution
In the class LCL_AIRPLANE, define the local subclass LCL_CARGO_PLANE for cargo planes. 1.
The class must have a private instance attribute MAX_CARGO with the same type as the table field SCPLANE-CARGOMAX. a)
2.
See the source code extract from the model solution
Define and implement an instance constructor that assigns values to all instance attributes in the class. a)
See the source code extract from the model solution
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
207
Only
Internal
Task 2:
Partner
Use
4.
See the source code extract from the model solution
SAP
3.
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_INHS_MAIN_A
Use
Partner
a)
Internal
Only
1.
Unit 3: Object-Oriented Concepts and Programming Techniques
3.
BC401
Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed using the WRITE statement. a)
See the source code extract from the model solution
Task 3: Create instances of your new classes and display their attributes. In the main program, define a suitably typed reference variable for each of your new classes. a)
Call the static method DISPLAY_N_O_AIRPLANES (before instantiating any objects). a)
3.
Use the two references to create an instance of each of the subclasses LCL_PASSENGER_PLANE and LCL_CARGO_PLANE. Decide for yourself how to fill the attributes. a)
SAP
Call the DISPLAY_ATTRIBUTES method for both instances. a)
5.
See the source code extract from the model solution
Call the static method DISPLAY_ATTRIBUTES a second time. See the source code extract from the model solution
Task 4: 1.
Observe the program flow in the ABAP Debugger, paying special attention to the call of the DISPLAY_ATTRIBUTES method. a)
2.
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Could the method GET_TECHNICAL_ATTRIBUTES be called directly from the redefined method DISPLAY_ATTRIBUTES of the subclasses? Answer: No, because the component of the superclass is private
Continued on next page
208
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Analyze your program.
Partner
a)
Use
See the source code extract from the model solution
SAP
4.
See the source code extract from the model solution
Use
Partner
2.
See the source code extract from the model solution
Internal
Only
1.
BC401
Lesson: Inheritance and Casting
Result Source code extract:
SAPBC401_INHS_MAIN_A REPORT
sapbc401_inhs_main_a.
Internal
Only
TYPE-POOLS icon.
INCLUDE sapbc401_inhs_a.
DATA: r_plane TYPE REF TO lcl_airplane,
Partner
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.
Use
START-OF-SELECTION.
SAP
SAP
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_passenger EXPORTING
Use
Partner
im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345.
Internal
CREATE OBJECT r_cargo EXPORTING im_name = ’US Hercules’ im_planetype = ’747-500’ im_cargo = 533.
Only
r_cargo->display_attributes( ).
r_passenger->display_attributes( ).
lcl_airplane=>display_n_o_airplanes( ).
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
209
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
SAPBC401_INHS_A *&---------------------------------------------------------------------* *&
Include
SAPBC401_INHS_A
*
*&---------------------------------------------------------------------* *------------------------------------------------------------------* *
CLASS lcl_airplane DEFINITION
*
*------------------------------------------------------------------*
Internal
Only
CLASS lcl_airplane DEFINITION. PUBLIC SECTION. "-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
Partner
METHODS: constructor IMPORTING im_name
TYPE string
im_planetype TYPE saplane-planetype,
Use
display_attributes. CLASS-METHODS: display_n_o_airplanes.
SAP
SAP
PRIVATE SECTION. "---------------------------------METHODS: get_technical_attributes IMPORTING im_type
Use
ex_tankcap DATA: name
TYPE saplane-planetype TYPE s_plan_wei
Partner
EXPORTING ex_weight
TYPE s_capacity.
TYPE string,
Internal
planetype TYPE saplane-planetype. CLASS-DATA: n_o_airplanes TYPE i.
Only
ENDCLASS.
"lcl_airplane DEFINITION
*------------------------------------------------------------------* *
CLASS lcl_airplane IMPLEMENTATION
*
*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. METHOD constructor. name
= im_name.
Continued on next page
210
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
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,
Internal
Only
/ ’Name des Flugzeugs’(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 ).
Partner
WRITE: / ’Gewicht:’(003), weight, ’Tankkap:’(004), cap. ENDMETHOD.
"display_attributes
Use
METHOD display_n_o_airplanes. WRITE: /, / ’Number of airplanes: ’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
SAP
"display_n_o_airplanes
SAP
ENDMETHOD.
METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap)
Partner
Use
WHERE planetype = im_type. IF sy-subrc <> 0. ex_weight = 100000. ex_tankcap = 10000.
ENDMETHOD. ENDCLASS.
"get_technical_attributes
Only
Internal
ENDIF.
"lcl_airplane IMPLEMENTATION
*---------------------------------------------------------------------* *
CLASS lcl_cargo_plane DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
211
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
PUBLIC SECTION. "---------------------METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype im_cargo TYPE scplane-cargomax. METHODS: display_attributes REDEFINITION.
"---------------------DATA: max_cargo TYPE scplane-cargomax.
"lcl_cargo_plane DEFINITION
*---------------------------------------------------------------------* *
CLASS lcl_cargo_plane IMPLEMENTATION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
SAP
SAP
CLASS lcl_cargo_plane IMPLEMENTATION.
Use
Partner
ENDCLASS.
Internal
Only
PRIVATE SECTION.
METHOD constructor. CALL METHOD super->constructor( im_name = im_name im_planetype = im_planetype ). max_cargo = im_cargo.
Use
Partner
"constructor
ENDMETHOD.
METHOD display_attributes.
Internal
super->display_attributes( ). WRITE: / ’Max Cargo = ’, max_cargo. ULINE.
ENDCLASS.
Only
ENDMETHOD.
"display_attributes
"lcl_cargo_plane IMPLEMENTATION
*---------------------------------------------------------------------* *
CLASS lcl_passenger_plane DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..
Continued on next page
212
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
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.
Internal
Only
DATA: max_seats TYPE sflight-seatsmax. "lcl_passenger_plane DEFINITION
ENDCLASS.
*---------------------------------------------------------------------* *
CLASS lcl_passenger_plane IMPLEMENTATION
Partner
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
Use
CLASS lcl_passenger_plane IMPLEMENTATION.
METHOD constructor. CALL METHOD super->constructor( EXPORTING im_name
= im_name
SAP
SAP
im_planetype = im_planetype ). max_seats = im_seats. "constructor
ENDMETHOD.
METHOD display_attributes.
Partner
Use
super->display_attributes( ). WRITE: / ’Max Seats = ’, max_seats. ULINE.
Internal
ENDMETHOD.
ENDCLASS.
"display_attributes "lcl_passenger_plane IMPLEMENTATION
Only
08-03-2004
© 2004 SAP AG. All rights reserved.
213
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
214
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
Exercise 12: Polymorphism Exercise Objectives After completing this exercise, you will be able to: • Program narrowing cast assignments • Use inheritance relationships for polymorphic method calls
Only
Task 1: 1.
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. (Where ## is your two-digit group number).
2.
In your main program, define an internal table for buffering airplane references. The row type of the internal table should be REF TO LCL_AIRPLANE.
Use
Partner
Task 2: Insert the references to your passenger and cargo airplanes into the internal table.
2.
Program a loop through the contents of the internal table. Call the DISPLAY_ATTRIBUTES method every time the loop runs.
Only
Internal
Display the attributes of all airplane types that were created so far. 1.
Task 3: Analyze your program. 1.
Follow the program flow in the ABAP Debugger, paying special attention to the call of the DISPLAY_ATTRIBUTES method.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
SAP
SAP
Buffer the airplane references in a suitable type of internal table.
Use
Partner
Your airplane management program should display the attributes of the airplane objects generically, that is, it should be open to future extensions with additional airplane classes.
Internal
Business Example
215
Unit 3: Object-Oriented Concepts and Programming Techniques
2.
BC401
What would happen if the DISPLAY_ATTRIBUTES method had not been redefined in the subclasses?
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
216
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
Solution 12: Polymorphism Task 1: Buffer the airplane references in a suitable type of internal table. 1.
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. (Where ## is your two-digit group number).
b)
In your main program, define an internal table for buffering airplane references. The row type of the internal table should be REF TO LCL_AIRPLANE. a)
See the source code extract from the model solution
Use
Partner
2.
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_CASS_MAIN_A
Task 2: Display the attributes of all airplane types that were created so far.
SAP
Insert the references to your passenger and cargo airplanes into the internal table. a)
Use
See the source code extract from the model solution
Program a loop through the contents of the internal table. Call the DISPLAY_ATTRIBUTES method every time the loop runs. a)
Partner
2.
SAP
1.
See the source code extract from the model solution
Analyze your program. Follow the program flow in the ABAP Debugger, paying special attention to the call of the DISPLAY_ATTRIBUTES method. a) 2.
Carry out this step in the usual manner. Additional information is available in the SAP Library.
What would happen if the DISPLAY_ATTRIBUTES method had not been redefined in the subclasses? Answer: The implementation from the superclass would be executed. Your program would not contain polymorphism. Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
217
Only
Internal
Task 3: 1.
Internal
Only
a)
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Result Source code extract:
SAPBC401_CASS_MAIN_A REPORT
sapbc401_cass_main_a.
Internal
Only
TYPE-POOLS icon.
INCLUDE sapbc401_inhs_a. DATA: r_plane TYPE REF TO lcl_airplane, r_cargo TYPE REF TO lcl_cargo_plane,
Partner
r_passenger TYPE REF TO lcl_passenger_plane, plane_list TYPE TABLE OF REF TO lcl_airplane.
Use
START-OF-SELECTION. *##############################
SAP
SAP
lcl_airplane=>display_n_o_airplanes( ). CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’
Use
Partner
im_planetype = ’747-400’ im_seats = 345. APPEND r_passenger TO plane_list.
Internal
CREATE OBJECT r_cargo EXPORTING im_name = ’US HErcules’ im_planetype = ’747-500’ im_cargo = 533.
Only
APPEND r_cargo TO plane_list.
LOOP AT plane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP.
lcl_airplane=>display_n_o_airplanes( ).
218
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
Exercise 13: Aggregation and Generic Calls Exercise Objectives
Business Example
Task 1:
Use Internal
2.
Extend the signature and implementation of method ADD_AIRPLANE so that the airplane references can be added to the previously defined list AIRPLANE_LIST.
3.
Extend the implementation of method DISPLAY_AIRPLANES so that the attributes of all airplanes of the airline can be added to the list. Each time an airplane is added, its DISPLAY_ATTRIBUTES method should be called.
4.
Extend the implementation of the DISPLAY_ATTRIBUTES method so that all of attributes of the airline can be displayed and, consequently, the contents of the airplane list can also be displayed.
Task 2: In the main program, create an airline instance. Transfer some airplane references to it and display the attributes. 1.
Remove all the statements from the main program that define the global internal table for airplane references and their insertions. Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
219
Only
From the include program SAPBC401_CAST_B, copy the portions of the source text for the local class LCL_CARRIER into your include program ZBC401_##_AIRPLANE so that you can add to them there. (Where ## is your two-digit group number).
Partner
1.
SAP
SAP
Define a local class for airlines.
Use
Partner
Now, the management of airplane instances should no longer take place in the main program. Instead, it should be encapsulated in a new class for airlines.
Internal
Only
After completing this exercise, you will be able to: • Implement aggregation relationships between classes • Program narrowing cast assignments • Use inheritance relationships for polymorphic method calls
BC401
In the main program, define a suitably typed reference variable for your new airline class.
3.
Using the reference, generate an instance of your class LCL_CARRIER. Decide for yourself how to fill the attributes.
4.
Call the ADD_AIRPLANE method to transfer the airplane instances that have been created so far to the airline. You may also create and transfer additional airplanes.
5.
Display the attributes of the airline by calling its DISPLAY_ATTRIBUTES method.
Use
Partner
2.
Internal
Only
Unit 3: Object-Oriented Concepts and Programming Techniques
SAP
SAP Only
Internal
Use
Partner
220
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
Solution 13: Aggregation and Generic Calls Task 1: Define a local class for airlines. From the include program SAPBC401_CAST_B, copy the portions of the source text for the local class LCL_CARRIER into your include program ZBC401_##_AIRPLANE so that you can add to them there. (Where ## is your two-digit group number). a) b)
Extend the signature and implementation of method ADD_AIRPLANE so that the airplane references can be added to the previously defined list AIRPLANE_LIST. a)
Extend the implementation of method DISPLAY_AIRPLANES so that the attributes of all airplanes of the airline can be added to the list. Each time an airplane is added, its DISPLAY_ATTRIBUTES method should be called. a)
Use
Extend the implementation of the DISPLAY_ATTRIBUTES method so that all of attributes of the airline can be displayed and, consequently, the contents of the airplane list can also be displayed. See the source code extract from the model solution
Task 2: In the main program, create an airline instance. Transfer some airplane references to it and display the attributes. 1.
Remove all the statements from the main program that define the global internal table for airplane references and their insertions. a)
2.
See the source code extract from the model solution
In the main program, define a suitably typed reference variable for your new airline class. a)
See the source code extract from the model solution Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
221
Only
Internal
a)
Partner
4.
See the source code extract from the model solution
SAP
SAP
3.
See the source code extract from the model solution
Use
Partner
2.
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_CASS_MAIN_B
Internal
Only
1.
Unit 3: Object-Oriented Concepts and Programming Techniques
3.
Using the reference, generate an instance of your class LCL_CARRIER. Decide for yourself how to fill the attributes. a)
4.
See the source code extract from the model solution
Display the attributes of the airline by calling its DISPLAY_ATTRIBUTES method. a)
See the source code extract from the model solution
Partner
Result Source code extract:
Use
SAPBC401_CASS_MAIN_B sapbc401_cass_main_b.
SAP
SAP
REPORT
TYPE-POOLS icon.
Partner
Use
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,
Internal
r_carrier TYPE REF TO lcl_carrier.
Only
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’
Continued on next page
222
Internal
Only
See the source code extract from the model solution
Call the ADD_AIRPLANE method to transfer the airplane instances that have been created so far to the airline. You may also create and transfer additional airplanes. a)
5.
BC401
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
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 ***************************
Internal
Only
r_carrier->add_airplane( r_passenger ).
Partner
r_carrier->add_airplane( r_cargo ).
***** show all airplanes inside carrier *************************** r_carrier->display_attributes( ).
Use
SAPBC401_CASS_B *&
Include
SAPBC401_CASS_B
SAP
SAP
*&---------------------------------------------------------------------* *
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
Use
CLASS lcl_airplane DEFINITION
Partner
*
*
*------------------------------------------------------------------* ... *---------------------------------------------------------------------*
Internal
*
CLASS lcl_carrier DEFINITION
*---------------------------------------------------------------------* *
Only
*---------------------------------------------------------------------* 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,
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
223
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
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 add_airplane.
Partner
APPEND im_plane TO airplane_list. ENDMETHOD.
"add_airplane
Use
METHOD display_attributes. WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). "display_attributes
SAP
SAP
ENDMETHOD.
Internal
Only
*
METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane. LOOP AT airplane_list INTO r_plane.
Partner
Use
r_plane->display_attributes( ). ENDLOOP. ENDMETHOD.
"display_airplanes
Internal
METHOD constructor. name = im_name. ENDMETHOD.
"constructor
Only
METHOD get_name. ex_name = name. ENDMETHOD.
ENDCLASS.
224
"get_name
"lcl_carrier IMPLEMENTATION
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Inheritance and Casting
Lesson Summary
Only
Related Information
Use
Partner
... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.
Internal
You should now be able to: • Define inheritance relationships between classes • Redefine methods • Create narrowing cast assignments • Create widening cast assignments • Explain the concept of polymorphism with reference to interfaces • Use cast assignments with inheritance to make generic calls
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
225
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Lesson: Interfaces and Casting Lesson Overview The only real difference between interfaces and inheritance is the role they play. The programming advantages are thus the same as for inheritance. Therefore, the former will be the first focus of this lesson.
Only
Internal
Lesson Objectives After completing this lesson, you will be able to:
Partner
Define and implement interfaces Implement interface methods Use interface references to make narrowing cast assignments Use interface references to make widening cast assignments Explain the term polymorphism with reference to interfaces Use cast assignments with interfaces to make generic calls
Use
• • • • • •
SAP
You want to implement client/server relationships in combination with generic access from your model in ABAP Objects.
Use
Interfaces differ from regular inheritance in their area of use. In terms of programming, there are hardly any differences, however.
Internal
In ABAP Objects, interfaces primarily serve to define uniform interfaces (protocols) for services. Various classes can thus offer – that is, implement – these services in different ways, but keep the same semantics. Interfaces therefore contain no implementations. In ABAP Objects, the same components can generally be defined in interfaces and in classes. To recognize the semantic differences from regular inheritance, you can concentrate on the following, typical use cases:
226
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
From a technical point of view, interfaces are simply superclasses that cannot be instantiated, do not have an implementation part, and only have public components. However, we will see that you can simulate multiple inheritance using interfaces.
Partner
Areas of Use for Interfaces
SAP
Business Example
BC401
Lesson: Interfaces and Casting
Partner
Only
Internal
Figure 112: Central Definition of Shared Components
SAP
SAP
Use
For example, you want to allow for the option of having multiple classes implementing a service in different ways, but using the same method names and with a uniform signature. With regular inheritance, you would define such a method in the shared superclass. However, if you cannot model a superclass suitably for inheritance, you need to define an interface and then define this method there. Therefore, you can compare this case with a generalization relationship with a superclass.
Only
Internal
Use
Partner
Figure 113: The Client Defines the Protocol
08-03-2004
© 2004 SAP AG. All rights reserved.
227
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Compared to regular inheritance, distribution of roles is sometimes different: The user generally defines the interfaces. In these, the user describes (both technically and semantically) the services that he/she wants the providers to offer. Each class can now decide for itself whether it serves the interface, that is, actually offers the services defined there. Therefore, this case is similar to a specialization relationship with a subclass.
Only
Use
Partner
Internal
As with regular inheritance, access to these services is then usually generic, that is, using a reference that is typed on the interface. As with regular inheritance, you can thus perform polymorphism with interfaces.
Internal
The similarity with representing a generalization/specialization relationship is justified, as we have just described.
228
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
In UML, interfaces are represented in the same way as classes. However, in addition to their name, they bear the stereotype «interface.» 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 arrow from the class to the interface.
Partner
Use
SAP
SAP
Figure 114: Interfaces in UML Notation
BC401
Lesson: Interfaces and Casting
Realization of Generalization/Specialization Relationships Using Interfaces In ABAP Objects, the same components can be defined in an interface as in classes. However, interfaces do not know the visibility levels of components, that is, all components of an interface are public. Note: Note the areas of use for interfaces as the uniform interface for offering services.
Use
Partner
Only
Internal
•
• •
The interface name is listed in the definition part of the class with the INTERFACES statement. This must be in the PUBLIC SECTION, that is, interfaces can only be implemented publicly. The interface methods must be implemented in the implementation part of the class. The components defined in the interface can be addressed in the implementation part of the class.
Interface components are distinguished from the other components in the implementing class by prefixing the interface name followed by a tilde ~ (the interface resolution operator): interface_name~component_name.
08-03-2004
© 2004 SAP AG. All rights reserved.
229
Only
Internal
Classes implement interfaces as follows:
Partner
Use
SAP
SAP
Figure 115: Defining and Implementing an Interface
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
To simplify accessing interface components you can work with alias names. These can only appear in the definition part of a class or in the interface definition. Their use is subject to the visibility restriction of the defining class. Example of an alias in the interface: ALIASES a_1 FOR lif_1~method_1.
Only
Use
Partner
Internal
The interface method lif_1~method_1 can then be addressed with the shorter form ref->a_1 .
Internal
Alternatively, you can use the alias names defined in the implementing class for the interface components. Even if shared components of the implementing classes subsequently are transferred to the interface, access to
230
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Interface components can only be accessed by using an object reference, whose class implements the interface. Syntactically, this takes place with the interface resolution operator ~ , just as with access to the interface components in the implementation part of the class.
Partner
Use
SAP
SAP
Figure 116: Addressing Interface Components Using Object References
BC401
Lesson: Interfaces and Casting
these components does not need to be adapted. However, the source text would then be less self-explanatory because you could conclude from the syntax that the components were defined in the class.
Polymorphism with Interfaces
Only
Use
Partner
Internal
Because interfaces cannot be instantiated, an interface reference can only refer to instances of classes that have implemented the interface. Therefore, if you want to perform polymorphism with interfaces, you must use narrowing cast to copy a reference to the reference variable that was typed with the interface – as with regular inheritance.
Internal
A user can thus address the instance of the implementing class using the interface. The prefixing of the interface name and the interface resolution operator is thus omitted. However, the user is restricted to using the components from the interface.
08-03-2004
© 2004 SAP AG. All rights reserved.
231
Only
If the class has implemented the interface, it is certain that all components that can be accessed syntactically after the cast assignment are actually available in the instance. The interface always contains at least the same components as the implementing class.
Partner
Use
SAP
SAP
Figure 117: Narrowing Cast with Interface References
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
In the example shown here, the methods DISPLAY_PARTNER and CHECK_AVAILABILITY of the interface LIF_PARTNER can only be accessed after assigning the reference variable R_PARTNER. It is not possible to access the specific components of the instance from class LCL_RENTAL (GET_NAME in the above example) using the reference variable R_PARTNER.
Only
Use
Partner
Internal
The view is thus restricted as a rule (usually observed). That is why we describe this type of assignment of reference variables as narrowing cast. There is a switch from a view of several components to a view of a few components. The term upcast is also common.
Internal
In the example shown here, a travel agency (LCL_TRAVEL_AGENCY) needs to manage all the various kinds of business partner in one list. The row type of the internal table must therefore be typed as the reference to the interface LIF_PARTNER. The travel agency only wants to request the services in order to display their attributes and to check availability. The relevant methods DISPLAY_PARTNER and CHECK_AVAILABILITY are defined in the interface LIF_PARTNER and implemented in all business partner classes.
232
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
A typical area of use for narrowing cast assignments is preparation for generic access: A user, who is not at all interested in the finer points of the instances of the classes that implement the interface but who simply wants to address the components defined in the interface, could use an interface reference for this access.
Partner
Use
SAP
SAP
Figure 118: Row Type of the Internal Table in the Application Example
BC401
Lesson: Interfaces and Casting
Objects of different classes (LCL_HOTEL, LCL_RENTAL, and LCL_CARRIER in the above example) can be kept in an internal table, typed with interface references (LIF_PARTNER in the above example). The components defined in the interface can then be accessed uniformly. For this example, method ADD_PARTNER is therefore needed. This copies the references to all the kinds of business partner in this internal table. It is import parameter is already typed as the reference to the interface.
Use
Partner
Only
Internal
The dynamic type and 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_partner . The static type for r_partner , which is always REF TO lif_partner
08-03-2004
© 2004 SAP AG. All rights reserved.
233
Only
Internal
Polymorphism can also be performed for interfaces: Interface references can be used to call methods, whereby different implementations can be executed depending on the object of the reference.
Partner
Use
SAP
SAP
Figure 119: Polymorphism – Generic Access Using the Interface Reference
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
, is not used. The implementation that is now executed when DISPLAY_PARTNER is called therefore depends on the object to which the interface reference R_PARTNER currently refers. When objects from different classes react differently to the same method calls, this is known as polymorphism.
Only
Polymorphism can be used to write programs that are highly generic, that is, they do not need to be changed significantly if use cases are added.
Partner
Use
In the example given here, it would therefore be very easy to realize a boat rental addition: The relevant class – for example, with the name LCL_SHIPPING – would simply have to implement the interface LIF_PARTNER and thus the method DISPLAY_PARTNER defined there. Business partner management could then include shipping companies without problem and also request them to display their attributes.
Internal
The option of performing polymorphism is one of the main strengths of interfaces: A client can handle different classes uniformly, irrespective of their implementation. The runtime system searches for the right implementation of a method on behalf of the client.
SAP
SAP Only
Internal
Use
Partner
Figure 120: Widening Cast Assignment and Exception Handling in the Application Example
234
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Interfaces and Casting
Partner
Use
SAP
That is why with this kind of cast, the runtime system checks, before the assignment, whether the current content of the source variable corresponds to the type requirements of the target variable. Otherwise, an exception that can be handled is triggered, and the original value of the target variable remains the same. This exception of error class CX_SY_MOVE_CAST_ERROR can be identified using TRY-ENDTRY and the CATCH statement.
08-03-2004
© 2004 SAP AG. All rights reserved.
235
Only
Therefore, what happens if there is no airline reference in the interface reference R_PARTNER at runtime but the widening cast assignment operator is used to copy the reference to the then invalid reference R_CARRIER? In contrast to the narrowing cast assignment, it is possible that the static type of the target variable (R_CARRIER) is neither more general than nor the same as the dynamic type of the source variable (R_PARTNER), namely when R_PARTNER contains hotel or car rental references.
Partner
A typical area of use for widening cast assignments is when specific components of instances need to be addressed whose references are kept in variables that are typed on the interface. A user who is interested in the finer points of instances of implementing classes cannot use the interface reference for this access because this only allows access to the interface components. In the example shown here, a travel agency (LCL_TRAVEL_AGENCY) needs to book a flight but keeps all the various business partner references in an internal table that was typed on the interface LIF_PARTNER.
SAP
Use
The view is thus widened (at least unchanged). That is why we describe this type of assignment of reference variables as widening cast. There is a switch from a view of a few components to a view of more components. The term downcast is also common.
Internal
Interface reference variables can contain references to instances of the implementing class at runtime. After assigning this type of reference (back) to a reference to the implementing class, clients are no longer limited to interface components: In the example given here, all components of the LCL_CARRIER instance can be accessed (again) after the assignment using reference R_CARRIER.
Internal
Only
If you want to assign an interface reference to a class reference where the class has implemented the interface, you must use the widening cast assignment operator MOVE ... ?TO ... or its short form ?= . Otherwise, the system would return a message stating that it is not certain that all components that can be accessed syntactically after the cast assignment are actually available in the instance. As a rule, the implementing class contains more components than the interface.
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Another way of preventing this runtime error would be to use runtime type identification (RTTI) classes. They can be used to determine the dynamic type at runtime and to set a condition for the cast.
Only
Interface Hierarchies
Use
Partner
We have already seen several times that an interface implementation strongly resembles regular inheritance. We therefore need to ask what the interface counterpart of hierarchical inheritance looks like. We want to explain interface hierarchies using an application example:
Internal
Assignments between interface reference variables, whose typing interfaces are not related to each other, cannot be checked statically either and must therefore be performed using widening cast. With such an assignment, the system checks at runtime whether the class of the instance to which the source reference refers also supports the interface with which the target reference is typed.
SAP
SAP
In this example, we need to know whether it would be useful to define a further service “room reservation” in the interface LIF_PARTNER. In this case, the classes LCL_CARRIER and LCL_RENTAL would have to implement the appropriate method because they have integrated the interface LIF_PARTNER. However, implementation of a room reservation – keeping the same semantics – is not conceivable for airlines or car rental companies.
236
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Use
Partner
Figure 121: Interface Hierarchy in the Application Example
BC401
Lesson: Interfaces and Casting
However, because there are several other business partner types for which an implementation would be useful (for example, motels and hotels), the method needs to be centrally defined and not individually for motels and hotels. On the other hand, the option of easily extending the model with other accommodation provider types (for example, guesthouse) must be retained.
Use
The including interface is known as a compound interface. An included interface represents a component of another interface and is therefore known as a component interface. An elementary interface does not itself contain other interfaces. The UML notation corresponds to the implementation of an elementary interface by a class.
08-03-2004
© 2004 SAP AG. All rights reserved.
237
Only
Internal
You can thus regard the including interface as a specialization of the included interface. It represents an extension of the included interface.
Partner
In ABAP Objects, interfaces – like regular superclasses – can include other interfaces. As with regular inheritance, the result is interface hierarchies of any “depth.”
SAP
SAP
Use
Partner
Only
Internal
Figure 122: Compound Interface in UML Notation
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
SAP Use
Only
Internal
All implementations of methods from all higher-level interfaces must take place in the first implementing class. Alias names are suitable for short-form syntax when accessing components from different interfaces. At the same time, you get a central documentary view of all components with the definition of these alias names in the implementing class.
Partner
They are therefore not prefixed with the name of the compound interface.
SAP
As with regular inheritance, the implementing class only needs to list the compound interface in order to integrate all components. Nevertheless, the components of the component interfaces keep their original names, that is, component_interface_name~component_name.
Use
Partner
Only
Internal
Figure 123: Definition and Implementation of Compound Interfaces – Syntax
238
© 2004 SAP AG. All rights reserved.
08-03-2004
Lesson: Interfaces and Casting
Internal
Figure 124: Addressing Components in Compound Interfaces – Syntax
The same possibilities apply for access its components from a compound interface and for cast assignments.
Use
Partner
Only
BC401
SAP
SAP Only
Internal
Use
Partner
Figure 125: Using Interfaces
Interfaces are used to describe protocols for using components without connecting a kind of implementation. An “intermediate” layer is introduced between the client and the server to protect the client from the explicit server, thereby making the client independent.
08-03-2004
© 2004 SAP AG. All rights reserved.
239
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Interfaces enable different classes to be handled uniformly, providing they implemented the interfaces. As with inheritance, you can also perform polymorphism using interface reference variables. As with regular inheritance, the definition of an interface means an abstraction of the implementing classes to a specific partial aspect. Multiple inheritance can be simulated using interfaces: If several interfaces are included, all components are available to all of these interfaces. All methods must be implemented.
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
240
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Interfaces and Casting
Exercise 14: Interface Implementation Exercise Objectives After completing this exercise, you will be able to: • Define interfaces • Implement interfaces
Only
Task 1:
From the include program SAPBC401_VEHT_F, copy the portions of the source text for the local classes LCL_VEHICLE, LCL_TRUCK, LCL_BUS, and LCL_RENTAL into a new include program ZBC401_##_VEHICLE to extend them there if necessary. (Where ## is your two-digit group number). Include this new include program in your main program.
3.
From the program SAPBC401_VEHT_MAIN_A, copy the portions of the source text for the data types TY_FUEL and TY_CARGO for the definitions of the reference variables, for the generation of the instances, and for the method calls in your main program to extend them there if necessary.
4.
To test your work so far, call the method DISPLAY_ATTRIBUTES for the car rental company. The list should now display all airplanes of your airline and all vehicles of your car rental company.
Internal
Use
2.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
241
Only
Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_CASS_MAIN_B (where ## is your two-digit group number).
Partner
1.
SAP
SAP
Define a class for car rental companies and a class hierarchy for general vehicles, buses, and trucks. Generate a car rental company and add a few vehicle instances. Add the attributes of the car rental company to the list.
Use
Partner
You now need to add a vehicle management procedure to your airplane management program. The airlines and car rental companies then need to be abstracted to business partners; that is, they need to offer general services using an abstract interface.
Internal
Business Example
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Task 2: Define and implement an interface for offering general services from business partners. 1.
Remove the calls of method DISPLAY_ATTRIBUTES from your main program again.
2.
If necessary, add an interface LIF_PARTNERS to your UML diagram. This needs to define a method DISPLAY_PARTNER. Draw the relationships to the classes LCL_RENTAL and LCL_CARRIER.
3.
Define the local interface LIF_PARTNERS and the method DISPLAY_PARTNER.
Use
Partner
Caution: You will therefore not receive any output on the list until the next exercise.
SAP Use
Only
Internal
Partner
Implement the interface in the classes LCL_CARRIER and LCL_RENTAL. You need to realize the display of a business partner’s attributes in such a way that they call their own methods DISPLAY_ATTRIBUTES.
SAP
Hint: Include the portions of the source text needed for this in your main program in an appropriate order with the remaining class definitions. 4.
Internal
Only
Note: In the following, you need to store the relevant list outputs as a general service.
242
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Interfaces and Casting
Solution 14: Interface Implementation Task 1: Define a class for car rental companies and a class hierarchy for general vehicles, buses, and trucks. Generate a car rental company and add a few vehicle instances. Add the attributes of the car rental company to the list. Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_CASS_MAIN_B (where ## is your two-digit group number). a)
2.
From the include program SAPBC401_VEHT_F, copy the portions of the source text for the local classes LCL_VEHICLE, LCL_TRUCK, LCL_BUS, and LCL_RENTAL into a new include program ZBC401_##_VEHICLE to extend them there if necessary. (Where ## is your two-digit group number). Include this new include program in your main program.
SAP
From the program SAPBC401_VEHT_MAIN_A, copy the portions of the source text for the data types TY_FUEL and TY_CARGO for the definitions of the reference variables, for the generation of the instances, and for the method calls in your main program to extend them there if necessary.
4.
Carry out this step in the usual manner. Additional information is available in the SAP Library.
To test your work so far, call the method DISPLAY_ATTRIBUTES for the car rental company. The list should now display all airplanes of your airline and all vehicles of your car rental company. a)
See the source code extract from the model solution
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
243
Only
Internal
a)
Partner
Use
3.
Carry out this step in the usual manner. Additional information is available in the SAP Library.
SAP
a)
Use
Partner
b)
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_INTS_MAIN_A
Internal
Only
1.
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Task 2: Define and implement an interface for offering general services from business partners. 1.
Remove the calls of method DISPLAY_ATTRIBUTES from your main program again.
Caution: You will therefore not receive any output on the list until the next exercise.
2.
If necessary, add an interface LIF_PARTNERS to your UML diagram. This needs to define a method DISPLAY_PARTNER. Draw the relationships to the classes LCL_RENTAL and LCL_CARRIER. Speak to your instructor if you have any questions.
SAP
SAP
a) 3.
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Define the local interface LIF_PARTNERS and the method DISPLAY_PARTNER.
Use
Implement the interface in the classes LCL_CARRIER and LCL_RENTAL. You need to realize the display of a business partner’s attributes in such a way that they call their own methods DISPLAY_ATTRIBUTES. a)
See the source code extract from the model solution
Result Source code extract:
Continued on next page
244
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
4.
See the source code extract from the model solution
Partner
Hint: Include the portions of the source text needed for this in your main program in an appropriate order with the remaining class definitions. a)
Use
Partner
a)
Internal
Only
Note: In the following, you need to store the relevant list outputs as a general service.
BC401
Lesson: Interfaces and Casting
SAPBC401_INTS_MAIN_A REPORT
sapbc401_ints_main_a.
TYPES ty_fuel TYPE p DECIMALS 2. TYPES ty_cargo TYPE p DECIMALS 2. TYPE-POOLS icon.
INCLUDE sapbc401_vehd_f.
Only
Internal
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,
Partner
r_carrier TYPE REF TO lcl_carrier, r_rental TYPE REF TO lcl_rental, r_truck TYPE REF TO lcl_truck,
Use
r_bus TYPE REF TO lcl_bus.
START-OF-SELECTION.
SAP
SAP
*############################## ***** Create CARRIER ******************************************** CREATE OBJECT r_carrier EXPORTING im_name = ’Smile&Fly Travel’.
Use
Partner
***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’
Internal
im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING
Only
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( ).
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
245
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
******* 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 *****************************************
Internal
Only
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’
Partner
im_cargo = 48. r_rental->add_vehicle( r_truck ).
Use
***** show attributes of rental *************************** r_rental->display_attributes( ).
SAP
*&---------------------------------------------------------------------* *&
Include
SAPBC401_VEHD_F
*
SAP
SAPBC401_VEHD_F
*&---------------------------------------------------------------------*
Use
* define interface lif_partners *---------------------------------------------------------------------* INTERFACE lif_partners.
Internal
METHODS display_partner. ENDINTERFACE.
Partner
*---------------------------------------------------------------------*
*---------------------------------------------------------------------* 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.
Continued on next page
246
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
*
BC401
Lesson: Interfaces and Casting
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.
"lcl_vehicle DEFINITION
ENDCLASS.
Partner
Internal
Only
"-------------------
*---------------------------------------------------------------------* CLASS lcl_vehicle IMPLEMENTATION
Use
*
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
SAP
METHOD get_average_fuel.
Use
METHOD constructor.
SAP
CLASS lcl_vehicle IMPLEMENTATION.
re_avgfuel = im_distance / im_fuel. "get_average_fuel
ENDMETHOD.
Partner
make = im_make. ADD 1 TO n_o_vehicles. "constructor
Internal
ENDMETHOD.
METHOD set_make. IF im_make IS INITIAL.
Only
" me->init_make( ). also possible
init_make( ). ELSE. make = im_make. ENDIF.
"set_make
ENDMETHOD.
METHOD init_make. make = ’default make’. ENDMETHOD.
"init_make
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
247
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
METHOD get_make. ex_make = make. "get_make
ENDMETHOD.
METHOD display_attributes. WRITE: make. "display_attributes
ENDMETHOD.
re_count = n_o_vehicles. "get_count
ENDMETHOD.
"lcl_vehicle IMPLEMENTATION
*---------------------------------------------------------------------* *
CLASS lcl_truck DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
SAP
SAP
CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.
PUBLIC SECTION. "------------------METHODS:
constructor IMPORTING im_make TYPE string
Partner
Use
im_cargo TYPE ty_cargo.
Internal
Use
Partner
ENDCLASS.
Internal
Only
METHOD get_count.
METHODS
display_attributes REDEFINITION.
METHODS
get_cargo RETURNING value(re_cargo) TYPE ty_cargo.
PRIVATE SECTION. "-------------------
Only
DATA: max_cargo TYPE ty_cargo.
ENDCLASS.
*---------------------------------------------------------------------* *
CLASS lcl_truck IMPLEMENTATION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_truck IMPLEMENTATION.
Continued on next page
248
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Interfaces and Casting
METHOD constructor. super->constructor( im_make ). max_cargo = im_cargo. "constructor
ENDMETHOD.
METHOD display_attributes. WRITE: / icon_ws_truck AS ICON.
Internal
Only
super->display_attributes( ). WRITE: 20 ’ Cargo = ’, max_cargo. ULINE. "display_attributes
ENDMETHOD.
Partner
METHOD get_cargo. re_cargo = max_cargo. "get_cargo
ENDMETHOD.
Use
ENDCLASS.
SAP
*
SAP
*---------------------------------------------------------------------* CLASS lcl_bus DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
Partner
Use
CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle. PUBLIC SECTION. "------------------METHODS:
constructor IMPORTING im_make TYPE string
METHODS
display_attributes REDEFINITION.
Only
Internal
im_passengers TYPE i.
PRIVATE SECTION. "------------------DATA: max_passengers TYPE i.
ENDCLASS.
*---------------------------------------------------------------------* *
CLASS lcl_bus IMPLEMENTATION
*---------------------------------------------------------------------*
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
249
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
* *---------------------------------------------------------------------* CLASS lcl_bus IMPLEMENTATION.
METHOD constructor. super->constructor( im_make ). max_passengers = im_passengers. "constructor
Internal
Only
ENDMETHOD.
METHOD display_attributes. WRITE: / icon_transportation_mode AS ICON. super->display_attributes( ). WRITE:
20 ’ Passengers = ’, max_passengers.
"display_attributes
ENDCLASS.
*---------------------------------------------------------------------* *
CLASS lcl_rental DEFINITION
SAP
* *---------------------------------------------------------------------* CLASS lcl_rental DEFINITION.
Partner
Use
PUBLIC SECTION. "------------------METHODS:
constructor IMPORTING im_name TYPE string.
METHODS
add_vehicle IMPORTING im_vehicle
METHODS
display_attributes.
TYPE REF TO lcl_vehicle.
Internal
SAP
*---------------------------------------------------------------------*
Use
Partner
ULINE. ENDMETHOD.
INTERFACES lif_partners.
Only
PRIVATE SECTION. "------------------DATA: name TYPE string, vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS.
*---------------------------------------------------------------------* *
CLASS lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------*
Continued on next page
250
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Interfaces and Casting
* *---------------------------------------------------------------------* CLASS lcl_rental IMPLEMENTATION. METHOD lif_partners~display_partner. display_attributes( ). ENDMETHOD.
METHOD constructor.
Internal
Only
name = im_name. "constructor
ENDMETHOD.
METHOD add_vehicle. APPEND im_vehicle TO vehicle_list. "add_vehicle
Partner
ENDMETHOD.
METHOD
display_attributes.
WRITE: / WRITE:
Use
DATA: r_vehicle TYPE REF TO lcl_vehicle. icon_transport_proposal AS ICON, name. ’ Here comes the vehicle list: ’. ULINE. ULINE.
LOOP AT vehicle_list INTO r_vehicle.
SAP
SAP
r_vehicle->display_attributes( ). ENDLOOP. "display_attributes
ENDMETHOD.
"lcl_rental IMPLEMENTATION
Partner
Use
ENDCLASS.
SAPBC401_INTS_A *&---------------------------------------------------------------------*
Internal
*&
Include
SAPBC401_INTS_A
*
*&---------------------------------------------------------------------*
*
CLASS lcl_airplane DEFINITION
Only
*------------------------------------------------------------------* *
*------------------------------------------------------------------* ... *------------------------------------------------------------------* *
CLASS lcl_airplane IMPLEMENTATION
*
*------------------------------------------------------------------* ... *---------------------------------------------------------------------*
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
251
Unit 3: Object-Oriented Concepts and Programming Techniques
*
BC401
CLASS lcl_cargo_plane DEFINITION
*
*---------------------------------------------------------------------* ... *---------------------------------------------------------------------* *
CLASS lcl_cargo_plane IMPLEMENTATION
*
*---------------------------------------------------------------------* ...
*
CLASS lcl_passenger_plane DEFINITION
*
*---------------------------------------------------------------------* ...
*
CLASS lcl_passenger_plane IMPLEMENTATION
*
*---------------------------------------------------------------------* ... *---------------------------------------------------------------------* *
CLASS lcl_carrier DEFINITION
*
SAP
* ... *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION.
Partner
Use
PUBLIC SECTION. "---------------------------------------INTERFACES lif_partners. METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string,
Internal
SAP
*---------------------------------------------------------------------*
Use
Partner
*---------------------------------------------------------------------*
Internal
Only
*---------------------------------------------------------------------*
add_airplane IMPORTING im_plane TYPE REF TO lcl_airplane,
Only
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
Continued on next page
252
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Interfaces and Casting
*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD lif_partners~display_partner. display_airplanes( ). "lif_partners~display_partner
ENDMETHOD.
METHOD add_airplane. ENDMETHOD.
Internal
Only
APPEND im_plane TO airplane_list. "add_airplane
METHOD display_attributes. WRITE: icon_flight AS ICON, name . ULINE. ULINE.
Partner
display_airplanes( ). ENDMETHOD.
"display_attributes
Use
METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane. LOOP AT airplane_list INTO r_plane. r_plane->display_attributes( ).
SAP
ENDMETHOD.
SAP
ENDLOOP. "display_airplanes
METHOD constructor. name = im_name.
Use
Partner
ENDMETHOD.
"constructor
METHOD get_name. ex_name = name.
Internal
ENDMETHOD.
ENDCLASS.
"get_name
"lcl_carrier IMPLEMENTATION
Only
08-03-2004
© 2004 SAP AG. All rights reserved.
253
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
254
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Interfaces and Casting
Exercise 15: Aggregation, Generic Calls, and Polymorphism Exercise Objectives
Only Partner SAP
1.
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. (Where ## is your two-digit group number).
2.
If necessary, add a class LCL_TRAVEL_AGENCY that uses the interface LIF_PARTNERS to your UML diagram.
Use
3.
From program SAPBC401_VEHT_B, copy the portions of the source text for the local class LCL_TRAVEL_AGENCY into your main program or one of your include programs to extend them there.
4.
Add to the row type of the internal table PARTNER_LIST so that references to the business partners that have implemented your interface can be buffered.
5.
Add to the signature and implementation of method ADD_PARTNER so that the business partner references can be added to the list PARTNER_LIST.
6.
Add to the implementation of method DISPLAY_AGENCY_PARTNERS so that the attributes of all business partners of the travel agency can be added to the list. The centrally provided method DISPLAY_PARTNER needs to be called for each business partner.
Use
You now need to add a user class to your program: Travel agencies need to manage various business partners using the interface and access the business partners’ general services.
Internal
Business Example
Task 1: Define a local class for travel agencies.
Only
255
Partner
© 2004 SAP AG. All rights reserved.
SAP
Continued on next page
08-03-2004
Internal
After completing this exercise, you will be able to: • Realize aggregation relationships between classes • Program narrowing cast assignments • Use inheritance relationships for polymorphic method calls
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Task 2:
In the main program, define a suitably typed reference variable for your new travel agency class.
2.
Using the reference, generate an instance of your class LCL_TRAVEL_AGENCY. Decide for yourself how to fill the attributes.
3.
Call the method ADD_PARTNER to transfer the references to the generated airline and car rental company instances to the travel agency.
4.
Add the attributes of the travel agency by calling its method DISPLAY_AGENCY_PARTNERS.
Use
Partner
1.
Internal
Only
In the main program, generate a travel agency instance, transfer the references to the airline and car rental company to this instance, and add the attributes.
SAP
SAP Only
Internal
Use
Partner
256
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Interfaces and Casting
Solution 15: Aggregation, Generic Calls, and Polymorphism Task 1: Define a local class for travel agencies. Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. (Where ## is your two-digit group number). a) b)
If necessary, add a class LCL_TRAVEL_AGENCY that uses the interface LIF_PARTNERS to your UML diagram. a)
3.
From program SAPBC401_VEHT_B, copy the portions of the source text for the local class LCL_TRAVEL_AGENCY into your main program or one of your include programs to extend them there.
See the source code extract from the model solution
Add to the implementation of method DISPLAY_AGENCY_PARTNERS so that the attributes of all business partners of the travel agency can be added to the list. The centrally provided method DISPLAY_PARTNER needs to be called for each business partner.
SAP Use
a)
See the source code extract from the model solution
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
257
Only
Internal
Add to the signature and implementation of method ADD_PARTNER so that the business partner references can be added to the list PARTNER_LIST. a)
6.
See the source code extract from the model solution
Partner
Add to the row type of the internal table PARTNER_LIST so that references to the business partners that have implemented your interface can be buffered. a)
5.
Carry out this step in the usual manner. Additional information is available in the SAP Library.
SAP
a) 4.
Speak to your instructor if you have any questions.
Use
Partner
2.
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_INTS_MAIN_B
Internal
Only
1.
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Task 2: In the main program, generate a travel agency instance, transfer the references to the airline and car rental company to this instance, and add the attributes. 1.
In the main program, define a suitably typed reference variable for your new travel agency class. a)
Using the reference, generate an instance of your class LCL_TRAVEL_AGENCY. Decide for yourself how to fill the attributes. a)
Call the method ADD_PARTNER to transfer the references to the generated airline and car rental company instances to the travel agency. a)
4.
See the source code extract from the model solution
Add the attributes of the travel agency by calling its method DISPLAY_AGENCY_PARTNERS. a)
Use
Partner
3.
See the source code extract from the model solution
See the source code extract from the model solution
SAP
SAP
Result Source code extract:
Use
Partner
SAPBC401_INTS_MAIN_B REPORT
sapbc401_ints_main_b.
TYPES ty_fuel TYPE p DECIMALS 2. TYPES ty_cargo TYPE p DECIMALS 2.
Internal
Internal
Only
2.
See the source code extract from the model solution
TYPE-POOLS icon.
Only
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,
Continued on next page
258
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Interfaces and Casting
r_truck TYPE REF TO lcl_truck, r_bus TYPE REF TO lcl_bus.
START-OF-SELECTION. *##############################
***** Create TRAVEL_AGENCY **************************************
Internal
Only
CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’.
***** Create CARRIER ********************************************
Partner
CREATE OBJECT r_carrier EXPORTING im_name = ’Smile&Fly Travel’. ... ***** insert business-parnter of agency into partner_list***********
Use
r_agency->add_partner( r_carrier ).
******* create RENTAL *****************************************
SAP
SAP
CREATE OBJECT r_rental EXPORTING im_name = ’HAPPY CAR RENTAL’.
... ***** insert business-parnter of agency into partner_list***********
Partner
Use
r_agency->add_partner( r_rental ).
******* show attributes of all partners of travel_agency ******
Internal
r_agency->display_agency_partners( ).
SAPBC401_VEHD_G
Only
*---------------------------------------------------------------------* * define client lcl_travel_agency * it will use the interface lif_partners *---------------------------------------------------------------------* INTERFACE lif_partners. METHODS display_partner. ENDINTERFACE.
"lif_partners
... *---------------------------------------------------------------------*
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
259
Unit 3: Object-Oriented Concepts and Programming Techniques
*
BC401
CLASS lcl_rental DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_rental DEFINITION. PUBLIC SECTION. METHODS:
constructor IMPORTING im_name TYPE string.
METHODS
add_vehicle IMPORTING im_vehicle
METHODS
display_attributes.
Internal
Only
"-------------------
TYPE REF TO lcl_vehicle. INTERFACES: lif_partners. "------------------DATA: name TYPE string, vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS.
"lcl_rental DEFINITION
*---------------------------------------------------------------------*
SAP
CLASS lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
SAP
*
Use
Partner
PRIVATE SECTION.
...
Use
*
CLASS lcl_travel_agency DEFINITION
*---------------------------------------------------------------------* *
Internal
*---------------------------------------------------------------------* CLASS lcl_travel_agency DEFINITION.
Only
PUBLIC SECTION. "------------------METHODS:
constructor IMPORTING im_name TYPE string.
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.
Continued on next page
260
© 2004 SAP AG. All rights reserved.
Partner
*---------------------------------------------------------------------*
08-03-2004
BC401
Lesson: Interfaces and Casting
ENDCLASS.
"lcl_travel_agency DEFINITION
*---------------------------------------------------------------------* *
CLASS lcl_travel_agency IMPLEMENTATION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_travel_agency IMPLEMENTATION.
Internal
Only
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.
Partner
ULINE. LOOP AT partner_list INTO r_partner. r_partner->display_partner( ).
ENDMETHOD.
METHOD
Use
ENDLOOP. "display_agency_partners
constructor.
SAP
ENDMETHOD. METHOD
SAP
name = im_name. "constructor
add_partner.
APPEND im_partner TO partner_list.
Use
"add_partner "lcl_travel_agency IMPLEMENTATION
Only
Internal
ENDCLASS.
Partner
ENDMETHOD.
08-03-2004
© 2004 SAP AG. All rights reserved.
261
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Lesson Summary
Only
Related Information
Use
Partner
... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.
Internal
You should now be able to: • Define and implement interfaces • Implement interface methods • Use interface references to make narrowing cast assignments • Use interface references to make widening cast assignments • Explain the term polymorphism with reference to interfaces • Use cast assignments with interfaces to make generic calls
SAP
SAP Only
Internal
Use
Partner
262
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
Lesson: Events Lesson Overview
Internal
Only
This lesson provides a general introduction to the concept of events in object orientation, followed by an explanation of all related modeling aspects and syntax elements. The section entitled ’Registration’ contains the information that is probably most important for understanding the topic.
Lesson Objectives After completing this lesson, you will be able to:
Partner
Define and trigger events Handle events Register and deregister event handling Explain the key differences between explicit method calls and event-controlled method calls
Use
• • • •
You want to implement event-controlled behavior from your model in ABAP Objects.
Use Internal
Besides attributes and methods, classes – and their instances – can contain a third type of component: events. Instance events can be triggered by the instances of the class, while static instance events can be triggered by the class itself. Events can also be defined as interface components.
Partner
Event-Controlled Method Calls
SAP
SAP
Business Example
Only
08-03-2004
© 2004 SAP AG. All rights reserved.
263
BC401
Internal
Figure 126: Event-Controlled Method Calls
SAP Use
An event can have exporting parameters, meaning that, unlike in the explicit method call, the calling program determines the protocol. In this application example, after an instance in the “vehicle” class is created, it triggers the event “vehicle created.” This event is received by different instances and processed differently be each one. The rental car company considers purchasing a vehicle, while the vehicle registration office registers the car, and so on.
264
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Because of the definition of the handler method, the range of possible results can be narrowed down, but which, if any, of these results actually will occur can only be determined after the event has been triggered.
Partner
This results in a completely different modeling concept: While you are developing the class that triggers the event, you do not need to know anything about the class that is handling it. The triggering class sends a specific message to all classes (and if need be, their instances) of the running program. At the time of development, it is completely unclear what type of handlers there will be and how many will be used.
SAP
Given the right circumstances, handler methods can now react to the triggering of this event. This means that the runtime system calls the handler methods after the event has been triggered. That is, the handler method is not called directly by the client.
Use
Partner
Only
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Lesson: Events
Caution: Do not confuse this concept of events in object-oriented programming with events in the ABAP runtime system (LOAD-OF-PROGRAM, START-OF-SELECTION, and so on). Also do not confuse it with background processing or workflow controlling.
Use
Partner
Only
Internal
Figure 127: Event Handling in a UML Class Diagram
Partner
SAP Use
SAP
In UML class diagrams, a dotted arrow with the stereotype «handlesEventOf» points from the handling class to the triggering class. The event definition and signature only appear implicitly in the handling class within the handler method. The handler methods are separated from the other methods using the stereotype «eventHandler».
Triggering and Handling events
Only
Internal
The following summarizes all of the required programming steps for event-controlling. They will be explained in more detail later.
08-03-2004
© 2004 SAP AG. All rights reserved.
265
BC401
Keep in mind that, depending on the status of your application, you may not need to program all steps. The separation of cause and effect in your programming should be reflected in the way you construct complex applications. Often, the event is already triggered and all you have to do is create another event handler.
Use
Partner
Figure 128: Triggering and Handling Events – Overview
Internal
Only
Unit 3: Object-Oriented Concepts and Programming Techniques
SAP
SAP Only
Internal
Use
Partner
Figure 129: Defining and Triggering Events Syntax
Within a class, instance events are defined using the EVENTS statement, while static events are defined using the CLASS-EVENTS statement.
266
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
Events can only have exporting parameters, which must be passed by value as a copy. A class or instance can trigger an event at runtime using the RAISE EVENT statement. Both instance events and static events can be triggered in instance methods. Only static events can be triggered in static methods. When an event is triggered, the handler methods that are registered to this event are called in sequence. Of course, these can trigger more events of their own.
Use
Partner
Only
Internal
If the event contains exporting parameters and you want to be able to address these syntactically, you must have specified the exporting parameters immediately after IMPORTING in the definition of the method. The handler method’s signature can consist of no more than the exporting parameters of the associated event. The parameters are typed by the handler method during the definition of the event. (“The object that triggers the event determines the protocol.”) In addition to the explicitly defined exporting parameters, the predefined importing parameter SENDER can always be listed. By using that parameter, you can place a reference to the event-trigger object into the handler method.
08-03-2004
© 2004 SAP AG. All rights reserved.
267
Only
Internal
Instance events or static methods can be defined within a class to handle events. To do so, you must specify the event (FOR EVENT) and the class or interface in which the event was defined (OF).
Partner
Use
SAP
SAP
Figure 130: Handling Events – Syntax
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Therefore, handler methods are usually called by triggered events (RAISE EVENT): However, they can be called explicitly as well (CALL METHOD).
Registering for Events
Use
Partner
When triggering instance events, you also have to specify what event the reaction will trigger. If instance methods are set to carry out the reaction, you also have to specify which instance(s) will perform the reaction.
Internal
Only
The definition of the handler method only specifies how and to which event of which class the method will react. At runtime, it needs to be determined which possible reactions will actually take place and when each of these will happen.
Internal
In this example, handler methods are defined for the event of the vehicle class, the car rental class, and the vehicle registration class. However, you can only predetermine which car rental instances and vehicle registration instances will react to which vehicle instance, and when they will do so. Registrations can also be revoked.
268
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
These specifications are collectively known as registration. The registration is always carried out using the trigger. When the event is triggered, the runtime uses the registrations of the trigger to determine which event handler methods need to be called.
Partner
Use
SAP
SAP
Figure 131: Registering Event Handling
BC401
Lesson: Events
Use
Partner
Only
Internal
Figure 132: Registering Event Handling – Syntax
SAP Use
The addition ACTIVATION ’X’ is optional. To revoke the registration,
Internal
use ACTIVATION space.
Only
You can register several methods with one SET-HANDLER statement:
SET HANDLER ref_handler_1->on_eventname_1 ... ref_handler_n->on_eventname_n FOR ... .
08-03-2004
© 2004 SAP AG. All rights reserved.
Partner
With instance events, FOR is followed by the reference to the object that triggers the event. Alternatively, you can also use the addition ALL INSTANCES. That way, you can also register objects that have not yet been created.
SAP
Events are registered using the SET HANDLER statement. Registration is only active at program runtime.
269
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
If multiple methods were registered to one event, then the sequence in which the event handler methods are called is not defined, that is, there is no guaranteed sequence in which the event handler methods are called. If a new event handler is registered within 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.
Use
Partner
Only
Internal
Internal
Objects that are registered for event handling are not deleted by the Garbage Collector if there are no remaining references to them.
270
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Every object or class that has defined events has an internal table: the handler table. All handler methods that are registered to the various events are listed within the table. For instance methods, the handler table also contains references to the registered objects.
Partner
Use
SAP
SAP
Figure 133: Registration/Deregistration – Handler Tables
BC401
Lesson: Events
Visibility Sections in Event Handling Events are also subject to the visibility concept and can therefore be either public, protected, or private. Event handler methods also have visibility attributes. •
The visibility of an event controls “who” may handle the event.
Only
•
PRIVATE Can only be handled within its class The visibility of a handler method controls the authorization required for registering the method, that is, the locations at which the SET HANDLER statement may be programmed.
SAP
SAP
PUBLIC Anywhere in the program PROTECTED Can be handled by users within that class or its subclasses
Only
Internal
Event handler methods can only have the same visibility or more restricted visibility than the events they refer to.
Partner
PRIVATE Can only be handled within its class
Use
Use
Partner
PROTECTED Can only be handled by users within that class or its subclasses
Internal
PUBLIC All
08-03-2004
© 2004 SAP AG. All rights reserved.
271
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
272
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
Exercise 16: Events in Superclasses Exercise Objectives
Business Example
Task 1:
Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_INTS_MAIN_B (where ## is your two-digit group number).
2.
Remove the calls of the method ADD_AIRPLANE from your main program. Note: The entry of an airplane reference into the airline’s list is to be event-controlled. Identify the class that is suitable for triggering the event and the classes that should be used for handling the event. Use your UML diagram if necessary. If applicable, illustrate the relationships in your UML diagram.
4.
Define the public event AIRPLANE_CREATED and trigger it in the class LCL_AIRPLANE using a suitable method.
5.
Change the method ADD_AIRPLANE in class LCL_CARRIER into a handler method for the event that you just defined. You will need to change both the signature and the implementation.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
273
Only
Internal
3.
Partner
Use
1.
SAP
SAP
Define an event for the creation of an airplane. Trigger and handle it so that the reference to the airplane is entered into the airline’s list of airplanes.
Use
Partner
Airplane and vehicle references are to be included in the airline and the car rental company’s lists. This process is to be event-controlled.
Internal
Only
After completing this exercise, you will be able to: • Define and trigger events • Handle events • Register event handling
Unit 3: Object-Oriented Concepts and Programming Techniques
6.
BC401
Register the new handler method, so that the airline enters every airplane that was created after itself in the list. Note: Although this model is unrealistic, we will use it for the time being. A different rule for entering the airplane can be created later.
7.
Observe the execution of the program in the ABAP Debugger.
1.
Remove the calls of the method ADD_VEHICLE from your main program.
2.
Define the event VEHICLE_CREATED and proceed as you did in the previous exercise.
Use
Only Partner
Define an event for the creation of a vehicle. Trigger and handle it so that the reference to the vehicle is entered into the car rental company’s list of vehicles.
Internal
Task 2:
SAP
SAP Only
Internal
Use
Partner
274
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
Solution 16: Events in Superclasses Task 1: Define an event for the creation of an airplane. Trigger and handle it so that the reference to the airplane is entered into the airline’s list of airplanes. Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_INTS_MAIN_B (where ## is your two-digit group number). a)
Partner
Note: The entry of an airplane reference into the airline’s list is to be event-controlled. a)
See the source code extract from the model solution
Identify the class that is suitable for triggering the event and the classes that should be used for handling the event. Use your UML diagram if necessary.
Use
a)
Define the public event AIRPLANE_CREATED and trigger it in the class LCL_AIRPLANE using a suitable method. a)
5.
See the source code extract from the model solution
Change the method ADD_AIRPLANE in class LCL_CARRIER into a handler method for the event that you just defined. You will need to change both the signature and the implementation. a)
See the source code extract from the model solution
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
275
Only
Internal
4.
Speak to your instructor if you have any questions.
Partner
If applicable, illustrate the relationships in your UML diagram.
SAP
3.
Remove the calls of the method ADD_AIRPLANE from your main program.
Use
2.
SAP
b)
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_EVES_MAIN_A
Internal
Only
1.
Unit 3: Object-Oriented Concepts and Programming Techniques
6.
BC401
Register the new handler method, so that the airline enters every airplane that was created after itself in the list. Note: Although this model is unrealistic, we will use it for the time being. A different rule for entering the airplane can be created later. a)
Only
Observe the execution of the program in the ABAP Debugger. a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Define an event for the creation of a vehicle. Trigger and handle it so that the reference to the vehicle is entered into the car rental company’s list of vehicles. 1.
Remove the calls of the method ADD_VEHICLE from your main program. a)
SAP
See the source code extract from the model solution
Define the event VEHICLE_CREATED and proceed as you did in the previous exercise.
Use
Speak to your instructor if you have any questions. See the source code extract from the model solution
Partner
a) b)
Result
Internal
Source code extract:
SAPBC401_EVES_MAIN_A sapbc401_eves_main_a.
Only
REPORT
TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2.
TYPE-POOLS icon. INCLUDE sapbc401_vehd_h. INCLUDE sapbc401_eves_a.
Continued on next page
276
© 2004 SAP AG. All rights reserved.
SAP
2.
Use
Partner
Task 2:
Internal
7.
See the source code extract from the model solution
08-03-2004
BC401
Lesson: Events
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,
Internal
Only
r_agency TYPE REF TO lcl_travel_agency.
START-OF-SELECTION. *########################
Partner
***** Create TRAVEL_AGENCY ************************************** CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’.
Use
***** Create CARRIER ******************************************** CREATE OBJECT r_carrier EXPORTING im_name = ’Smile&Fly Travel’.
SAP
SAP
***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345.
Partner
Use
***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US Hercules’ im_planetype = ’747-500’
Internal
im_cargo = 533.
***** insert business-parnter of agency into partner_list***********
Only
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.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
277
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
******* 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.
Internal
Only
***** insert business-parnter of agency into partner_list*********** r_agency->add_partner( r_rental ). ******* show attributes of all partners of travel_agency ******
SAPBC401_VEHD_H *&---------------------------------------------------------------------* *&
Include
SAPBC401_VEHD_H
*
*&---------------------------------------------------------------------* *---------------------------------------------------------------------*
Use
Partner
r_agency->display_agency_partners( ).
* it will use the interface lif_partners *---------------------------------------------------------------------* INTERFACE lif_partners.
SAP
SAP
* define client lcl_travel_agency
METHODS display_partner.
Use
"lif_partners
*---------------------------------------------------------------------* *
CLASS lcl_vehicle DEFINITION
Internal
*---------------------------------------------------------------------* CLASS lcl_vehicle DEFINITION.
Only
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.
Continued on next page
278
© 2004 SAP AG. All rights reserved.
Partner
ENDINTERFACE.
08-03-2004
BC401
Lesson: Events
EVENTS: vehicle_created. PRIVATE SECTION. DATA: make
TYPE string.
METHODS
init_make.
CLASS-DATA:
n_o_vehicles TYPE i.
ENDCLASS.
Internal
Only
"-------------------
"lcl_vehicle DEFINITION
*---------------------------------------------------------------------* *
CLASS lcl_vehicle IMPLEMENTATION
Partner
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
Use
CLASS lcl_vehicle IMPLEMENTATION. METHOD get_average_fuel. re_avgfuel = im_distance / im_fuel. "get_average_fuel
SAP
SAP
ENDMETHOD. METHOD constructor. make = im_make. ADD 1 TO n_o_vehicles. RAISE EVENT vehicle_created.
Use
Partner
ENDMETHOD.
"constructor
METHOD set_make. IF im_make IS INITIAL.
Internal
init_make( ).
" me->init_make( ). also possible
ELSE. make = im_make.
Only
ENDIF. ENDMETHOD.
"set_make
METHOD init_make. make = ’default make’. ENDMETHOD.
"init_make
METHOD get_make. ex_make = make. ENDMETHOD.
"get_make
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
279
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
METHOD display_attributes. WRITE: make. ENDMETHOD.
"display_attributes
METHOD get_count. re_count = n_o_vehicles. "get_count
ENDCLASS.
"lcl_vehicle IMPLEMENTATION
*---------------------------------------------------------------------* CLASS lcl_truck DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* ...
*---------------------------------------------------------------------*
SAP
CLASS lcl_bus DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
SAP
*
Use
Partner
*
Internal
Only
ENDMETHOD.
*---------------------------------------------------------------------* *
CLASS lcl_rental DEFINITION
*---------------------------------------------------------------------*
Internal
* *---------------------------------------------------------------------*
Partner
Use
...
CLASS lcl_rental DEFINITION.
Only
PUBLIC SECTION. "------------------METHODS:
constructor IMPORTING im_name TYPE string.
METHODS
add_vehicle FOR EVENT vehicle_created OF lcl_vehicle
METHODS
display_attributes.
IMPORTING sender.
INTERFACES: lif_partners. PRIVATE SECTION. "-------------------
Continued on next page
280
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
DATA: name TYPE string, vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS.
"lcl_rental DEFINITION
*---------------------------------------------------------------------* *
CLASS lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------* *
Internal
Only
*---------------------------------------------------------------------* CLASS lcl_rental IMPLEMENTATION. METHOD lif_partners~display_partner. display_attributes( ).
Partner
ENDMETHOD. METHOD
"lif_partners~display_partner
constructor.
name = im_name. ENDMETHOD.
METHOD
Use
SET HANDLER add_vehicle FOR ALL INSTANCES. "constructor
add_vehicle.
SAP
ENDMETHOD. METHOD
SAP
APPEND sender TO vehicle_list. "add_vehicle
display_attributes.
DATA: r_vehicle TYPE REF TO lcl_vehicle.
Use
WRITE:
Partner
WRITE: /
icon_transport_proposal AS ICON, name. ’ Here comes the vehicle list: ’. ULINE. ULINE.
LOOP AT vehicle_list INTO r_vehicle. r_vehicle->display_attributes( ).
ENDCLASS.
"display_attributes
Only
Internal
ENDLOOP. ENDMETHOD.
"lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------* *
CLASS lcl_travel_agency DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* ...
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
281
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
SAPBC401_EVES_A *&---------------------------------------------------------------------* *&
Include
SAPBC401_EVES_A
*
*&---------------------------------------------------------------------* *------------------------------------------------------------------* *
CLASS lcl_airplane DEFINITION
*
*------------------------------------------------------------------*
Internal
Only
CLASS lcl_airplane DEFINITION. PUBLIC SECTION. "--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
Partner
METHODS: constructor IMPORTING im_name
TYPE string
im_planetype TYPE saplane-planetype,
Use
display_attributes. CLASS-METHODS: display_n_o_airplanes.
SAP
SAP
EVENTS airplane_created.
PRIVATE SECTION. "---------------------------------------------IMPORTING im_type
TYPE saplane-planetype
EXPORTING ex_weight
TYPE s_plan_wei
ex_tankcap
Internal
DATA: name
Partner
Use
METHODS: get_technical_attributes
TYPE s_capacity.
TYPE string,
planetype TYPE saplane-planetype.
ENDCLASS.
Only
CLASS-DATA: n_o_airplanes TYPE i. "lcl_airplane DEFINITION
*------------------------------------------------------------------* *
CLASS lcl_airplane IMPLEMENTATION
*
*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
Continued on next page
282
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
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,
Internal
Only
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
Partner
IMPORTING ex_weight = weight ex_tankcap = cap ). WRITE: / ’Gewicht:’(003), weight, ENDMETHOD.
Use
’Tankkap:’(004), cap. "display_attributes
METHOD display_n_o_airplanes.
SAP
SAP
WRITE: /, / ’Number of airplanes: ’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. ENDMETHOD.
"display_n_o_airplanes
METHOD get_technical_attributes.
Partner
Use
SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) WHERE planetype = im_type. IF sy-subrc <> 0.
Internal
ex_weight = 100000. ex_tankcap = 10000. ENDIF.
ENDCLASS.
Only
ENDMETHOD.
"get_technical_attributes "lcl_airplane IMPLEMENTATION
*---------------------------------------------------------------------* *
CLASS lcl_cargo_plane DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
283
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
... *---------------------------------------------------------------------* *
CLASS lcl_passenger_plane DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* ... *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
Partner
CLASS lcl_carrier DEFINITION. PUBLIC SECTION. "----------------------------------------
Use
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
SAP
IMPORTING sender,
SAP
Internal
Only
*
display_airplanes, display_attributes. PRIVATE SECTION. "-----------------------------------
Use
TYPE string,
airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS.
"lcl_carrier DEFINITION
Internal
*---------------------------------------------------------------------* *
CLASS lcl_carrier IMPLEMENTATION
Partner
DATA: name
*---------------------------------------------------------------------*
Only
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.
Continued on next page
284
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
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( ). ENDMETHOD.
Internal
Only
ENDLOOP. "display_airplanes
METHOD constructor. SET HANDLER add_airplane FOR ALL INSTANCES.
Partner
name = im_name. ENDMETHOD.
"constructor
Use
METHOD get_name. ex_name = name. ENDMETHOD.
"lcl_carrier IMPLEMENTATION
SAP
SAP
ENDCLASS.
"get_name
Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
285
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
286
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
Exercise 17: Events in Interfaces (optional) Exercise Objectives
Only
Business Example
Partner
Task:
SAP Use
Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. (Where ## is your two-digit group number).
2.
Remove the calls of the method ADD_PARTNER from your main program.
3.
If necessary, examine your UML diagram. Which class or interface should define the event? Which class or interface should trigger it? Which class or interface should handle it?
Only
Internal
Note: The entry of a business partner reference into the travel agent’s list is to be event-controlled.
If applicable, illustrate the relationships in your UML diagram. 4.
Define the event PARTNER_CREATED and trigger it using a suitable method in the class that you selected.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
Partner
1.
SAP
Define an event for the creation of a business partner. Trigger and handle it so that the reference to the business partner is entered into the travel agent’s list of partners.
Use
Airline and car rental company references are to be entered into the travel agent’s list. This process is to be event-controlled. Be sure to create your program so that it can be easily extended to manage additional business partners of the travel agent in the future.
Internal
After completing this exercise, you will be able to: • Define events in interfaces • Trigger interface events in implementing classes • Handle interface events • Register event handling
287
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
5.
Change the method ADD_PARTNER in the class LCL_TRAVEL_AGENCY into a handler method for the event that you just defined. You will need to change both the signature and the implementation.
6.
Register the new handler method, so that the travel agent enters every business partner that was created after itself into the list.
Only
Observe the execution of the program in the ABAP Debugger.
Use
Partner
7.
Internal
Note: Although this model is unrealistic, we will use it for the time being. A different rule for entering the business partner can be created later.
SAP
SAP Only
Internal
Use
Partner
288
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
Solution 17: Events in Interfaces (optional) Task: Define an event for the creation of a business partner. Trigger and handle it so that the reference to the business partner is entered into the travel agent’s list of partners. Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. (Where ## is your two-digit group number). a)
Partner
3.
Remove the calls of the method ADD_PARTNER from your main program. Note: The entry of a business partner reference into the travel agent’s list is to be event-controlled. a)
See the source code extract from the model solution
SAP
If necessary, examine your UML diagram. Which class or interface should define the event? Which class or interface should trigger it? Which class or interface should handle it?
Use
Define the event PARTNER_CREATED and trigger it using a suitable method in the class that you selected. a)
5.
See the source code extract from the model solution
Change the method ADD_PARTNER in the class LCL_TRAVEL_AGENCY into a handler method for the event that you just defined. You will need to change both the signature and the implementation. a)
See the source code extract from the model solution
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
289
Only
Internal
4.
Speak to your instructor if you have any questions.
Partner
If applicable, illustrate the relationships in your UML diagram. a)
Use
2.
SAP
b)
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_EVES_MAIN_B
Internal
Only
1.
Unit 3: Object-Oriented Concepts and Programming Techniques
6.
BC401
Register the new handler method, so that the travel agent enters every business partner that was created after itself into the list. Note: Although this model is unrealistic, we will use it for the time being. A different rule for entering the business partner can be created later. a)
Only
Observe the execution of the program in the ABAP Debugger. a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Partner
Result Source code extract:
REPORT
Use
SAPBC401_EVES_MAIN_B sapbc401_eves_main_b.
SAP
SAP
TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2.
Use
DATA: r_vehicle TYPE REF TO lcl_vehicle,
Partner
Internal
TYPE-POOLS icon. INCLUDE sapbc401_vehd_i. INCLUDE sapbc401_eves_b.
r_truck TYPE REF TO lcl_truck, r_bus
TYPE REF TO lcl_bus,
Only
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. *########################
Continued on next page
290
Internal
7.
See the source code extract from the model solution
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
******* 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’.
Internal
Only
******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = ’MAN’ im_cargo = 45. ******* create truck ***************************************** CREATE OBJECT r_bus EXPORTING im_make = ’Mercedes’
Partner
im_passengers = 80. ******* create truck *****************************************
Use
CREATE OBJECT r_truck EXPORTING im_make = ’VOLVO’ im_cargo = 48.
***** Create CARRIER ********************************************
SAP
SAP
CREATE OBJECT r_carrier EXPORTING im_name = ’Smile&Fly Travel’.
***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’
Partner
Use
im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING
Internal
im_name = ’US Hercules’ im_planetype = ’747-500’ im_cargo = 533.
Only
******* show attributes of all partners of travel_agency ****** r_agency->display_agency_partners( ).
SAPBC401_VEHD_I *&---------------------------------------------------------------------* *&
Include
SAPBC401_VEHD_I
*
*&---------------------------------------------------------------------* *---------------------------------------------------------------------*
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
291
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
* define client lcl_travel_agency * it will use the interface lif_partners *---------------------------------------------------------------------* INTERFACE lif_partners. METHODS display_partner. EVENTS: partner_created. ENDINTERFACE.
"lif_partners
*---------------------------------------------------------------------* *
CLASS lcl_rental DEFINITION
*---------------------------------------------------------------------* * CLASS lcl_rental DEFINITION.
PUBLIC SECTION. "------------------METHODS:
constructor IMPORTING im_name TYPE string.
METHODS
add_vehicle for event vehicle_created of lcl_vehicle
SAP
METHODS
SAP
importing sender.
Use
Partner
*---------------------------------------------------------------------*
Internal
Only
...
display_attributes.
INTERFACES: lif_partners. PRIVATE SECTION. "-------------------
Use
vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS.
"lcl_rental DEFINITION
Internal
*---------------------------------------------------------------------* *
CLASS lcl_rental IMPLEMENTATION
Partner
DATA: name TYPE string,
*---------------------------------------------------------------------* *---------------------------------------------------------------------* CLASS lcl_rental IMPLEMENTATION. METHOD lif_partners~display_partner. display_attributes( ). ENDMETHOD. METHOD
"lif_partners~display_partner
constructor.
name = im_name. SET HANDLER add_vehicle FOR ALL INSTANCES.
Continued on next page
292
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
*
BC401
Lesson: Events
RAISE EVENT lif_partners~partner_created. ENDMETHOD. METHOD
"constructor
add_vehicle.
APPEND sender TO vehicle_list. ENDMETHOD.
METHOD
"add_vehicle
display_attributes.
Internal
Only
DATA: r_vehicle TYPE REF TO lcl_vehicle. skip 2. WRITE: / WRITE:
icon_transport_proposal AS ICON, name. ’ Here comes the vehicle list: ’. ULINE. ULINE.
LOOP AT vehicle_list INTO r_vehicle.
Partner
r_vehicle->display_attributes( ). ENDLOOP. ENDMETHOD.
"display_attributes
Use
ENDCLASS.
"lcl_rental IMPLEMENTATION
SAP
*
SAP
*---------------------------------------------------------------------* CLASS lcl_travel_agency DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
Partner
Use
CLASS lcl_travel_agency DEFINITION. PUBLIC SECTION.
Internal
"------------------METHODS:
constructor IMPORTING im_name TYPE string.
METHODS
add_partner FOR EVENT partner_created OF lif_partners IMPORTING sender.
Only
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
*---------------------------------------------------------------------*
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
293
Unit 3: Object-Oriented Concepts and Programming Techniques
BC401
* *---------------------------------------------------------------------* 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.
Internal
Only
r_partner->display_partner( ). ENDLOOP. ENDMETHOD. METHOD
"display_agency_partners
constructor.
Partner
name = im_name. SET HANDLER add_partner FOR ALL INSTANCES. ENDMETHOD.
Use
METHOD
"constructor
add_partner.
APPEND sender TO partner_list. "add_partner
*&---------------------------------------------------------------------*
"lcl_travel_agency IMPLEMENTATION
SAPBC401_EVES_B *&
Include
SAPBC401_EVES_B
*
*&---------------------------------------------------------------------* *---------------------------------------------------------------------*
Internal
*
CLASS lcl_carrier DEFINITION
*---------------------------------------------------------------------*
Partner
SAP
SAP
ENDCLASS.
Use
ENDMETHOD.
*
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,
Continued on next page
294
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
*---------------------------------------------------------------------*
BC401
Lesson: Events
display_airplanes, display_attributes. PRIVATE SECTION. "----------------------------------DATA: name
TYPE string,
airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS.
"lcl_carrier DEFINITION
*
Internal
Only
*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION
*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD lif_partners~display_partner.
Partner
display_attributes( ). ENDMETHOD.
"lif_partners~display_partner
Use
METHOD add_airplane. APPEND sender TO airplane_list. ENDMETHOD.
"add_airplane
SAP
SAP
METHOD display_attributes. SKIP 2. WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). "display_attributes
Partner
Use
ENDMETHOD.
METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane.
Internal
LOOP AT airplane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP.
Only
ENDMETHOD.
"display_airplanes
METHOD constructor. name = im_name. SET HANDLER add_airplane FOR ALL INSTANCES. RAISE EVENT lif_partners~partner_created. ENDMETHOD.
"constructor
METHOD get_name. ex_name = name.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
295
Unit 3: Object-Oriented Concepts and Programming Techniques
ENDMETHOD. ENDCLASS.
BC401
"get_name "lcl_carrier IMPLEMENTATION
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
296
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Events
Lesson Summary
Related Information
Use
Partner
... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.
Internal
Only
You should now be able to: • Define and trigger events • Handle events • Register and deregister event handling • Explain the key differences between explicit method calls and event-controlled method calls
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
297
Unit Summary
BC401
Unit Summary
Only Partner
Use SAP
SAP
Internal
You should now be able to: • Define inheritance relationships between classes • Redefine methods • Create narrowing cast assignments • Create widening cast assignments • Explain the concept of polymorphism with reference to interfaces • Use cast assignments with inheritance to make generic calls • Define and implement interfaces • Implement interface methods • Use interface references to make narrowing cast assignments • Use interface references to make widening cast assignments • Explain the term polymorphism with reference to interfaces • Use cast assignments with interfaces to make generic calls • Define and trigger events • Handle events • Register and deregister event handling • Explain the key differences between explicit method calls and event-controlled method calls
Only
Internal
Use
Partner
298
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Test Your Knowledge
Partner
What is the ABAP syntax required to redefine an inherited method in a local class?
3.
If you copy a subclass reference to a reference variable that is typed on the superclass (narrowing cast), which components can you access with this reference variable?
SAP
2.
Choose the correct answer(s).
Use
Redefined components of the superclass Newly defined components of the subclass Inherited components of the superclass Redefined components of the subclass
If a reference variable – typed on a superclass – contains a subclass reference and you copy this to a reference variable that is typed on the class (widening cast), which of the following components can you access with this reference variable? Choose the correct answer(s).
□ □ □ □
08-03-2004
A B C D
Redefined components of the superclass Newly defined components of the subclass Inherited components of the superclass Redefined components of the subclass
© 2004 SAP AG. All rights reserved.
299
Only
Internal
4.
A B C D
Partner
□ □ □ □
SAP
What is the ABAP syntax required to make a local subclass inherit from a superclass?
Use
1.
Internal
Only
Test Your Knowledge
Test Your Knowledge
BC401
Does an interface have an implementation part?
7.
If you copy an instance reference of a class, which implements an interface, to a reference variable that is typed on the interface (narrowing cast), what components can you access using this reference variable?
Partner
Only
6.
Choose the correct answer(s).
SAP Use
If a reference variable that is typed on an interface contains an instance reference of a class that implements this interface and you copy this to a reference variable that is typed on the class (widening cast), which of the following components can you access with this reference variable? Choose the correct answer(s).
300
□ □
A B
□ □
C D
The components of the interface The components from the class that are not defined on the interface All components of the class The components of the interface for which alias names have been defined
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
The components of the interface The components of the class that are not defined in the interface All components of the class The components of the interface for which alias names have been defined
Partner
8.
A B C D
SAP
□ □ □ □
Use
For what purpose do you use inheritance?
Internal
5.
BC401
Test Your Knowledge
9.
What is the statement for defining events?
Partner
11. With which statement would you define a handler method M_H for event E of class C?
Internal
Only
10. What is the statement for triggering events?
Use
Partner
Internal
SAP
SAP
Use
12. With which statement would you register handler method M_H of the reacting instance REF_H with the triggering instance REF_R?
13. Can events be defined in interfaces?
Only
14. Can events be triggered in interfaces?
08-03-2004
© 2004 SAP AG. All rights reserved.
301
Test Your Knowledge
BC401
Answers 1.
What is the ABAP syntax required to make a local subclass inherit from a superclass? Answer: Using the INHERITING FROM addition to the CLASS-DEFINITION statement
Only
2.
What is the ABAP syntax required to redefine an inherited method in a local class?
Refer to the relevant section of the lesson. If you copy a subclass reference to a reference variable that is typed on the superclass (narrowing cast), which components can you access with this reference variable?
SAP
SAP
3.
Answer: A, C Refer to the relevant section of the lesson.
Use Internal
If a reference variable – typed on a superclass – contains a subclass reference and you copy this to a reference variable that is typed on the class (widening cast), which of the following components can you access with this reference variable? Answer: A, B, C
5.
Only
Refer to the relevant section of the lesson. For what purpose do you use inheritance? Answer: Inheritance is how generalization/specialization relationships between classes are implemented in a program. Refer to the relevant section of the lesson.
302
© 2004 SAP AG. All rights reserved.
Partner
4.
Use
Partner
Answer: Using the REDEFINITION addition to the METHODS statement
Internal
Refer to the relevant section of the lesson.
08-03-2004
BC401
Test Your Knowledge
6.
Does an interface have an implementation part? Answer: No Refer to the relevant section of the lesson. If you copy an instance reference of a class, which implements an interface, to a reference variable that is typed on the interface (narrowing cast), what components can you access using this reference variable? Answer: A Refer to the relevant section of the lesson. If a reference variable that is typed on an interface contains an instance reference of a class that implements this interface and you copy this to a reference variable that is typed on the class (widening cast), which of the following components can you access with this reference variable? Answer: A, B, C, D
SAP
9.
SAP
Refer to the relevant section of the lesson. What is the statement for defining events?
Use
Partner
Answer: EVENTS Refer to the relevant section of the lesson.
Answer: RAISE EVENT Refer to the relevant section of the lesson. 11. With which statement would you define a handler method M_H for event E of class C? Answer: METHODS m_h FOR EVENT e OF c ... . Refer to the relevant section of the lesson.
© 2004 SAP AG. All rights reserved.
303
Only
Internal
10. What is the statement for triggering events?
08-03-2004
Use
Partner
8.
Internal
Only
7.
Test Your Knowledge
BC401
12. With which statement would you register handler method M_H of the reacting instance REF_H with the triggering instance REF_R? Answer: SET HANDLER ref_h->m_h FOR ref_r. Refer to the relevant section of the lesson.
Only
Internal
13. Can events be defined in interfaces? Answer: Yes
Partner
Refer to the relevant section of the lesson. 14. Can events be triggered in interfaces?
Use
Answer: No Refer to the relevant section of the lesson.
SAP
SAP Only
Internal
Use
Partner
304
© 2004 SAP AG. All rights reserved.
08-03-2004
Unit 4 Unit Overview
We will add a few more details (which were deliberately left out earlier) to your understanding of object-oriented programming concepts. These apply equally to local and global classes.
SAP
SAP
The third lesson is about possibilities for generating very specific global classes. In turn, this generation tool uses the Class Builder.
Unit Objectives
Use Internal
Describe the functions of the Class Builder Create global classes using the Class Builder Create interfaces using the Class Builder Reference global classes/interfaces in other Repository objects Create object-oriented transactions (transaction-code-type) Define abstract classes Define abstract methods Define final classes Define final methods Limit the visibility of the constructor Define friend relationships between classes Create persistent objects using the standard technique Load persistent objects using the standard technique Access components of persistent objects
© 2004 SAP AG. All rights reserved.
Only
08-03-2004
Partner
After completing this unit, you will be able to: • • • • • • • • • • • • • •
Use
Partner
The first lesson will introduce you to the Class Builder, a tool from the ABAP Workbench that you have not used before. You will focus on learning how to apply the techniques that you learned for local classes and interfaces to global classes and interfaces.
Internal
Only
Object-Oriented Repository Objects
305
Unit 4: Object-Oriented Repository Objects
BC401
Unit Contents
Only
Use
Partner
Internal
Lesson: Global Classes and Interfaces .......................................... 307 Procedure: Importing Local Classes and Interfaces ....................... 315 Procedure: Moving the Method Definition of a Global Class to an Implemented Interface ......................................................... 324 Procedure: Creating an Object-Oriented Transaction ..................... 330 Exercise 18: Global Classes .................................................. 331 Exercise 19: Global Interfaces................................................ 335 Exercise 20: Refactoring Assistant........................................... 347 Lesson: Special Object-Oriented Programming Techniques.................. 352 Exercise 21: Singleton Classes (Optional) .................................. 359 Exercise 22: Friendship Relationships (optional) .......................... 363 Lesson: Persistent Objects in ABAP Objects for SAP Web Application Server 6.20 .................................................................................. 369 Procedure: Creating Persistent Classes .................................... 373
SAP
SAP Only
Internal
Use
Partner
306
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Lesson: Global Classes and Interfaces Lesson Overview This lesson introduces you to a new tool in the ABAP Workbench: The Class Builder, which was integrated into SAP R/3 4.6A at the same time as ABAP Objects. We will examine its main functions and its integration into the ABAP Workbench – especially the Object Navigator.
Only
Lesson Objectives
SAP
Business Example
Use
Describe the functions of the Class Builder Create global classes using the Class Builder Create interfaces using the Class Builder Reference global classes/interfaces in other Repository objects Create object-oriented transactions (transaction-code-type)
Creating Global Classes and Interfaces
SAP
• • • • •
Use
Partner
After completing this lesson, you will be able to:
Internal
We will demonstrate the use of global standard classes using the powerful example of the SAP Grid Control.
Develop your classes and interfaces as actively integrated Repository objects.
Internal
On the other hand, global classes and global interfaces are individual Repository objects with all of the normal attributes (active integration, versioning, transport system, and so on). The namespace convention (Y*, Z*, or a special customer namespace) reflects the namespace of other Repository objects. Therefore, a special maintenance tool is available in the ABAP Workbench as of SAP R/3 4.6A: the Class Builder.
08-03-2004
© 2004 SAP AG. All rights reserved.
307
Only
In both cases, whether or not the source text is stored separately in include programs is irrelevant.
Partner
As with subroutines, local classes and interfaces can only be used within the program in which they are defined and implemented. The CLASS statement is a local, declarative statement in the program. Just as the TYPES statement defines local data types, the CLASS statement defines local object types.
Unit 4: Object-Oriented Repository Objects
BC401
SAP Use Internal
Do the same when creating global classes. The global class or global interface is then displayed in the Class Builder table in the editor area of the Object Navigator.
Partner
A dialog box asks you to make further specifications for the new class: Do not change the default specifications at this point. You will learn about the different settings and their effects later.
SAP
As with other Repository objects, the separate navigation area of the Object Navigator makes it the ideal development tool for all Repository objects. It also supports the Class Builder. As with other Repository objects, the easiest way to create a new global class is to use the context menu in the navigation area: First select the package node or select the class node itself within a package.
Use
Partner
Only
Internal
Figure 134: Creating Global Classes in the Object Navigator
Only
308
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Partner
Only
Internal
Figure 135: Definition of Attributes
SAP
SAP
You can use the input help when you are defining the type attributes. Remember to use meaningful short descriptions.
Use
Choose the Attributes tab to open the list of all attribute definitions in the class. You can define new attributes here.
Only
Internal
Use
Partner
Figure 136: Definition of Methods
08-03-2004
© 2004 SAP AG. All rights reserved.
309
Unit 4: Object-Oriented Repository Objects
BC401
Choose the Methods tab to open the list of all method definitions in the class. You can define new methods here. You can use the input help when defining the attributes. Remember to use meaningful short descriptions. There are separate editor windows for the signature and the implementation.
Internal
Only
Choose the Constructor button to define an instance constructor. The constructor name is chosen automatically and the selection possibilities in the editor window for the signature are restricted appropriately.
Use
Partner
Hint: Methods can be transported separately.
SAP
SAP
If you want to include a local interface in your global class, you must enter the name of the interface in the Interfaces tab. Once you have done that, all of the interface’s components automatically appear under the relevant tabs according to the naming convention and the interface resolution operator.
310
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Use
Partner
Figure 137: Including Global Classes
BC401
Lesson: Global Classes and Interfaces
In the method list, select a method and choose the Parameter button to go to the signature maintenance. You can define new formal parameters here.
SAP Use
Only
Internal
Partner
You can scroll between the signatures using the Previous Method and Next Method buttons. Choose the Methods button to return to the method list.
SAP
You can use the input help when defining the attributes. Remember to use meaningful short descriptions.
Use
Partner
Only
Internal
Figure 138: Definition of Method Signatures
Figure 139: Implementation of Methods
08-03-2004
© 2004 SAP AG. All rights reserved.
311
Unit 4: Object-Oriented Repository Objects
BC401
In the method list, select a method (double-click) or, if a method is already selected, choose the Source code button to go to the signature maintenance. You can implement the modifications here. You can display the method’s signature by choosing the relevant button.
SAP
SAP
Use
Partner
Only
Internal
Figure 140: Displaying the Method Definition
Use
Only
Internal
Partner
Choose Goto → Method definition if you want to change the attributes of your method during the implementation.
312
© 2004 SAP AG. All rights reserved.
08-03-2004
Lesson: Global Classes and Interfaces
Internal
Figure 141: Definition of Components Using the Navigation Area
Hint: Print selected portions of the source text using Class → Print or Method → Print.
SAP
SAP
You can also define attributes, methods, or events in the context menu in the Object Navigator’s navigation area. The attributes are then maintained in a dialog box, and not in the table we saw before.
Use
Partner
Only
BC401
Only
Internal
Use
Partner
Figure 142: The Class Builder Testing Environment
08-03-2004
© 2004 SAP AG. All rights reserved.
313
Unit 4: Object-Oriented Repository Objects
BC401
You can test active global classes: The class’s templates are allocated temporarily. Static ones are allocated immediately, instance components are allocated when you choose the Instance button. The system only lists the public components. Methods can be tested using the Call method icon.
1. 2.
Partner
3.
Select an event. Choose the Handler button. This registers a standard method for the event. Call a method in which the event trigger was implemented.
The event that was triggered and all of the exported actual parameters are displayed in a list.
Internal
Only
You can test the triggering of events in a class as follows:
Use
SAP
SAP Only
Internal
Use
Partner
314
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Importing Local Classes and Interfaces Use The procedure is an easy way to make global copies of local classes and local interfaces.
Only
In the initial screen of the Class Builder, choose Object type → Import → Local program classes.
3.
Enter the name of the main program and, if the local classes and interfaces were defined within include programs, select Expand Includes.
4.
Choose the button Display Classes/Interfaces.
5.
Enter names for the global classes and interfaces that you want to create. Remember the customer namespace, if applicable.
6.
Select the global classes and interfaces that you want to create and choose the Import button.
SAP
2.
SAP
In the SAP Easy Access Menu, choose Tools → ABAP Workbench → Development → Class Builder or call the transaction SE24.
Use
1.
Internal
Procedure
Partner
Caution: This function cannot be used from within the Object Navigator.
Only
Internal
Use
Partner
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
315
Unit 4: Object-Oriented Repository Objects
BC401
Use
Partner
Only
Internal
Figure 143: Importing a Local Program Class
Other Functions of the Class Builder
SAP
SAP
You set out the inheritance relationships between global classes in the Properties tab.
Only
Internal
Use
Partner
Figure 144: Defining an Inheritance Relationship
316
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Choose the Superclass button to specify an inheritance relationship. In this example, the subclass ZCL_CARGO_PLANE_00 will inherit from superclass ZCL_AIRPLANE_00.
SAP
SAP
Use
Partner
Only
Internal
Figure 145: Redefining an Inherited Method
Use
Only
Internal
Partner
To redefine an inherited method, select the relevant method in the list and choose the Redefine button. Alternatively, you can use the context menu in the navigation area.
08-03-2004
© 2004 SAP AG. All rights reserved.
317
BC401
Internal
Figure 146: Defining a Local Type
You can define local types in global classes. This includes local classes in particular.
SAP
All components of the global class have access to these local types, but they are encapsulated to the outside.
Use
Only
Internal
To edit the implementation parts of these local classes, choose the Impl. button. (Local Class Implementations).
Partner
The same applies for local interfaces in global classes.
SAP
Technically, you are not defining a class within a class, but a class that is local in the Repository object of the global class.
Use
Partner
Only
Unit 4: Object-Oriented Repository Objects
318
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Partner
Only
Internal
Figure 147: Structured Display of Inherited Components
SAP
SAP
Use
To improve your understanding of inheritance and interface components, you can set the flag Group by Classes and Interfaces in the User-Specific Settings for the Class Builder. The system will then display the components of the global class in a structure.
Only
Internal
Use
Partner
Figure 148: Sorting the Component Display of Global Classes
You can also sort all components by five criteria in three levels. To do this, display the appropriate dialog box by choosing the Sort button.
08-03-2004
© 2004 SAP AG. All rights reserved.
319
Unit 4: Object-Oriented Repository Objects
BC401
Inclusion of Global Classes Using the ABAP Editor Like other Repository objects, global classes and interfaces are included in the navigation area of the Object Navigator.
Use
Only
Internal
Partner
This way, the previously discussed advantages also apply to working with global classes and interfaces.
SAP
SAP
Use
Partner
Only
Internal
Figure 149: Separating the Navigation and Editing Areas of the Object Navigator.
320
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
SAP Use
Only
Internal
Partner
Alternatively, you can also choose the Pattern button. The CREATE-OBJECT statement is under ABAP Objects Pattern. You can generate the statement using the input help.
SAP
In the navigation area, select a class name and drag it to the editing area. This creates a CREATE OBJECT statement. You must then add the reference variable and the actual parameters, if applicable, to the statement.
Use
Partner
Only
Internal
Figure 150: Object Instantiation Using Drag&Drop
08-03-2004
© 2004 SAP AG. All rights reserved.
321
Unit 4: Object-Oriented Repository Objects
BC401
SAP
The Refactoring Assistant
Internal
Working with the tool is simple, since it is based on Drag&Drop dialogs.
322
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
In an ideal world, all classes, interfaces, and the associations between them would be modeled completely using UML diagrams before developers began implementing them. However, in some cases, the model needs to be adapted during the implementation phase. The Refactoring Assistant offers a range of user-friendly options for you to change Repository objects that you created previously. For example, you can use the Refactoring Assistant to move the components of a class within the inheritance hierarchy. For a complete list of the features in this tool, refer to the SAP Library.
Partner
Use
Alternatively, you can also choose the Pattern button. The CALL-METHOD statement is under ABAP Objects Pattern. You can generate the statement using the input help.
SAP
In the navigation area, select a method name and drag it to the editing area. This creates a CREATE METHOD statement. You must then add the reference variable and the actual parameters, if applicable, to the statement.
Use
Partner
Only
Internal
Figure 151: Method Calls Using Drag&Drop
BC401
Lesson: Global Classes and Interfaces
Use
Partner
Only
Internal
Figure 152: Working with the Refactoring Assistant
SAP Use
Only
Internal
Partner
Generally, you do not adjust the implementation of methods, since you cannot know how much you will need to alter object references after making these changes.
SAP
Hint: The Tool Info button opens the SAP Library article about the Refactoring Assistant. There you can also find the descriptions of the tool’s other abilities.
08-03-2004
© 2004 SAP AG. All rights reserved.
323
Unit 4: Object-Oriented Repository Objects
BC401
Change to editing mode and choose a global class that implements a global interface.
2.
Choose the Refactoring Assistant from the Utilities menu.
3.
In the tree structure that appears, open the folder for the method you want to move and for the “target” – in this case, the implemented interface.
4.
Move the method to the interface.
5.
Save your work. Caution: You might also need to, adapt statements calling the method in the source code.
7.
Activate both the class and the interface.
SAP Use
Only
Internal
Partner
The SAP Control Framework is a collection of global classes and interfaces that you can use to include SAP GUI controls in your ABAP Objects programs, regardless of the platform. We will show you how to use SAP standard classes effectively. We will demonstrate this with the widely used SAP Grid Control.
SAP
Use of SAP Standard Classes – Application Example
Use
Partner
1.
Internal
Only
Moving the Method Definition of a Global Class to an Implemented Interface
324
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
SAP Use
Only
Internal
Partner
SAP Grid Control contains a number of interactive standard functions that users of lists often need for example, print, export, and so on). As a developer, you have the option of hiding these standard functions. When required, you can also adapt the implementations to fit the needs of your application. You can also add your own functions to the application toolbar.
SAP
SAP Grid Control is a tool with which you can display non-hierarchical lists in a standardized form. The list data is displayed in tables. It is very easy to work with as only very few programming steps have to be carried out.
Use
Partner
Only
Internal
Figure 153: SAP Grid Control
08-03-2004
© 2004 SAP AG. All rights reserved.
325
Unit 4: Object-Oriented Repository Objects
BC401
SAP Use Internal
Let us take a common case as an example: Placing an SAP Grid Control in a screen area with a fixed size. You need to create an instance of each of the global classes CL_GUI_CUSTOM_CONTAINER and CL_GUI_ALV_GRID.
Partner
There are different types of container controls. However, they all encapsulate fundamental control functions, such as scroll bars.
SAP
The technical connection between screen control and application control is implemented using container controls. Generally, application controls (SAP Grid Control, tree control, picture control) always have to be embedded in a container control. In turn, the container control must be connected to the screen.
Use
Partner
Only
Internal
Figure 154: Including an SAP Grid Control Instance in a Dialog Program
Only
326
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
For normal display, the follow programming steps are sufficient:
SAP
2.
Use
If this table has a global row type, you can transfer the name of this global structure to the same method. Then the Grid Control instance automatically creates the field catalog.
08-03-2004
© 2004 SAP AG. All rights reserved.
327
Only
Internal
4.
Partner
3.
Use the fullscreen editor of the Screen Painter to define a custom control area on your screen. Create an instance of the class CL_GUI_CUSTOM_CONTAINER and transfer the name of the custom control area to the constructor. Create an instance of the class CL_GUI_GUI_ALV_GRID and transfer the reference to the custom control instance to the constructor. Call the method SET_TABLE_FOR_FIRST_DISPLAY of the grid control instance and transfer the internal standard table to it.
SAP
1.
Use
Partner
Only
Internal
Figure 155: Displaying Application Data Using an SAP Grid Control Instance
Unit 4: Object-Oriented Repository Objects
BC401
If you change the contents of the internal tables at runtime, you only need to call the method REFRESH_TABLE_DISPLAY in the relevant dialog step to refresh the display. Note: Extensive documentation about the SAP Control Framework is available. The SAP Library contains comprehensive descriptions of all classes and a complete tutorial.
Only
Individual elements of the SAP Control Framework are also covered in other courses.
Partner
OO Transactions as a Transaction Type
SAP Use
Partner Only
Internal
SAP
In transaction maintenance, you can create a transaction code as an OO transaction. This means that you link the transaction code either to the transaction service of the ABAP Objects services for persistent objects or to a public method in a global or local class of a program. When calling this type of OO transaction, which is linked to an instance method, the system automatically creates an instance of the class in its own internal session and then executes this instance method.
Use
SAP also offers a separate comprehensive course about dialog programming with the EnjoySAP controls. It covers all aspects, including complex programming techniques like Drag&Drop functions.
Internal
The Object Navigator also contains the Enjoy Demo Center, which makes it very easy to use standard template programs. You can find it under Environment → Examples → Control Examples.
328
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
•
The constructor cannot contain any IMPORTING parameters
•
ABAP list displays cannot be processed
Only
SAP Internal
Caution: Global classes in ABAP Objects cannot contain screen definitions. Thus, when you create a link to a global class, note the following:
Therefore, you may have to resort to methods in local program classes. Naturally, you can then use all the conventional dialog programming techniques.
08-03-2004
© 2004 SAP AG. All rights reserved.
Partner
Use
Thus, users now have the opportunity to call methods themselves in the usual way (through menu options, command field entries, and so on).
SAP
If the OO Transaction Model flag is set, the transaction code is linked to the transaction service of the ABAP Objects services. Conversely, if it is not set, you can call any method in a global or local class.
Use
Partner
Only
Internal
Figure 156: Creating an OO Transaction Code
329
Unit 4: Object-Oriented Repository Objects
BC401
Call the usual dialog for creating a transaction code and enter a short text.
2.
Choose the option Method of a Class (OO Transaction) as an Initial Object.
3.
Leave the OO Transaction Model flag unchecked if you want to link the transaction code to a normal instance method.
4.
Enter the Class Name and Method. Set the Local in Program flag and enter the program name, if you are using a local class.
5.
Save the transaction code.
Use
Partner
1.
Internal
Only
Creating an Object-Oriented Transaction
SAP
SAP Only
Internal
Use
Partner
330
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Exercise 18: Global Classes Exercise Objectives After completing this exercise, you will be able to: • Describe the functions of the Class Builder • Create global classes using the Class Builder
Only
Internal
Business Example Create a global class to represent hotels.
Create a global class for hotels. Create the global class ZCL_##_HOTEL. (Where ## is your two-digit group number).
2.
Define the following attributes in the class:
Use
of type STRING
as a private instance attribute
MAX_BEDS
of type I
as a private instance attribute
N_O_HOTELS
of type I
as a private static attribute
Partner
NAME
SAP
SAP
1.
Define the following methods in the class: CONSTRUCTOR
Instance constructor for setting the private attributes with the import parameters IM_NAME and IM_BEDS
DISPLAY_ATTRIBUTES
Instance method for displaying attributes in an ABAP list
DISPLAY_N_O_HOTELS
Static method to display the number of created hotel instances in an ABAP list
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
331
Only
Internal
Maintain the short texts. 3.
Use
Partner
Task 1:
Unit 4: Object-Oriented Repository Objects
BC401
Maintain the short texts.
Task 2: Check your work. 1.
Activate your class.
2.
Test your class in the Class Builder’s testing environment.
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
332
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Solution 18: Global Classes Task 1: Create a global class for hotels. 1.
Create the global class ZCL_##_HOTEL. (Where ## is your two-digit group number).
Only
Follow the processes as outlined in the relevant section of this lesson. Model solution: CL_HOTEL
Define the following attributes in the class: NAME
of type STRING
as a private instance attribute
MAX_BEDS
of type I
as a private instance attribute
N_O_HOTELS
of type I
as a private static attribute
SAP
SAP
2.
Use
Partner
Caution: If you copy from this model solution, you must remove the inheritance relationship to the global class CL_HOUSE and the global interface IF_PARTNERS.
Define the following methods in the class: CONSTRUCTOR
Instance constructor for setting the private attributes with the import parameters IM_NAME and IM_BEDS
DISPLAY_ATTRIBUTES
Instance method for displaying attributes in an ABAP list
DISPLAY_N_O_HOTELS
Static method to display the number of created hotel instances in an ABAP list
Use
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
333
Only
Internal
3.
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.
Partner
Maintain the short texts. a) b)
Internal
a) b)
Unit 4: Object-Oriented Repository Objects
BC401
Maintain the short texts. a) b)
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.
Task 2: Check your work. Activate your class. a) 2.
Test your class in the Class Builder’s testing environment. a) b)
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.
Use
Partner
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Internal
Only
1.
SAP
SAP Only
Internal
Use
Partner
334
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Exercise 19: Global Interfaces Exercise Objectives
Business Example
Task 1: 1.
If applicable, change the interface name in your UML diagram to ZIF_##_PARTNERS. (Where ## is your two-digit group number).
2.
Create the global interface ZIF_##_PARTNERS.
SAP
SAP
Create a global interface for generalized access to business partner instances.
Use
Task 2: Have your hotel class implement the interface. 1.
If necessary, add the class ZCL_##_HOTEL to your UML diagram. It should implement the DISPLAY_PARTNER interface method and trigger the instance event PARTNER_CREATED. Draw the corresponding relationships in your diagram.
2.
Include the interface in your hotel class. Continued on next page
© 2004 SAP AG. All rights reserved.
335
Only
Internal
Hint: Import the local interface from your program ZBC401_##_MAIN or from the previous lesson’s sample solution SAPBC401_EVES_MAIN_B.
Partner
Define the instance method DISPLAY_PARTNER and the instance event PARTNER_CREATED in the interface.
08-03-2004
Use
Partner
Add a hotel as a new business partner in your program for managing a travel agency’s business partners. Replace the local interface that you have been using with a global one, so that it can also be implemented by the global hotel class.
Internal
Only
After completing this exercise, you will be able to: • Describe the functions of the Class Builder • Create interfaces using the Class Builder • Reference global classes/interfaces in other Repository objects
Unit 4: Object-Oriented Repository Objects
BC401
3.
Implement the interface method in such a way that the hotel’s DISPLAY_ATTRIBUTES instance method is called.
4.
Trigger the instance event in a suitable instance method of the hotel class.
Task 3: Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_EVES_MAIN_B (where ## is your two-digit group number).
2.
Remove the definition of the local interface and adapt all places where it was used to suit the new global interface.
3.
Define a reference variable, specify your global hotel class as the type, and create an instance.
4.
Run your program. If you have done everything correctly, the simple instantiation should be enough to be able to display the hotel attributes on the list as well.
Use
Partner
1.
Internal
Only
Add an instance of your global hotel class to your main program.
SAP
SAP Only
Internal
Use
Partner
336
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Solution 19: Global Interfaces Task 1: Create a global interface for generalized access to business partner instances. 1.
If applicable, change the interface name in your UML diagram to ZIF_##_PARTNERS. (Where ## is your two-digit group number).
2.
Speak to your instructor if you have any questions.
Create the global interface ZIF_##_PARTNERS.
Hint: Import the local interface from your program ZBC401_##_MAIN or from the previous lesson’s sample solution SAPBC401_EVES_MAIN_B.
SAP
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions. Model solution: IF_PARTNERS
Task 2:
Use
If necessary, add the class ZCL_##_HOTEL to your UML diagram. It should implement the DISPLAY_PARTNER interface method and trigger the instance event PARTNER_CREATED. Draw the corresponding relationships in your diagram. a)
2.
Include the interface in your hotel class. a) b)
3.
Speak to your instructor if you have any questions.
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.
Implement the interface method in such a way that the hotel’s DISPLAY_ATTRIBUTES instance method is called. a) b)
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions. Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
337
Only
Internal
1.
Partner
Have your hotel class implement the interface.
SAP
a) b) c)
Use
Partner
Define the instance method DISPLAY_PARTNER and the instance event PARTNER_CREATED in the interface.
Internal
Only
a)
Unit 4: Object-Oriented Repository Objects
4.
BC401
Trigger the instance event in a suitable instance method of the hotel class. a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Task 3: Add an instance of your global hotel class to your main program. Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_EVES_MAIN_B (where ## is your two-digit group number). a)
2.
Remove the definition of the local interface and adapt all places where it was used to suit the new global interface. a)
Define a reference variable, specify your global hotel class as the type, and create an instance. a)
Run your program. If you have done everything correctly, the simple instantiation should be enough to be able to display the hotel attributes on the list as well. a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Internal
Result Source code extract:
Only
SAPBC401_CLSS_MAIN_A REPORT
sapbc401_clss_main_a.
TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2.
TYPE-POOLS icon.
Continued on next page
338
© 2004 SAP AG. All rights reserved.
Partner
Use
4.
See the source code extract from the model solution
SAP
SAP
3.
See the source code extract from the model solution
Use
Partner
b)
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_CLSS_MAIN_A
Internal
Only
1.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
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,
Internal
Only
r_carrier TYPE REF TO lcl_carrier, r_rental TYPE REF TO lcl_rental, r_agency TYPE REF TO lcl_travel_agency,
Partner
r_hotel TYPE REF TO cl_hotel.
START-OF-SELECTION. *########################
Use
******* create travel_agency *****************************************
SAP
SAP
CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’.
******* create rental ***************************************** CREATE OBJECT r_rental EXPORTING im_name = ’HAPPY CAR RENTAL’. ******* create truck *****************************************
Partner
Use
CREATE OBJECT r_truck EXPORTING im_make = ’MAN’ im_cargo = 45. ******* create truck ***************************************** CREATE OBJECT r_bus EXPORTING im_make = ’Mercedes’
Internal
im_passengers = 80.
******* create truck *****************************************
Only
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’
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
339
Unit 4: Object-Oriented Repository Objects
BC401
im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US Hercules’ im_planetype = ’747-500’ im_cargo = 533.
******* create hotel *****************************************
Internal
Only
CREATE OBJECT r_hotel EXPORTING im_name = ’Holiday Inn’ im_beds = 345.
******* show attributes of all partners of travel_agency ******
SAPBC401_VEHD_J *&---------------------------------------------------------------------* *&
Include
SAPBC401_VEHD_J
*
*&---------------------------------------------------------------------* *---------------------------------------------------------------------*
Use
Partner
r_agency->display_agency_partners( ).
*---------------------------------------------------------------------* *---------------------------------------------------------------------* *
CLASS lcl_vehicle DEFINITION
SAP
SAP
* work with the global interface if_hotel
*---------------------------------------------------------------------*
Use
*---------------------------------------------------------------------* *
CLASS lcl_truck DEFINITION
*---------------------------------------------------------------------*
Internal
* *---------------------------------------------------------------------*
Partner
...
...
*
CLASS lcl_bus DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* ... *---------------------------------------------------------------------* *
CLASS lcl_rental DEFINITION
*---------------------------------------------------------------------* *
Continued on next page
340
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
*---------------------------------------------------------------------*
BC401
Lesson: Global Classes and Interfaces
*---------------------------------------------------------------------* CLASS lcl_rental DEFINITION. PUBLIC SECTION. "------------------METHODS:
constructor IMPORTING im_name TYPE string.
METHODS
add_vehicle FOR EVENT vehicle_created OF lcl_vehicle
METHODS
display_attributes.
INTERFACES:
if_partners.
Internal
Only
IMPORTING sender.
PRIVATE SECTION. "------------------DATA: name TYPE string,
Partner
vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS.
"lcl_rental DEFINITION
*
Use
*---------------------------------------------------------------------* CLASS lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------* *
SAP
SAP
*---------------------------------------------------------------------* CLASS lcl_rental IMPLEMENTATION. METHOD if_partners~display_partner. display_attributes( ).
METHOD
"lif_partners~display_partner
Partner
Use
ENDMETHOD. constructor.
name = im_name. SET HANDLER add_vehicle FOR ALL INSTANCES.
METHOD
"constructor
Only
Internal
RAISE EVENT if_partners~partner_created. ENDMETHOD. add_vehicle.
APPEND sender TO vehicle_list. ENDMETHOD. METHOD
"add_vehicle
display_attributes.
DATA: r_vehicle TYPE REF TO lcl_vehicle. skip 2. WRITE: / WRITE:
icon_transport_proposal AS ICON, name. ’ Here comes the vehicle list: ’. ULINE. ULINE.
LOOP AT vehicle_list INTO r_vehicle.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
341
Unit 4: Object-Oriented Repository Objects
BC401
r_vehicle->display_attributes( ). ENDLOOP. ENDMETHOD.
"display_attributes
ENDCLASS.
"lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------* CLASS lcl_travel_agency DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
Partner
CLASS lcl_travel_agency DEFINITION. PUBLIC SECTION. "------------------constructor IMPORTING im_name TYPE string.
METHODS
add_partner FOR EVENT partner_created OF if_partners
Use
METHODS:
IMPORTING sender. METHODS
display_agency_partners.
SAP
SAP
PRIVATE SECTION. "------------------DATA: name TYPE string, partner_list TYPE TABLE OF REF TO if_partners. "lcl_travel_agency DEFINITION
*---------------------------------------------------------------------* *
CLASS lcl_travel_agency IMPLEMENTATION
*---------------------------------------------------------------------*
Internal
* *---------------------------------------------------------------------*
Partner
Use
ENDCLASS.
Internal
Only
*
CLASS lcl_travel_agency IMPLEMENTATION. DATA: r_partner TYPE REF TO if_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. METHOD
"display_agency_partners
constructor.
Continued on next page
342
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
METHOD display_agency_partners.
BC401
Lesson: Global Classes and Interfaces
name = im_name. SET HANDLER add_partner FOR ALL INSTANCES. ENDMETHOD.
METHOD
"constructor
add_partner.
APPEND sender TO partner_list. ENDMETHOD.
"add_partner "lcl_travel_agency IMPLEMENTATION
Internal
Only
ENDCLASS.
SAPBC401_CLSS_A *------------------------------------------------------------------*
Partner
*
INCLUDE SAPBC401_CLSS_A
*------------------------------------------------------------------* * work with interface if_partners
Use
* implement and raise events in lcl_carrier *------------------------------------------------------------------* *
CLASS lcl_airplane DEFINITION
*
*------------------------------------------------------------------*
SAP
SAP
... *---------------------------------------------------------------------* *
CLASS lcl_cargo_plane DEFINITION
*---------------------------------------------------------------------* ...
Partner
Use
*---------------------------------------------------------------------* *
CLASS lcl_passenger_plane DEFINITION
*---------------------------------------------------------------------* *
Internal
*---------------------------------------------------------------------* ... *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION
Only
*
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION. "---------------------------------------INTERFACES if_partners. METHODS: constructor IMPORTING im_name TYPE string,
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
343
Unit 4: Object-Oriented Repository Objects
BC401
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,
ENDCLASS.
"lcl_carrier DEFINITION
*---------------------------------------------------------------------* *
CLASS lcl_carrier IMPLEMENTATION
Partner
*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD if_partners~display_partner. ENDMETHOD.
Use
display_attributes( ). "lif_partners~display_partner
METHOD add_airplane.
SAP
SAP
APPEND sender TO airplane_list. ENDMETHOD.
Internal
Only
airplane_list TYPE TABLE OF REF TO lcl_airplane.
"add_airplane
METHOD display_attributes. SKIP 2.
Partner
Use
WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ).
Internal
ENDMETHOD.
"display_attributes
METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane.
Only
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 if_partners~partner_created. ENDMETHOD.
"constructor
Continued on next page
344
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
METHOD get_name. ex_name = name. ENDMETHOD. ENDCLASS.
"get_name "lcl_carrier IMPLEMENTATION
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
345
Unit 4: Object-Oriented Repository Objects
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
346
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Exercise 20: Refactoring Assistant Exercise Objectives After completing this exercise, you will be able to: • Describe the functions of the Class Builder • Create global classes using the Class Builder
Only
Include your global hotel class in a class hierarchy.
Define a global superclass for houses and have your hotel class inherit from it. 1.
If necessary, add the class ZCL_##_HOUSE to your UML diagram. (Where ## is your two-digit group number).
SAP
Create the global class ZCL_##_HOTEL and leave it empty.
3.
Define an inheritance relationship to make ZCL_##_HOUSE the superclass and ZCL_##_HOTEL the subclass.
Use
Task 2: 1.
Use the Refactoring Assistant to move the NAME attribute, the instance constructor, and the DISPLAY_ATTRIBUTES method into the class ZCL_##_HOUSE.
2.
Adapt the signature and the implementation of the instance constructor in the superclass.
3.
Adapt the implementation of the DISPLAY_ATTRIBUTES method in the superclass.
4.
Overload the instance constructor in the subclass.
5.
Redefine the DISPLAY_ATTRIBUTES method in the subclass. Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
347
Only
Internal
Move the general components of the ZCL_##_HOTEL class to the superclass.
Partner
2.
SAP
It will define the attribute NAME and the method DISPLAY_ATTRIBUTES. The class ZCL_##_HOTEL will inherit from it. Draw the relationships in your diagram.
Use
Partner
Task 1:
Internal
Business Example
Unit 4: Object-Oriented Repository Objects
6.
BC401
Observe the execution of the program in the ABAP Debugger. If you have done everything correctly, the display of the list should be the same as in the previous exercise.
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
348
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Solution 20: Refactoring Assistant Task 1: Define a global superclass for houses and have your hotel class inherit from it. 1.
If necessary, add the class ZCL_##_HOUSE to your UML diagram. (Where ## is your two-digit group number).
Only
a)
Create the global class ZCL_##_HOTEL and leave it empty. a) b) c)
3.
Define an inheritance relationship to make ZCL_##_HOUSE the superclass and ZCL_##_HOTEL the subclass. Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.
Task 2:
Use
Use the Refactoring Assistant to move the NAME attribute, the instance constructor, and the DISPLAY_ATTRIBUTES method into the class ZCL_##_HOUSE. a) b)
2.
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.
Adapt the signature and the implementation of the instance constructor in the superclass. a) b)
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
349
Only
Internal
1.
Partner
Move the general components of the ZCL_##_HOTEL class to the superclass.
SAP
a) b)
SAP
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions. Model solution: CL_HOUSE
Use
Partner
2.
Speak to your instructor if you have any questions.
Internal
It will define the attribute NAME and the method DISPLAY_ATTRIBUTES. The class ZCL_##_HOTEL will inherit from it. Draw the relationships in your diagram.
Unit 4: Object-Oriented Repository Objects
3.
Adapt the implementation of the DISPLAY_ATTRIBUTES method in the superclass. a) b)
4.
Only
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.
Observe the execution of the program in the ABAP Debugger. If you have done everything correctly, the display of the list should be the same as in the previous exercise. Carry out this step in the usual manner. Additional information is available in the SAP Library.
Use
a)
Internal
Partner
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.
Redefine the DISPLAY_ATTRIBUTES method in the subclass. a) b)
6.
Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.
Overload the instance constructor in the subclass. a) b)
5.
BC401
SAP
SAP Only
Internal
Use
Partner
350
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Global Classes and Interfaces
Lesson Summary
Only
Internal
You should now be able to: • Describe the functions of the Class Builder • Create global classes using the Class Builder • Create interfaces using the Class Builder • Reference global classes/interfaces in other Repository objects • Create object-oriented transactions (transaction-code-type)
Related Information
Use
Partner
... about this topic is available in the SAP Library.
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
351
Unit 4: Object-Oriented Repository Objects
BC401
Lesson: Special Object-Oriented Programming Techniques Lesson Overview
Internal
Only
In this lesson, you will complete your knowledge of object-oriented programming. The concepts introduced here apply to other object-oriented programming languages in the same or in a similar way. They can be used freely in ABAP Objects, both with local and global classes.
Lesson Objectives After completing this lesson, you will be able to:
Partner SAP
In such an abstract class, you can define abstract methods (amongst other things) – that is, you can leave their implementation open. If the subclass of that class is not abstract, the abstract methods must must be redefined there. That is, it must be implemented for the first time. Note: The relevant flag is in the Class Builder, in the Properties tab for that class or method.
352
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
You can prevent the instantiation of a class by using the ABSTRACT addition with the CLASS statement. Superclasses are a typical use for abstract classes, as they are not intended to be instantiated themselves, but their subclasses are.
Partner
Abstract Classes and Abstract Methods
You want to add special object-oriented programming techniques to your ABAP Objects implementations.
SAP
Business Example
Use
Define abstract classes Define abstract methods Define final classes Define final methods Limit the visibility of the constructor Define friend relationships between classes
Use
• • • • • •
Lesson: Special Object-Oriented Programming Techniques
Internal
Figure 157: Abstract Classes and Abstract Methods
References to such abstract classes can therefore be used for polymorphic access to subclass instances.
SAP
Only
Internal
Note: You will find the relevant flag in the Class Builder, under the Properties tab for that class or method.
Partner
You can prevent a method from being redefined by using the FINAL addition with the METHODS statement.
You can prevent a class from being inherited by using the FINAL addition with the CLASS statement.
SAP
Final Classes and Methods
Use
Static methods cannot be abstract because they cannot be redefined.
Use
Partner
Only
BC401
08-03-2004
© 2004 SAP AG. All rights reserved.
353
BC401
Internal
Figure 158: Final Classes and Methods
Thus, all methods of a final class are implicitly final. Therefore, you may not repeat the FINAL addition in the methods themselves.
Visibility of the Instance Constructor
Only
Internal
Note: The relevant flag is in the Class Builder, in the Properties tab for the relevant class.
Partner
Use
You can limit the instantiability of a class by using the CREATE addition with the CLASS statement.
SAP
SAP
Classes that are abstract and final should only contain static components.
Use
Partner
Only
Unit 4: Object-Oriented Repository Objects
354
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Special Object-Oriented Programming Techniques
SAP Use Internal
In some cases, classes have to work together so closely that one or both classes need access to the other’s protected and private components. Similarly, they need to be able to create instances of these other classes regardless of the visibility of the constructors. To avoid making these options available to all users, you can use the concept of class friendship. A class can provide friendship to other classes and interfaces (and hence all classes that implement the interface). This is the purpose of the FRIENDS addition of the CLASS statement and the Friends tab in the Class Builder. There, all classes and interfaces that grant friendship are listed.
08-03-2004
© 2004 SAP AG. All rights reserved.
355
Only
Friendship
Partner
Note: Regardless of that, the instance constructor must always be defined syntactically in the public section.
SAP
The variant CLASS ... DEFINITION CREATE PUBLIC ... is the standard case, that is the normal definition of a class. The other two variants limit the context in which the CREATE OBJECT statement can appear, as specified above. In that sense, they can determine the visibility section for the instance constructor.
Use
Partner
Only
Internal
Figure 159: Implicit Setting of the Instance Constructor’s Visibility
Unit 4: Object-Oriented Repository Objects
BC401
In principle, granting friendship is one-sided: A class granting friendship is not automatically a friend of its friends. If a class granting friendship wants to access the non-public components of a friend, this friend must also explicitly grant friendship to it.
Use
Partner
Only
Internal
Use
Only
Internal
Conversely, granting friendship is not inherited. A friend of a superclass is therefore not automatically a friend of its subclasses.
Partner
The friend property is inherited: Classes that inherit from friends and interfaces containing a friend (as a component interface) also become friends. Therefore, extreme caution is advised when granting friendship. The higher up a friend is in the inheritance tree, the more subclasses can access all components of a class that grants friendship.
SAP
SAP
Figure 160: Definition of Friendship Relationships
356
© 2004 SAP AG. All rights reserved.
08-03-2004
Lesson: Special Object-Oriented Programming Techniques
Internal
Figure 161: Areas of Use for Friendship Relationships
SAP
Classes Without Multiple Instantiation
Use
Only
Internal
Partner
There are many cases in which you need to prevent a class from being instantiated more than once per program context. This can be done using the aforementioned singleton concept:
SAP
A typical application of the friend relationship between classes is when methods that access the same data are distributed over several classes. This common data is, however, to be protected from access by “foreign” classes. In such friendships, you can make the class containing the data a singleton - that is, make sure it can only be instantiated once in each program instance.
Use
Partner
Only
BC401
08-03-2004
© 2004 SAP AG. All rights reserved.
357
Unit 4: Object-Oriented Repository Objects
BC401
Use
Partner
Only
Internal
Figure 162: Singleton Classes
SAP
A public static component could then make the reference to the class available to an external user.
SAP
The class is defined with the additions FINAL and CREATE PRIVATE and is instantiated using its static constructor.
Only
Internal
Use
Partner
358
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Special Object-Oriented Programming Techniques
Exercise 21: Singleton Classes (Optional) Exercise Objectives
Only
Business Example
Task 1:
Use
2.
Define the attribute R_SINGLETON for a reference to the singleton instance, making sure that the attribute has a suitable type.
3.
Define and implement the method GET_SINGLETON. It will provide the reference to the singleton instance.
4.
Ensure that the singleton instance is only created with the first call of the GET_SINGLETON method.
Task 2: Create a singleton instance.
08-03-2004
1.
Create the executable program ZBC401_##_MAIN_SPECIAL. (Where ## is your two-digit group number).
2.
Define a reference variable for the singleton instance.
3.
Create the singleton instance.
© 2004 SAP AG. All rights reserved.
359
Only
Internal
Create the global class ZCL_##_SINGLETON. (Where ## is your two-digit group number). When doing so, specify the necessary attributes for the singleton class.
Partner
1.
SAP
SAP
Create a singleton class.
Use
Partner
You need a class that can be instantiated no more than once per program context.
Internal
After completing this exercise, you will be able to: • Describe the functions of the Class Builder • Create global classes using the Class Builder • Define singleton classes • Instantiate singleton classes
Unit 4: Object-Oriented Repository Objects
BC401
Solution 21: Singleton Classes (Optional) Task 1: Create a singleton class. Create the global class ZCL_##_SINGLETON. (Where ## is your two-digit group number). When doing so, specify the necessary attributes for the singleton class. a) b)
Define the attribute R_SINGLETON for a reference to the singleton instance, making sure that the attribute has a suitable type. a)
3.
Define and implement the method GET_SINGLETON. It will provide the reference to the singleton instance.
SAP
Ensure that the singleton instance is only created with the first call of the GET_SINGLETON method. a)
Use the relevant sections of the lesson as a guide.
Task 2: Create a singleton instance. Create the executable program ZBC401_##_MAIN_SPECIAL. (Where ## is your two-digit group number). a) b) 2.
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_SPCS_MAIN_A
Define a reference variable for the singleton instance. a)
See the source code extract from the model solution
Continued on next page
360
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
1.
Partner
Use
Use the relevant sections of the lesson as a guide.
SAP
a) 4.
Use the relevant sections of the lesson as a guide.
Use
Partner
2.
Carry out this step in the usual manner. Additional information is available in the SAP Library. Specify the attributes as they are outlined in the relevant section of this lesson.
Internal
Only
1.
BC401
Lesson: Special Object-Oriented Programming Techniques
3.
Create the singleton instance. a)
See the source code extract from the model solution
Result Source code extract:
Internal
Only
SAPBC401_SPCS_MAIN_A REPORT sapbc401_spcs_main_a.
Partner
DATA: r_single TYPE REF TO cl_singleton.
START-OF-SELECTION. *########################
Use
r_single = cl_singleton=>get_singleton( ).
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
361
Unit 4: Object-Oriented Repository Objects
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
362
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Special Object-Oriented Programming Techniques
Exercise 22: Friendship Relationships (optional) Exercise Objectives
Only Partner
Business Example Create a global class for travel agents that can access the private attributes of a singleton class that is a friend. The class must buffer flight connection data.
Use
Task 1: Buffer the flight data in a singleton class.
SAP
Hint: You can use the global table kind TY_CONNECTIONS. Make sure that this internal table is filled with data from the transparent table SPFLI, but only when the singleton instance is accessed for the first time.
Task 2: Create a global class for travel agencies and have the singleton class grant it friendship. Enable the new global class to pass flight connection data to a user. 1.
Create the global class ZCL_##_AGENCY. (Where ## is your two-digit group number). Have the singleton class grant it friendship.
2.
Define the private instance attribute NAME of type STRING. Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
363
Only
Internal
2.
Partner
Use
Add the attribute CONNECTION_LIST for the flight connection data to your ZCL_##_SINGLETON singleton class, making sure that the right attributes have been set for the flight connection data. (Where ## is your two-digit group number).
SAP
1.
Internal
After completing this exercise, you will be able to: • Describe the functions of the Class Builder • Create global classes using the Class Builder • Define friendship relationships • Access private attributes of a friendship-granting class
BC401
3.
Define and implement an instance constructor that sets the private attribute NAME.
4.
Define the public instance method GET_CONNECTION with the following signature: Kind
Reference type
IM_CARRID
Importing
S_CARR_ID
IM_CONNID
Importing
S_CONN_ID
EX_CONNECTION
Exporting
SPFLI
Implement your method in such a way that the additional data for selected flight connections can be read and exported from the private internal table of the singleton instance using single-record access. If the required data record does not exist, it is enough if you display a message in the ABAP list.
SAP
Task 3:
Use Internal
Add a reference variable for a travel agency instance to the executable program ZBC401_##_MAIN_SPECIAL that you created earlier. (Where ## is your two-digit group number).
2.
Create a travel agency instance.
3.
Call the GET_CONNECTION method for an existing flight connection from the flight data model (for example, LH/0400) and display the data in the ABAP list.
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
364
1.
Partner
Create a travel agency instance and have it provide the data of a flight connection.
SAP
Hint: If required, use the statement CLASS ... DEFINITION LOAD to syntactically enable direct access to the static components of the class.
Use
Partner
5.
Name
Internal
Only
Unit 4: Object-Oriented Repository Objects
BC401
Lesson: Special Object-Oriented Programming Techniques
Solution 22: Friendship Relationships (optional) Task 1: Buffer the flight data in a singleton class. Add the attribute CONNECTION_LIST for the flight connection data to your ZCL_##_SINGLETON singleton class, making sure that the right attributes have been set for the flight connection data. (Where ## is your two-digit group number).
a) b) 2.
Make sure that this internal table is filled with data from the transparent table SPFLI, but only when the singleton instance is accessed for the first time.
SAP
a)
SAP
Speak to your instructor if you have any questions. Model solution: CL_SINGLETON
Speak to your instructor if you have any questions.
Task 2:
Use
a) b) 2.
Define the private instance attribute NAME of type STRING. a)
3.
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: CL_AGENCY
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Define and implement an instance constructor that sets the private attribute NAME. a)
Carry out this step in the usual manner. Additional information is available in the SAP Library. Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
365
Only
Internal
Create the global class ZCL_##_AGENCY. (Where ## is your two-digit group number). Have the singleton class grant it friendship.
Partner
Create a global class for travel agencies and have the singleton class grant it friendship. Enable the new global class to pass flight connection data to a user. 1.
Use
Partner
Hint: You can use the global table kind TY_CONNECTIONS.
Internal
Only
1.
Unit 4: Object-Oriented Repository Objects
Define the public instance method GET_CONNECTION with the following signature: Name
Kind
Reference type
IM_CARRID
Importing
S_CARR_ID
IM_CONNID
Importing
S_CONN_ID
EX_CONNECTION
Exporting
SPFLI
a)
Implement your method in such a way that the additional data for selected flight connections can be read and exported from the private internal table of the singleton instance using single-record access. If the required data record does not exist, it is enough if you display a message in the ABAP list.
SAP Use
Create a travel agency instance and have it provide the data of a flight connection. Add a reference variable for a travel agency instance to the executable program ZBC401_##_MAIN_SPECIAL that you created earlier. (Where ## is your two-digit group number). a) 2.
See the source code extract from the model solution
Create a travel agency instance. a)
See the source code extract from the model solution
Continued on next page
366
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
1.
Use the relevant sections of the lesson as a guide.
Partner
Task 3:
Internal
a)
SAP
Hint: If required, use the statement CLASS ... DEFINITION LOAD to syntactically enable direct access to the static components of the class.
Use
Partner
5.
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Internal
Only
4.
BC401
BC401
Lesson: Special Object-Oriented Programming Techniques
3.
Call the GET_CONNECTION method for an existing flight connection from the flight data model (for example, LH/0400) and display the data in the ABAP list. a)
See the source code extract from the model solution
Result
Internal
Only
Source code extract:
SAPBC401_SPCS_MAIN_B REPORT
sapbc401_spcs_main_b.
Partner
DATA: r_single TYPE REF TO cl_singleton, r_agency TYPE REF TO cl_agency, rec TYPE spfli.
Use
START-OF-SELECTION.
SAP Use
r_agency->get_connection( EXPORTING im_carrid = ’LH’
WRITE: / rec-carrid, rec-connid, rec-cityfrom, rec-cityto.
SAP
r_single = cl_singleton=>get_singleton( ).
Internal
*########################
CREATE OBJECT r_agency EXPORTING im_name = ’Agency’.
Partner
im_connid = ’0400’ IMPORTING ex_connection = rec ).
Only
08-03-2004
© 2004 SAP AG. All rights reserved.
367
Unit 4: Object-Oriented Repository Objects
BC401
Lesson Summary
Only
Related Information
Use
Partner
... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.
Internal
You should now be able to: • Define abstract classes • Define abstract methods • Define final classes • Define final methods • Limit the visibility of the constructor • Define friend relationships between classes
SAP
SAP Only
Internal
Use
Partner
368
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Persistent Objects in ABAP Objects for SAP Web Application Server 6.20
Lesson: Persistent Objects in ABAP Objects for SAP Web Application Server 6.20 Lesson Overview
Only
Lesson Objectives • • •
Create persistent objects using the standard technique Load persistent objects using the standard technique Access components of persistent objects
Use
Partner
After completing this lesson, you will be able to:
SAP
You need to use the new Object Services of the SAP Web AS 6.20 in your ABAP Objects programs.
Use
In principle, ABAP programs work with data and objects that are valid at runtime. They are transient – that is, temporary – and disappear when the program ends. If this data is to be stored permanently and independently of the program – that is, persistently – it must be stored in a database. (Theoretically, you could also use files at operating system level.)
Partner
Persistence Services
SAP
Business Example
Only
Internal
Internal
This lesson shows how you can use ABAP Objects to write instances of global classes to database tables, permanently and independently of a specific program. After introducing the concepts involved and how they can be applied in the SAP Web AS 6.20, we will then present a detailed description of the standard process for application developers.
08-03-2004
© 2004 SAP AG. All rights reserved.
369
Unit 4: Object-Oriented Repository Objects
BC401
Partner
Only
Internal
SAP Internal
To ensure that the instances of persistent classes are unique, they should contain key attributes. These can be typed either as worldwide unique identification numbers (object GUID) or as semantic keys.
370
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
To use the Persistence Service for objects, their types must be created as persistent classes in the Class Builder. The term persistent class indicates that the instances of the class and their state are managed by the Persistence Service. (Global classes as such are generally persistent. The question is whether or not their instances are also persistent.)
Partner
Persistent Objects as Instances of Special Global Classes
SAP
The Persistence Services are used with object-oriented programming techniques. In this way, you can simulate an object-oriented database management system using a relational database management system and ABAP Objects.
Use
For this purpose, the Persistence Services for ABAP Objects were introduced in the SAP Web AS 6.10. On request, these services write the current attribute values of objects defined as persistent to the associated transparent tables. On receiving another request, they import these values from the tables and write the attributes to an object previously defined as persistent. When doing this, the Persistence Services use the ABAP Open SQL interface.
Use
Figure 163: Simulation of an Object-Oriented Database Management System
BC401
Lesson: Persistent Objects in ABAP Objects for SAP Web Application Server 6.20
Only Partner
Use
In the program, you need to define a reference variable with the type of the class actor and fill it with the reference from the static attribute AGENT. You can then create a new instance of the persistent class using its method CREATE_PERSISTENT. Its interface is created from the definition of the key attributes of the persistent class. If the object already exists, it raises the class-based exception CX_OS_OBJECT_EXISTING. By default, the data is saved by asynchronous update. This process must be started using the COMMIT WORK statement. Thus, the instances of the persistent class do not become persistent objects until after that point.
Internal
When you create a persistent class ZCL_, the Class Builder automatically generates methods for getting and setting its attributes. In addition, other Repository objects are also generated, including the class actor (also known as the class agent) ZCA_. Programs must call the methods of this class to manage the instances of persistent classes – that is, persistent objects. This class also performs the actual database access. It automatically inherits the required methods from the basis class ZCB_. These methods can be redefined if necessary – for example, to extend database accesses. The class actor is a singleton instance and has a friendship relationship with the persistent class.
SAP
SAP Only
Internal
Use
Partner
Figure 164: Generating and Writing to Persistent Objects
08-03-2004
© 2004 SAP AG. All rights reserved.
371
Unit 4: Object-Oriented Repository Objects
BC401
You can load persistent objects (back) into a program using the GET_PERSISTENT method. When doing so, you must pass the key values to the interface parameters so that the object can be uniquely reconstituted. If the program could not find the object, it raises the class-based exception CX_OS_OBJECT_NOT_FOUND.
Use
Partner
Only
Internal
SAP
SAP
Figure 165: Reading Persistent Objects
Only
Internal
Use
Partner
372
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Persistent Objects in ABAP Objects for SAP Web Application Server 6.20
1.
Model the class for your persistent objects.
2.
Find or create a suitable transparent table that has a field for each attribute of the class. If necessary, adapt the attributes of the class to match the technical field attributes of the transparent table. Each key attribute of the class must match a primary key field in the table and the other way round.
3.
In the Class Builder, create a persistent class as described in the SAP Library. Define the persistence mapping to the table.
Use
Partner
Internal
Only
Creating Persistent Classes
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
373
Unit 4: Object-Oriented Repository Objects
BC401
Lesson Summary You should now be able to: • Create persistent objects using the standard technique • Load persistent objects using the standard technique • Access components of persistent objects
Internal
Only
Related Information
Use
Partner
... is available in the SAP Library.
SAP
SAP Only
Internal
Use
Partner
374
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Unit Summary
Unit Summary
Use
Only Partner
Internal
You should now be able to: • Describe the functions of the Class Builder • Create global classes using the Class Builder • Create interfaces using the Class Builder • Reference global classes/interfaces in other Repository objects • Create object-oriented transactions (transaction-code-type) • Define abstract classes • Define abstract methods • Define final classes • Define final methods • Limit the visibility of the constructor • Define friend relationships between classes • Create persistent objects using the standard technique • Load persistent objects using the standard technique • Access components of persistent objects
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
375
Unit Summary
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
376
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Test Your Knowledge
Test Your Knowledge 1.
Which of the following statements are correct?
Partner
F
□
G
□
H
□
I
For a user to be able to execute an object-oriented program, you always need to supply a module pool program or a function group program. Otherwise, there is nowhere for the CREATE OBJECT statement to create the instance. Determine whether this statement is true or false.
Partner
SAP
□
You can create function modules using the Class Builder. A global class can contain a local class. A global interface can contain a local interface. A global class can contain a local interface. Nested definition of classes is when a local class is within a global class. Using the Class Builder, a local class can be converted into a global class. A local class can be copied using the Class Builder. The copy is then a global class. You can use the Refactoring Assistant to move the methods to a different class within an inheritance hierarchy. You can use the Refactoring Assistant to design model diagrams.
SAP
Use
A B C D E
Use
2.
□ □ □ □ □
Internal
Only
Choose the correct answer(s).
True False
Only
Internal
□ □
08-03-2004
© 2004 SAP AG. All rights reserved.
377
Test Your Knowledge
3.
BC401
Which of the following statements are correct? Choose the correct answer(s).
Only Partner
A non-abstract class can contain abstract methods. An abstract class contains no implementations. An abstract method contains no implementations. Final classes cannot be superclasses within a class hierarchy. A final method must be redefined. Final classes can contain non-final methods. A friend of a class is also a friend of its subclasses. The subclasses of a class’s friend are also the class’s friend. The visibility of an instance constructor can be limited. A private instance constructor (instantiation only by the class itself) can be defined in the private section.
For what purpose is the technique of persistent objects used?
Use
□
C
□
D
□
E
To encapsulate database accesses in an object-oriented manner. Exclusively to implement database accesses in an object-oriented context (Open SQL is not allowed in ABAP Objects). To apply an object-oriented model for business objects (creating, using, writing, and reading business objects). To extend SAP standard classes (which have generally been migrated in the SAP Web AS 6.10). For authorization checks (accessing components of persistent objects is only possible using agents).
Only
Internal
A B
Partner
□ □
SAP
SAP
Choose the correct answer(s).
Use
4.
A B C D E F G H I J
Internal
□ □ □ □ □ □ □ □ □ □
378
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Test Your Knowledge
Answers 1.
Which of the following statements are correct? Answer: B, D, G, H Refer to the relevant section of the lesson.
Only
For a user to be able to execute an object-oriented program, you always need to supply a module pool program or a function group program. Otherwise, there is nowhere for the CREATE OBJECT statement to create the instance.
The creation of the first instance and the call of the first method can be realized using an OO transaction. However, certain restrictions apply. Refer to the relevant section of the lesson. Which of the following statements are correct?
SAP
SAP
3.
Answer: C, D, H, I
Partner
Use
Refer to the relevant section of the lesson. 4.
For what purpose is the technique of persistent objects used? Answer: A, C Refer to the relevant section of the lesson.
Only
Internal
Use
Partner
Answer: False
Internal
2.
08-03-2004
© 2004 SAP AG. All rights reserved.
379
Unit Summary
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
380
© 2004 SAP AG. All rights reserved.
08-03-2004
Unit 5 Only
Unit Overview
Partner SAP
SAP
Unit Objectives After completing this unit, you will be able to:
Use Internal
Unit Contents Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20 .......................................................................... 383
08-03-2004
© 2004 SAP AG. All rights reserved.
381
Only
Create exception classes Trigger class-based exceptions in ABAP Objects programs Propagate class-based exceptions in ABAP Objects programs Handle class-based exceptions in ABAP Objects programs Map class-based exceptions in ABAP Objects programs to each other Dynamically create objects Dynamically access class and object components Define field symbols Define data references Dereference data references Dynamically create data objects Ascertain the attributes of data objects at runtime
Partner
• • • • • • • • • • • •
Use
This last unit will look at the new exception concept and the language’s features for dynamic programming, thereby demonstrating how closely the procedural and object-oriented parts of ABAP Objects are interlocked. To fully exploit the available functions, you must therefore program in a partially object-oriented manner, even if you use the concepts in purely procedural program units.
Internal
Exception Handling and Dynamic Programming
Unit 5: Exception Handling and Dynamic Programming
BC401
Procedure: Define global exception classes ................................ 389 Exercise 23: Class-Based Exceptions ....................................... 401 Exercise 24: Mapping Exceptions to Each Other .......................... 411 Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20 ............................................................ 422 Exercise 25: Type Casting with Data Elements (Optional)................ 443 Exercise 26: Creating Data Objects at Runtime............................ 449
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
382
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20 Lesson Overview
Lesson Objectives After completing this lesson, you will be able to:
Partner
Create exception classes Trigger class-based exceptions in ABAP Objects programs Propagate class-based exceptions in ABAP Objects programs Handle class-based exceptions in ABAP Objects programs Map class-based exceptions in ABAP Objects programs to each other
SAP
You need to use the new exceptions concept of the SAP Web AS 6.20 in your ABAP Objects programs.
Use Internal
08-03-2004
© 2004 SAP AG. All rights reserved.
383
Only
We use the term exception to refer to a situation that arises while a program is being executed, where there is no point in continuing to run the program in the normal way. The SAP Web AS 6.10 introduced a new ABAP Objects exception concept, parallel to the existing concept. Exceptions and exception handling are now based on classes. This concept includes the concepts that preceded it but also enhances (and thus replaces) them.
Partner
The Concept of Class-Based Exception Handling
SAP
Business Example
Use
• • • • •
Internal
Only
This lesson provides a comprehensive introduction to the new class-based exception concept in ABAP Objects. The main properties and the activities you need to perform are presented in detail and then applied in practical examples.
Unit 5: Exception Handling and Dynamic Programming
BC401
SAP Use
You can define exception classes yourself, but there is already a range of predefined exception classes in the system – particularly for exceptions in the runtime environment. Generally you create exception classes globally in the Class Builder, but you can also define local exception classes within a program or global class. The use of class-based exceptions is not limited to object-oriented contexts. Class-based exceptions can be raised and handled in all processing blocks. In particular, the catchable runtime errors used previously can now be handled as class-based exceptions. If a class-based exception is raised, 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.
384
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
When handling an exception, you can have it raise new exceptions and thus create a chain of exceptions. Thus, in special cases, you can catch a runtime exception and then have it raise an exception of its own.
Partner
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 contain information about the error situation.
SAP
Class-based exceptions are raised either using the ABAP statement RAISE EXCEPTION or by the ABAP runtime environment. Division by zero, for example, would be an example of the latter.
Use
Partner
Only
Internal
Figure 166: An Overview of the Class-Based Exception Concept
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
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.
Use
Partner
Only
Internal
The way in which exception classes are assigned to one of these three paths in the hierarchy defines how the associated exceptions are propagated. (This will be discussed in more detail later in this unit.)
Use
New exception classes inherit from one of these superclasses, so that other components can be added. These are usually individual exception texts. You can assign several texts to each class. The IDs assigned to them are created by the Class Builder as identically-named static constants. You can then specify which text is to be used when an exception is raised by passing one of these constants to the import parameter TEXTID of the instance constructor.
08-03-2004
© 2004 SAP AG. All rights reserved.
385
Only
Internal
The CX_ROOT class provides some predefined methods that are inherited by all exception classes: The GET_SOURCE_POSITION method returns the name of the main program and (if relevant) the names of the include program and the line number in the source code where the exception occurred. The GET_TEXT method returns an exception text in the form of a string.
Partner
In the SAP standard system, the names of all exception classes start with CX_.
SAP
SAP
Figure 167: Exception Classes: The Inheritance Hierarchy
Unit 5: Exception Handling and Dynamic Programming
BC401
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 BCD_ZERODIVIDE if the program catches a CX_SY_ZERODIVIDE exception (division by zero). If the exception is not listed, a runtime error occurs. An exception can only be handled if the statement that could raise it is enclosed in a TRY-ENDTRY block. The exception is then handled using the CATCH statement in the TRY-ENDTRY block.
Use
Partner
Only
Internal
Internal
A CATCH block contains the exception handler that is executed if a specified exception has occurred in the associated TRY-ENDTRY block. You can specify any number of exception classes to the CATCH statement. In this way, you define an exception handler for all these exception classes and their subclasses. Like all ABAP control structures, TRY-ENDTRY structures can be nested to any depth. Thus the TRY block, CATCH blocks, and the CLEANUP block in particular can contain complete TRY-ENDTRY blocks themselves.
386
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
The TRY block contains the set of statements that 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 block and then step by step outwards in all the enclosing TRY-ENDTRY blocks. 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 propagate the exception to the calling program. (This will be discussed in more detail later.)
Partner
Use
SAP
SAP
Figure 168: Structure of a TRY-ENDTRY Block
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
After an exception occurs, the system searches through the listed exception handlers in the order specified. It then executes the first exception handler whose CATCH statement contains the relevant exception class or one of its superclasses.
In the following sections, we will focus on global exception classes that are handled locally. Remember, you can also use local exception classes handled locally or global exception classes handled in methods of other global classes.
There are two special features to note in the following example: Firstly, we will simply instantiate a standard exception class, rather than define a new one. Secondly, the exception will be raised by the runtime system as the result of an error, rather than by a procedure.
Use
Partner
Example: Handling a Predefined Exception
Internal
Only
In some cases, the system cannot find a handler for an exception within a specific TRY-ENDTRY block but the exception is handled in a surrounding TRY-ENDTRY block or propagated to a calling program. If this occurs, a CLEANUP block is executed before leaving the TRY-ENDTRY block.
SAP
SAP Only
Internal
Use
Partner
Figure 169: Example Syntax for Handling Predefined Exceptions
In the above calculation, if the value range for data type I is exceeded, the runtime system raises the exception CX_SY_ARITHMETIC_OVERFLOW. This exception is handled in the implemented CATCH block. The reference to the appropriate instance is stored in the data object REF_EXC. The handler
08-03-2004
© 2004 SAP AG. All rights reserved.
387
Unit 5: Exception Handling and Dynamic Programming
BC401
can then access the instance’s exception text using the functional method GET_TEXT. The text is stored in the data object TEXT with the type STRING and then displayed as an information message. Note: The MESSAGE statement was extended in SAP Web AS 6.10, so that any string could be sent as a data object with the type STRING.
As well as the string message that will be displayed, you must also specify the message type message_type.
Use
The ABAP keyword documentation for each statement lists the classes whose exceptions may occur when that statement is executed. The following will show you how to create your own global exception classes.
388
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
As with the (obsolete) use of CATCH SYSTEM-EXCEPTIONS, this is also about catching runtime errors that cannot be entirely excluded. A typical example of this can be found in widening cast assignments.
Partner
Caution: This is a demonstration example that has been deliberately kept simple. Normally, you would define the RESULT variable with numerical type F to avoid a runtime error. Then you could define the size of the result value before, if necessary using MOVE to convert to an integer variable.
SAP
SAP
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.
Use
Partner
If the value range for data type I is not exceeded, no exception is raised and the TRY block is processed completely. The processing block then continues executing after the keyword ENDTRY.
Internal
Only
MESSAGE string TYPE message_type.
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
Define global exception classes 1.
In the Class Builder, create a global class as described in the SAP Library. When you enter its name, prefix it with CX_. Choose the option Exception Class as the Class Type. Do not change the default entry for Superclass, unless you are fully aware of the consequences of doing so.
Use
Partner
Only
Internal
SAP
SAP
Use Internal
Give your exception class additional attributes as necessary (for example, for generic extensions to exception texts). If these attributes are public, the Class Builder generates an appropriate instance constructor so that these values can be set for these attributes when the exception is raised. The import parameters are generated with the same names as the attributes.
3.
Save as many exception texts as you need. When doing so you can insert your attributes as parameters in the static text in the form &&.
Only
2.
For the first text you create yourself, always use a predefined static constant as an ID. It always has the same name as the exception class itself. If no text is specified explicitly when the exception is raised, the text with this ID is used instead. For all other texts, you define other IDs. The Class Builder then generates identically-named static constants Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
Partner
Figure 170: Creating Global Exception Classes
389
Unit 5: Exception Handling and Dynamic Programming
BC401
automatically. When the exception is raised, you pass one of these constants to the import parameter TEXTID, to specify the appropriate text for the exception instance.
SAP
SAP
Use
Partner
Only
Internal
Figure 171: Define Variable Exception Texts
Use Internal
Activate your exception class.
Propagating and Handling an Exception Exceptions that occur in procedures do not necessarily need to be handled where they occur; they can be propagated to the caller of the procedure. The caller can then handle the exception itself or propagate it to its own caller, and so on. The highest levels to which an exception can be propagated are processing blocks without local data areas – that is, event blocks or dialog
390
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
4.
Partner
Note: The exception texts of global exception classes are stored in their 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 in the OTR in an instance 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.
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
modules. The exceptions propagated by the called procedures must be dealt with there, as must any exceptions raised within this processing block itself. Otherwise a runtime error occurs. To propagate an exception from within a procedure, you generally need to include the RAISING addition in the procedure’s signature. In methods of local classes and subroutines, specify the RAISING addition directly when defining the procedure
Only Partner
Use
FORM subr_name ... RAISING cx_... cx_.... After RAISING, you list the exception classes whose objects are to be propagated. In methods of global classes, the exception classes whose instances are to be propagated are entered in the exception table of the method in the Class Builder. You also need to set the Exception Class flag for each exception table. The process is similar for function modules. To set the flag in the Function Builder, choose the Exceptions tab. It is clear that a global method or function module can raise only class-based or conventional exceptions.
Internal
FORM subr_name ... RAISING cx_... cx_... or
SAP
SAP Only
Internal
Use
Partner
Figure 172: Propagating Exceptions
The TEXTID parameter is optional: The default value is always the static constant, which has the same name as the exception class. However, one of the static constants defined as additional text IDs in the exception class can also be
08-03-2004
© 2004 SAP AG. All rights reserved.
391
Unit 5: Exception Handling and Dynamic Programming
BC401
used to supply the value. When the exception is raised, the appropriate text for that exception instance is raised. After the exception has been caught, you can then display the text using the functional method GET_TEXT. If the caller does not catch the exception, it can be propagated upwards to the next-level caller. Before control is passed to the next-level caller, the (optional) CLEAN-UP block may be executed. You then use this block to run the appropriate statements.
Only Partner
CLASS lcl_plane DEFINITION.
Internal
Example: Raising, Passing Along, and Handling an Exception
PUBLIC SECTION.
Use
...
METHODS get_attributes
SAP
SAP
EXPORTING ex_name
TYPE t_name_15
value(ex_wa_plane) TYPE saplane RAISING
Use
ENDCLASS.
Partner
cx_bc401_excd_planetype.
"lcl_plane DEFINITION
Internal
CLASS lcl_plane IMPLEMENTATION. ...
Only
METHOD get_attributes.
SELECT SINGLE * FROM saplane INTO ex_wa_plane WHERE planetype = me->type. IF sy-subrc = 0. IF ex_wa_plane-seatsmax_b = 0. "should stand for freighter here RAISE EXCEPTION TYPE cx_bc401_excd_planetype EXPORTING planetype = me->type
392
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
textid = cx_bc401_excd_planetype=>cx_bc401_excd_planetype_f. ENDIF. ELSE. RAISE EXCEPTION TYPE cx_bc401_excd_planetype EXPORTING planetype = me->type. ENDIF. "lcl_plane
ENDCLASS.
Internal
Only
ENDMETHOD.
"lcl_plane IMPLEMENTATION
Partner
CLASS lcl_carrier DEFINITION. PUBLIC SECTION.
Use
...
ENDCLASS.
SAP
SAP
METHODS display_attributes. "lcl_carrier DEFINITION
CLASS lcl_carrier IMPLEMENTATION.
Partner
Use
... METHOD display_attributes. DATA:
Internal
l_ref_plane TYPE REF TO lcl_plane, l_name TYPE t_name_15, l_wa_plane TYPE saplane,
Only
l_ref_exc TYPE REF TO cx_bc401_excd_planetype, l_exc_text TYPE string.
... TRY.
CALL METHOD l_ref_plane->get_attributes IMPORTING
08-03-2004
© 2004 SAP AG. All rights reserved.
393
Unit 5: Exception Handling and Dynamic Programming
BC401
ex_wa_plane = l_wa_plane. WRITE: l_wa_plane-planetype, l_wa_plane-producer, l_wa_plane-seatsmax_b. CATCH cx_bc401_excd_planetype INTO l_ref_exc. l_exc_text = l_ref_exc->get_text( ). WRITE l_exc_text COLOR COL_NEGATIVE.
ENDMETHOD.
"display_attributes "lcl_carrier IMPLEMENTATION
SAP Use Internal
394
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Hint: It would also have been possible to deal with the two errors by means of two exception classes. You could then use different CATCH blocks to deal with whichever of the two errors occurred. However, at this point we wanted to demonstrate how you would use different texts within one exception class.
Partner
The exception is handled in the instance method DISPLAY_ATTRIBUTES of the class LCL_CARRIER. If the exception is raised, execution of the method GET_ATTRIBUTES terminates, and continues with the execution of the CATCH block. Note in particular that the program no longer executes the WRITE statements entered in the TRY block after the method call. The system copies the reference to the instance of the exception class to the local variable L_REF_EXC. The exported error text is set dynamically so that it contains context-sensitive information.
SAP
The instance method GET_ATTRIBUTES of the local class LCL_PLANE displays the name and other attributes of the airplane. If the airplane type is not valid, the exception you defined yourself, CX_BC401_EXCD_PLANETYPE, is to be raised and propagated. That is, there may be instances of airplanes in this scenario whose type is not valid. For example, there may be no data for the airplane type in the table SAPLANE or the airplane may be a freight aircraft. The exception class is written so that there is a separate text available for each of these two situations. In one of the two cases, the default value is passed to the parameter TEXTID, while in the other an additionally defined static constant is passed, depending on the cause of the error. In both cases, the program also passes the invalid airplane type itself to the exception instance.
Use
Partner
ENDCLASS.
Internal
Only
ENDTRY.
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
Class-Based Exceptions in Debugging Mode If an exception is raised, the name of the exception class is displayed in the Exception Raised field in debugging mode. If this exception is caught using a CATCH block, this is displayed in the form of a success message. The pointer for the current statement then moves to this CATCH block.
Use
Partner
Only
Internal
Exception Classes: The Inheritance Hierarchy The following explains consequences that arise from the choice of an exception class’s superclass. It also shows how the exceptions in the runtime system were integrated into the inheritance hierarchy of the exception classes.
08-03-2004
© 2004 SAP AG. All rights reserved.
395
Only
Internal
Two pushbuttons also appear. They allow you to display the values of the attributes of the exception instance and navigate to the point in the source code where the exception occurred.
Partner
Use
SAP
SAP
Figure 173: Class-Based Exceptions in Debugging Mode
Unit 5: Exception Handling and Dynamic Programming
BC401
SAP Use Internal
396
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
For subclasses of CX_NO_CHECK, the rule is that the corresponding exceptions cannot be propagated explicitly using the RAISING addition. These exceptions can be handled. Otherwise they are automatically propagated. Neither a syntax warning nor a runtime error is caused directly where it is raised. Instead all exceptions that are not handled somewhere in the call hierarchy are propagated up to the highest call level. If it is not
Partner
The rule for subclasses of CX_DYNAMIC_CHECK also applies to subclasses of CX_DYNAMIC_CHECK: You must either handle them or explicitly propagate them using the RAISING addition. The difference is that this is not checked statically. That is, the system does not report a syntax warning, if the exception is not either handled or propagated. If the exception is then raised, a runtime error occurs. Typical examples of this situation are the predefined exceptions CX_SY_... for errors that occur in the runtime environment. These are usually subclasses of CX_DYNAMIC_CHECK.
SAP
Subclasses of CX_STATIC_CHECK: The relevant exception must either be handled, or propagated explicitly using the RAISING addition. If this is not the case, the syntax check displays a warning. If you define your own exception classes, CX_STATIC_CHECK is defined as the superclass by default.
Use
Partner
Only
Internal
Figure 174: Integration of Standard Exceptions in the Runtime System
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
caught there either, a runtime error occurs at that point. Some predefined exceptions with the prefix CX_SY_... for error situations in the runtime environment are subclasses of CX_NO_CHECK.
Mapping Exceptions to Each Other
Partner
Use
In the following section, you should show how the raising of exceptions can be chained together – that is, how an exception raises another exception, and so on. Each instance should remain valid, regardless of whether or not the associated CATCH block has already been left or not. In this respect, you must make sure that the previous exception instance can always be accessed by means of at least one reference. The public instance attribute PREVIOUS, inherited by all exception classes from CX_ROOT, provides a convenient way of doing this.
Internal
Only
For the sake of clarity, you should start by emphasizing that an exception can be propagated through any number of call hierarchies, before it is finally handled.
SAP
SAP Only
Internal
Use
Partner
Figure 175: Mapping Exceptions to Each Other
When raising the next exception, only one reference to the previous exception instance must be passed to the new instance. You do this with the optional parameter PREVIOUS of the instance constructor – that is, using RAISE
08-03-2004
© 2004 SAP AG. All rights reserved.
397
Unit 5: Exception Handling and Dynamic Programming
BC401
EXCEPTION. In this way, the new exception is mapped to the previous one. After the mapped exception has been caught, the instance attribute PREVIOUS contains a reference to the previous exception instance, and so on. In this way, you can access each instance in the chain of exceptions. Therefore, you can follow the history of the raising of the exceptions in the program.
Example: Creating a Chain of Exceptions
Only
CLASS lcl_carrier
Partner
DEFINITION.
Internal
The method GET_ATTRIBUTES has been defined and implemented in the local class LCL_PLANE as in the previous example. Another exception class, here CX_BC401_EXCD_LIST, has already been defined.
PUBLIC SECTION.
Use
...
METHODS display_attributes
SAP
SAP
RAISING cx_bc401_excd_list.
ENDCLASS.
"lcl_carrier DEFINITION
Use
Partner
CLASS lcl_carrier IMPLEMENTATION. ...
Internal
METHOD display_attributes. DATA: l_ref_plane TYPE REF TO lcl_plane, l_name TYPE t_name_15,
Only
l_wa_plane TYPE saplane,
l_ref_exc TYPE REF TO cx_bc401_excd_planetype, l_exc_text TYPE string.
... TRY. CALL METHOD l_ref_plane->get_attributes IMPORTING
398
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
ex_wa_plane = l_wa_plane. WRITE: l_wa_plane-planetype, l_wa_plane-producer, l_wa_plane-seatsmax_b. CATCH cx_bc401_excd_planetype INTO l_ref_exc. l_exc_text = l_ref_exc->get_text( ). WRITE l_exc_text COLOR COL_NEGATIVE. RAISE EXCEPTION TYPE cx_bc401_excd_list
Internal
Only
EXPORTING previous = l_ref_exc. ENDTRY.
Partner
ENDMETHOD.
"display_attributes
ENDCLASS.
"lcl_carrier IMPLEMENTATION
Use
... DATA: ref_plane
TYPE REF TO lcl_plane,
SAP
ref_exc exc_text
SAP
ref_carrier TYPE REF TO lcl_carrier,
TYPE REF TO cx_bc401_excd_list, TYPE string,
Partner
Use
previous_text TYPE string.
...
Internal
START-OF-SELECTION. ...
Only
TRY. CALL METHOD ref_carrier->display_attributes. CATCH cx_bc401_excd_list INTO ref_exc.
exc_text = ref_exc->get_text( ). MESSAGE exc_text TYPE ’I’.
previous_text = ref_exc->previous->get_text( ). MESSAGE previous_text TYPE ’I’. ENDTRY.
08-03-2004
© 2004 SAP AG. All rights reserved.
399
Unit 5: Exception Handling and Dynamic Programming
BC401
...
Since the method DISPLAY_ATTRIBUTES propagates its exception to the main program, the system stops list processing within the DISPLAY_ATTRIBUTES method as soon as the first error occurs.
SAP
SAP
Hint: It would also be possible to propagate the original exception from the method DISPLAY_ATTRIBUTES. We would not then have had to define two exception classes explicitly. However, the point of this example is to show how exceptions can be chained.
Use
Partner
The exception for the list with the errors is now handled in the main program. First the exception text is displayed as an information message. However, since the exception is mapped to a second exception for the invalid airplane type, the instance attribute PREVIOUS contains a reference to the second exception. You use this reference to export the text from the original exception and display it as an information message.
Internal
Only
The exception for the invalid airplane type is caught in the instance method DISPLAY_ATTRIBUTES of the class LCL_CARRIER. The exception text is displayed in the list. Another exception is then raised, since the list now contains errors. The reference to the first exception instance is now passed to the second.
Only
Internal
Use
Partner
400
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
Exercise 23: Class-Based Exceptions Exercise Objectives
Only
Business Example
Use
Partner
Your airplane management program should use the class-based exception concept if an invalid airplane type occurs. An error text should be displayed in the list, instead of the current default values.
Task 1:
Use
Create a global exception class called ZCX_##_INVALID_PLANETYPE. (where ## is your two-digit group number). Choose the superclass so that the syntax check determines if the relevant exception is handled after it is raised or if it is explicitly propagated.
2.
Add an attribute for the airplane type (suggested name: PLANETYPE) and assign the type S_PLANETYPE to it.
3.
Create a default error message that can be enhanced dynamically to include the airplane type.
Partner
Task 2: Raise your new exception if an error occurs. 1.
Complete your program ZBC401_##_MAIN program or copy the model solution for the airplane management program, SAPBC401_EVES_MAIN_B (where ## is your two-digit group number).
2.
Raise your exception within method ET_TECHNICAL_ATTRIBUTES of local class LCL_AIRPLANE. Ensure that the invalid airplane type is copied into the attribute of the exception instance. Continued on next page
© 2004 SAP AG. All rights reserved.
401
Only
Internal
1.
SAP
SAP
Create a global exception class for an invalid airplane type.
08-03-2004
Internal
After completing this exercise, you will be able to: • Define global exception classes • Raise class-based exceptions • Propagate class-based exceptions • Handle class-based exceptions
Unit 5: Exception Handling and Dynamic Programming
3.
BC401
Make sure that the raised exception is explicitly propagated.
Task 3: Handle the exception. 1.
Catch your exception in the DISPLAY_ATTRIBUTES method of local class LCL_AIRPLANE.
Only
2.
Read the error text in the exception instance and display it in the ABAP list.
Use
Partner
To that end, define a variable (suggested name: EXC_TEXT) with data type STRING.
Internal
To do so, define a local reference variable (suggested name: R_EXCEPTION) and assign it to the CX_ROOT class.
SAP
SAP Only
Internal
Use
Partner
402
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
Solution 23: Class-Based Exceptions Task 1: Create a global exception class for an invalid airplane type. Create a global exception class called ZCX_##_INVALID_PLANETYPE. (where ## is your two-digit group number). Choose the superclass so that the syntax check determines if the relevant exception is handled after it is raised or if it is explicitly propagated. a)
2.
Add an attribute for the airplane type (suggested name: PLANETYPE) and assign the type S_PLANETYPE to it. a) b)
SAP
Create a default error message that can be enhanced dynamically to include the airplane type. a)
Follow the processes as outlined in the relevant section of this document. Speak to your instructor if you have any questions.
Task 2: 1.
Complete your program ZBC401_##_MAIN program or copy the model solution for the airplane management program, SAPBC401_EVES_MAIN_B (where ## is your two-digit group number). a) b)
2.
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_EXCS_RAISE_TRY
Raise your exception within method ET_TECHNICAL_ATTRIBUTES of local class LCL_AIRPLANE.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
403
Only
Internal
Raise your new exception if an error occurs.
Partner
b)
Use
Follow the processes as outlined in the relevant section of this document. Speak to your instructor if you have any questions.
SAP
3.
Use
Partner
b) c)
Follow the processes as outlined in the relevant section of this document. Speak to your instructor if you have any questions. Model solution: CX_BC401_INVALID_PLANETYPE
Internal
Only
1.
Unit 5: Exception Handling and Dynamic Programming
BC401
Ensure that the invalid airplane type is copied into the attribute of the exception instance. a) 3.
See the source code extract from the model solution
Make sure that the raised exception is explicitly propagated. a)
See the source code extract from the model solution
Handle the exception. 1.
Catch your exception in the DISPLAY_ATTRIBUTES method of local class LCL_AIRPLANE.
a) 2.
See the source code extract from the model solution
Read the error text in the exception instance and display it in the ABAP list.
SAP
a)
See the source code extract from the model solution
SAP
To that end, define a variable (suggested name: EXC_TEXT) with data type STRING.
Use
Partner
To do so, define a local reference variable (suggested name: R_EXCEPTION) and assign it to the CX_ROOT class.
Internal
Only
Task 3:
Source code extract:
*&---------------------------------------------------------------------* *&
Include
BC401_EXCS_RAISE_TRY_CL2
*
*&---------------------------------------------------------------------* *------------------------------------------------------------------* * events in: lcl_airplane and lcl_carrier ! *
*------------------------------------------------------------------* *
CLASS lcl_airplane DEFINITION
*
*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION.
Continued on next page
404
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
BC401_EXCS_RAISE_TRY_CL2
Partner
Use
Result
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
PUBLIC SECTION. "--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: constructor IMPORTING im_name
TYPE string
im_planetype TYPE saplane-planetype,
Internal
Only
display_attributes.
CLASS-METHODS: display_n_o_airplanes. EVENTS: airplane_created.
Partner
PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes EXPORTING ex_weight ex_tankcap
DATA: name
TYPE s_plan_wei TYPE s_capacity
cx_bc401_invalid_planetype.
SAP
SAP
RAISING
TYPE saplane-planetype
Use
IMPORTING im_type
TYPE string,
planetype TYPE saplane-planetype.
ENDCLASS.
Partner
Use
CLASS-DATA: n_o_airplanes TYPE i. "lcl_airplane DEFINITION
*------------------------------------------------------------------*
Internal
*
CLASS lcl_airplane IMPLEMENTATION
*
*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.
Only
METHOD constructor. name
= im_name.
planetype
= im_planetype.
n_o_airplanes = n_o_airplanes + 1. RAISE EVENT airplane_created. ENDMETHOD.
"constructor
METHOD display_attributes. DATA: weight TYPE saplane-weight,
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
405
Unit 5: Exception Handling and Dynamic Programming
BC401
cap TYPE saplane-tankcap, r_exception TYPE REF TO cx_root, exc_text TYPE string.
WRITE: / icon_ws_plane AS ICON, / ’Name of Airplane’(001), AT pos_1 name, / ’Type of airplane: ’(002), AT pos_1 planetype.
Internal
Only
* handle exception in case of invalid planetype: TRY. get_technical_attributes( EXPORTING im_type = planetype IMPORTING ex_weight = weight ex_tankcap = cap ).
Partner
WRITE: / ’Weight:’(003), weight, ’Tankkap:’(004), cap. CATCH cx_bc401_invalid_planetype INTO r_exception.
Use
exc_text = r_exception->get_text( ). WRITE: / exc_text COLOR COL_NEGATIVE. ENDTRY. "display_attributes
SAP
SAP
ENDMETHOD. METHOD display_n_o_airplanes.
WRITE: /, / ’Number of airplanes: ’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. "display_n_o_airplanes
Partner
Use
ENDMETHOD.
METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap)
Internal
WHERE planetype = im_type. IF sy-subrc <> 0. RAISE EXCEPTION TYPE cx_bc401_invalid_planetype
Only
EXPORTING planetype = im_type. ENDIF. ENDMETHOD.
ENDCLASS.
"get_technical_attributes
"lcl_airplane IMPLEMENTATION
*---------------------------------------------------------------------* *
CLASS lcl_cargo_plane DEFINITION
Continued on next page
406
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane. PUBLIC SECTION. "---------------------METHODS: constructor IMPORTING im_name TYPE string
Internal
Only
im_planetype TYPE saplane-planetype im_cargo TYPE scplane-cargomax. METHODS: display_attributes REDEFINITION. PRIVATE SECTION.
Partner
"---------------------DATA: max_cargo TYPE scplane-cargomax.
"lcl_cargo_plane DEFINITION
Use
ENDCLASS.
*---------------------------------------------------------------------* *
CLASS lcl_cargo_plane IMPLEMENTATION
SAP
SAP
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION.
Partner
Use
METHOD constructor. CALL METHOD super->constructor EXPORTING im_name
= im_name
Internal
im_planetype = im_planetype. max_cargo = im_cargo. ENDMETHOD.
"constructor
Only
METHOD display_attributes. super->display_attributes( ). WRITE: / ’Max Cargo = ’, max_cargo. ULINE. ENDMETHOD. ENDCLASS.
"display_attributes "lcl_cargo_plane IMPLEMENTATION
*---------------------------------------------------------------------*
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
407
Unit 5: Exception Handling and Dynamic Programming
*
BC401
CLASS lcl_passenger_plane DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane.. PUBLIC SECTION. METHODS: constructor IMPORTING im_name TYPE string
Internal
Only
im_planetype TYPE saplane-planetype im_seats TYPE sflight-seatsmax. METHODS: display_attributes REDEFINITION. PRIVATE SECTION. "lcl_passenger_plane DEFINITION
*---------------------------------------------------------------------* *
CLASS lcl_passenger_plane IMPLEMENTATION
*---------------------------------------------------------------------* *
SAP
CLASS lcl_passenger_plane IMPLEMENTATION. METHOD constructor.
SAP
*---------------------------------------------------------------------*
Use
Partner
DATA: max_seats TYPE sflight-seatsmax. ENDCLASS.
CALL METHOD super->constructor
Partner
Use
EXPORTING im_name
= im_name
im_planetype = im_planetype. max_seats = im_seats.
Internal
ENDMETHOD.
"constructor
METHOD display_attributes.
Only
super->display_attributes( ). WRITE: / ’Max Seats = ’, max_seats. ULINE. ENDMETHOD. ENDCLASS.
"display_attributes "lcl_passenger_plane IMPLEMENTATION
*---------------------------------------------------------------------* *
CLASS lcl_carrier DEFINITION
*---------------------------------------------------------------------* *
Continued on next page
408
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
*---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION. "---------------------------------------INTERFACES lif_partners. METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string,
Internal
Only
add_airplane FOR EVENT airplane_created OF lcl_airplane IMPORTING sender, display_airplanes, display_attributes.
Partner
PRIVATE SECTION. "----------------------------------DATA: name
TYPE string,
ENDCLASS.
Use
airplane_list TYPE TABLE OF REF TO lcl_airplane. "lcl_carrier DEFINITION
*---------------------------------------------------------------------*
SAP
CLASS lcl_carrier IMPLEMENTATION
SAP
*
*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD lif_partners~display_partner. display_attributes( ).
Use
Partner
ENDMETHOD.
"lif_partners~display_partner
METHOD add_airplane. APPEND sender TO airplane_list.
Internal
ENDMETHOD.
"add_airplane
METHOD display_attributes.
Only
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.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
409
Unit 5: Exception Handling and Dynamic Programming
ENDMETHOD.
BC401
"display_airplanes
METHOD constructor. name = im_name. SET HANDLER add_airplane FOR ALL INSTANCES. RAISE EVENT lif_partners~partner_created. ENDMETHOD.
"constructor
Internal
Only
METHOD get_name. ex_name = name. ENDMETHOD.
"lcl_carrier IMPLEMENTATION
Use
Partner
ENDCLASS.
"get_name
SAP
SAP Only
Internal
Use
Partner
410
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
Exercise 24: Mapping Exceptions to Each Other Exercise Objectives
Only
If your airplane management program encounters an exception and displays an error on the list, make the program raise another exception. The second exception should refer to the first exception, so that both instances can be evaluated when the exception is handled.
SAP Internal
Complete your ZBC401_##_MAIN program or copy the sample solution of the previous exercise, SAPBC401_EXCS_RAISE_TRY. (where ## is your two-digit group number).
2.
To make your program easier to maintain, create another include program for your exception class and include it in your main program (suggested name: ZBC401_##_EXCEPTION).
3.
Define a local exception class in your new include program. The exception is needed in case exception handling takes place during the output of the list (suggested name: LCX_LIST_ERROR). Hint: Derive your local exception class from the superclass CX_STATIC_CHECK.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
411
Only
1.
Partner
Use
Define a local exception class for the event of an error text being displayed in the list.
SAP
Task 1:
Use
Partner
Business Example
Internal
After completing this exercise, you will be able to: • Define local exception classes • Map an exception, when it is raised, to another exception that has already been raised • When handling a mapped exception, evaluate the previous exception as well
Unit 5: Exception Handling and Dynamic Programming
4.
BC401
Add a public instance method to your local exception class. This method returns a special text appropriate to the error that may occur – for example “The list contains an error.” We suggest the name: GET_EXC_TEXT.
Task 2: Raise the new exception and map it to the original one. Raise your new exception in method DISPLAY_ATTRIBUTES of local class LCL_AIRPLANE when the exception for the invalid airplane type is being handled. Transfer the reference to the original exception instance to the exception instance that is to be created. Extend the signature of the DISPLAY_ATTRIBUTES method, so that your new exception is explicitly propagated.
Task 3:
2.
Use this reference to export the text of your new exception. Define an appropriately typed text variable for this purpose (suggested name: EXC_TEXT).
Use
Catch your new exception in the DISPLAY_AIRPLANES method of local class LCL_CARRIER. Define an appropriately-typed local reference for the purpose (suggested name: R_EXC).
Internal
If an exception occurs, display the text of your new exception as well the old one, in the form of an information message. 3.
Use the same variables to export the text of the original exception.
412
© 2004 SAP AG. All rights reserved.
Only
Enter this text in form of an information message, as well.
Partner
1.
SAP
SAP
Handle your new exception and evaluate the information of both the new and the original exception instance.
Use
Partner
2.
Internal
Only
1.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
Solution 24: Mapping Exceptions to Each Other Task 1: Define a local exception class for the event of an error text being displayed in the list. Complete your ZBC401_##_MAIN program or copy the sample solution of the previous exercise, SAPBC401_EXCS_RAISE_TRY. (where ## is your two-digit group number). a)
2.
To make your program easier to maintain, create another include program for your exception class and include it in your main program (suggested name: ZBC401_##_EXCEPTION).
Define a local exception class in your new include program. The exception is needed in case exception handling takes place during the output of the list (suggested name: LCX_LIST_ERROR). Hint: Derive your local exception class from the superclass CX_STATIC_CHECK.
4.
See the source code extract from the model solution
Add a public instance method to your local exception class. This method returns a special text appropriate to the error that may occur – for example “The list contains an error.” We suggest the name: GET_EXC_TEXT. a)
See the source code extract from the model solution
Task 2: Raise the new exception and map it to the original one. 1.
08-03-2004
Raise your new exception in method DISPLAY_ATTRIBUTES of local class LCL_AIRPLANE when the exception for the invalid airplane type is being handled. Continued on next page
© 2004 SAP AG. All rights reserved.
413
Only
Internal
a)
Partner
Use
3.
Carry out this step in the usual manner. Additional information is available in the SAP Library.
SAP
SAP
a)
Use
Partner
b)
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_EXCS_RAISE_TRY_OPT
Internal
Only
1.
Unit 5: Exception Handling and Dynamic Programming
BC401
Transfer the reference to the original exception instance to the exception instance that is to be created. a) 2.
See the source code extract from the model solution
Extend the signature of the DISPLAY_ATTRIBUTES method, so that your new exception is explicitly propagated. a)
See the source code extract from the model solution
Only
Handle your new exception and evaluate the information of both the new and the original exception instance. Catch your new exception in the DISPLAY_AIRPLANES method of local class LCL_CARRIER. Define an appropriately-typed local reference for the purpose (suggested name: R_EXC). a)
Use this reference to export the text of your new exception. Define an appropriately typed text variable for this purpose (suggested name: EXC_TEXT). If an exception occurs, display the text of your new exception as well the old one, in the form of an information message. a)
Use
See the source code extract from the model solution
Use the same variables to export the text of the original exception. Enter this text in form of an information message, as well.
Internal
a)
See the source code extract from the model solution
Result
Only
Source code extract:
SAPBC401_EXCS_RAISE_TRY_OPT REPORT
sapbc401_excs_raise_try_opt.
TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2.
TYPE-POOLS icon.
Continued on next page
414
© 2004 SAP AG. All rights reserved.
Partner
3.
SAP
SAP
2.
See the source code extract from the model solution
Use
Partner
1.
Internal
Task 3:
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
INCLUDE bc401_excs_raise_try_opt_exc. INCLUDE bc401_excs_raise_try_opt_cl1. INCLUDE bc401_excs_raise_try_opt_cl2.
DATA: r_vehicle TYPE REF TO lcl_vehicle, r_truck TYPE REF TO lcl_truck, TYPE REF TO lcl_bus,
Internal
Only
r_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,
START-OF-SELECTION.
...
Use
Partner
r_agency TYPE REF TO lcl_travel_agency.
BC401_EXCS_RAISE_TRY_OPT_EXC *&---------------------------------------------------------------------* Include
BC401_EXCS_RAISE_TRY_OPT_EXC
*
SAP
SAP
*&
*&---------------------------------------------------------------------*
*---------------------------------------------------------------------*
Use
Partner
*
CLASS lcx_list_error DEFINITION
*---------------------------------------------------------------------* * *---------------------------------------------------------------------*
Internal
CLASS lcx_list_error DEFINITION INHERITING FROM cx_static_check.
PUBLIC SECTION.
Only
METHODS get_exc_text RETURNING value(result) TYPE string.
ENDCLASS.
"lcx_list_error DEFINITION
*---------------------------------------------------------------------* *
CLASS lcx_list_error IMPLEMENTATION
*---------------------------------------------------------------------* *
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
415
Unit 5: Exception Handling and Dynamic Programming
BC401
*---------------------------------------------------------------------* CLASS lcx_list_error IMPLEMENTATION.
METHOD get_exc_text. result = ’The list contains an error.’(err). "get_text
ENDMETHOD.
"lcx_list_error IMPLEMENTATION
BC401_EXCS_RAISE_TRY_CL2 *&---------------------------------------------------------------------* *&
Include
BC401_EXCS_RAISE_TRY_CL2
*
Partner
*&---------------------------------------------------------------------*
*
CLASS lcl_airplane DEFINITION
Use
*------------------------------------------------------------------* *
*------------------------------------------------------------------*
SAP
SAP
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION. "---------------------------------------------
Use
METHODS: display_attributes
im_name
Partner
Internal
CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: constructor IMPORTING TYPE string
im_planetype TYPE saplane-planetype.
RAISING lcx_list_error.
Only
CLASS-METHODS: display_n_o_airplanes. EVENTS: airplane_created. PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes IMPORTING im_type EXPORTING ex_weight ex_tankcap RAISING
TYPE saplane-planetype TYPE s_plan_wei TYPE s_capacity
cx_bc401_invalid_planetype.
Continued on next page
416
© 2004 SAP AG. All rights reserved.
Internal
Only
ENDCLASS.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
DATA: name
TYPE string,
planetype TYPE saplane-planetype.
CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS.
"lcl_airplane DEFINITION
*
CLASS lcl_airplane IMPLEMENTATION
Internal
Only
*------------------------------------------------------------------* *
*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION.
Partner
METHOD constructor. ... ENDMETHOD.
"constructor
Use
METHOD display_attributes. DATA: weight TYPE saplane-weight, cap TYPE saplane-tankcap,
SAP
SAP
r_exception TYPE REF TO cx_root, exc_text TYPE string. WRITE: / icon_ws_plane AS ICON, / ’Name of Airplane’(001), AT pos_1 name,
Partner
Use
/ ’Type of airplane: ’(002), AT pos_1 planetype. *
handle exception in case of invalid planetype: TRY.
Internal
get_technical_attributes( EXPORTING im_type = planetype IMPORTING ex_weight = weight ex_tankcap = cap ).
Only
WRITE: / ’Weight:’(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. RAISE EXCEPTION TYPE lcx_list_error EXPORTING previous = r_exception.
ENDTRY.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
417
Unit 5: Exception Handling and Dynamic Programming
ENDMETHOD.
BC401
"display_attributes
METHOD display_n_o_airplanes. ... ENDMETHOD.
"display_n_o_airplanes
METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane
Internal
Only
INTO (ex_weight, ex_tankcap) WHERE planetype = im_type. IF sy-subrc <> 0. RAISE EXCEPTION TYPE cx_bc401_invalid_planetype EXPORTING planetype = im_type.
ENDMETHOD.
"get_technical_attributes
ENDCLASS.
"lcl_airplane IMPLEMENTATION
...*---------------------------------------------------------------------* *
CLASS lcl_carrier DEFINITION
SAP
* *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION.
Partner
Use
PUBLIC SECTION. "---------------------------------------INTERFACES lif_partners. METHODS: constructor IMPORTING im_name TYPE string,
Internal
SAP
*---------------------------------------------------------------------*
Use
Partner
ENDIF.
get_name RETURNING value(ex_name) TYPE string, add_airplane FOR EVENT airplane_created OF lcl_airplane
Only
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
Continued on next page
418
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
*---------------------------------------------------------------------* *
CLASS lcl_carrier IMPLEMENTATION
*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD lif_partners~display_partner. ... "lif_partners~display_partner
Internal
Only
ENDMETHOD. METHOD add_airplane. ... ENDMETHOD.
"add_airplane
Partner
METHOD display_attributes. SKIP 2. WRITE: icon_flight AS ICON, name . ULINE. ULINE. ENDMETHOD.
Use
display_airplanes( ). "display_attributes
METHOD display_airplanes.
SAP
r_plane
TYPE REF TO lcl_airplane,
r_exc
TYPE REF TO lcx_list_error,
SAP
DATA:
exc_text TYPE string.
Partner
Use
LOOP AT airplane_list INTO r_plane. TRY. r_plane->display_attributes( ). CATCH lcx_list_error INTO r_exc.
Internal
exc_text = r_exc->get_exc_text( ). MESSAGE exc_text TYPE ’I’.
Only
exc_text = r_exc->previous->get_text( ). MESSAGE exc_text TYPE ’I’. ENDTRY. ENDLOOP. ENDMETHOD.
"display_airplanes
METHOD constructor. ... ENDMETHOD.
"constructor
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
419
Unit 5: Exception Handling and Dynamic Programming
BC401
METHOD get_name. ... ENDMETHOD.
ENDCLASS.
"get_name
"lcl_carrier IMPLEMENTATION
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
420
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20
Lesson Summary
Only
Related Information
Use
Partner
... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.
Internal
You should now be able to: • Create exception classes • Trigger class-based exceptions in ABAP Objects programs • Propagate class-based exceptions in ABAP Objects programs • Handle class-based exceptions in ABAP Objects programs • Map class-based exceptions in ABAP Objects programs to each other
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
421
Unit 5: Exception Handling and Dynamic Programming
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20 Lesson Overview
Only Partner
After completing this lesson, you will be able to:
Lesson Objectives
Use
Dynamically create objects Dynamically access class and object components Define field symbols Define data references Dereference data references Dynamically create data objects Ascertain the attributes of data objects at runtime
Partner
Business Example You want to add special dynamic programming techniques to your ABAP Objects implementations.
Field Symbols With field symbols, ABAP or ABAP Objects has offered dereferenced pointers for many releases. 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
422
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
SAP
• • • • • • •
Use
As of SAP Web AS 6.10 at the latest, ABAP Objects objects offers at least the same possibilities that you may know from other programming languages. However, ABAP Objects stands out in the field of dynamic programming, particularly because ABAP Workbench supports it to such a high degree.
SAP
However, it is important for you to understand that this development took place, as it will help to explain why very similar concepts sometimes use quite different syntax structures.
Internal
Beginning with ABAP/4, the possibilities for dynamic programming with ABAP Objects have increased with the over several releases. This section will not retrace this development, it will give you a complete systematic introduction to the subject.
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
data object assigned to it. Thus, you can only access the content of the data object to which the field symbol points. This is known as the “value semantics of field symbols”.
SAP
SAP
Use
Partner
Only
Internal
Figure 176: Field Symbols
Caution: Note that the parentheses (<>) around the field symbol’s name are part of the syntax.
By specifying a type for the field symbol, you can ensure that only compatible objects are assigned to it.
For example: DATA: date TYPE d VALUE ’20040101’, time TYPE t. FIELD-SYMBOLS: TYPE d, TYPE t. ASSIGN: date TO , time TO . * possible? = .
08-03-2004
© 2004 SAP AG. All rights reserved.
423
Only
Internal
You use the ASSIGN statement to assign a data object to a field symbol. If the field symbol is generically typed (TYPE ANY), it adopts the type of the object.
Partner
Use
You declare field symbols using the FIELD-SYMBOLS statement.
Unit 5: Exception Handling and Dynamic Programming
BC401
The last statement is a syntax error! Conversely, using the following construction would cause a runtime error: FIELD-SYMBOLS: TYPE ANY, TYPE ANY. Use the expression IS ASSIGNED to find out whether the field symbol is assigned to a field. The statement UNASSIGN sets the field symbol so that it points to nothing. The logical expression IS ASSIGNED is then false.
Use
Partner
Only
Internal
SAP
SAP
Use
If you use the CASTING 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 explicitly specified type. In the above example, note that the system field SY-DATUM is an elementary character-type component of length 8. You can also use type casting dynamically when you assign a data object to a field symbol.
424
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
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.
Partner
Figure 177: Type Casting with Field Symbols
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
For example: PARAMETERS tabname TYPE dd02l-tabname. DATA: dummy TYPE i, line(65535) TYPE c. FIELD-SYMBOLS TYPE ANY.
You can now access line using as if this elementary data object had the same type as the row type of the transparent table passed using tabname.
Partner
Note: You define the dummy data object only to ensure that line has the correct alignment.
Static and instance attributes can be accessed by assigning their contents to a field symbol. Syntactically, the attribute access takes the place of the data object.
Use
Attribute Access Using the ASSIGN Statement
SAP
SAP
Accessing Attributes Using Field Symbols
Internal
Only
ASSIGN line TO CASTING TYPE (tabname).
ASSIGN o_ref->instance_attribute TO .
You can also access it dynamically.
Dynamic Attribute Access Using the ASSIGN Statement DATA: classname
TYPE seoclsname VALUE ’CLASS’,
attributname TYPE seocpdname VALUE ’ATTRIBUTE’. ASSIGN (classname)=>(attributname) TO . ASSIGN o_ref->(attributname) TO .
08-03-2004
© 2004 SAP AG. All rights reserved.
425
Only
Internal
If the field symbol has been typed generically, the missing type attributes are copied from the attributes during assignment.
Partner
Use
ASSIGN class=>static_attribute TO .
Unit 5: Exception Handling and Dynamic Programming
BC401
Data References In addition to field symbols, data and object references were also introduced to SAP R/3 4.6A in the transition to ABAP Objects. Since then, ABAP Objects contains complete reference semantics.
SAP
SAP
Use
Partner
Only
Internal
Note: The data syntax element represents a predefined name, comparable with space or constructor .
426
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Data reference variables contain data references - that is, pointers to data objects. You can use the TYPE REF TO addition to the TYPES statement to define a reference type to a data object. You can specify the data type explicitly or choose the generic variation using TYPE REF TO data . In this case, your data reference can point to data objects of any type.
Partner
Use
Figure 178: Data References
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
You define the data reference variable itself using the DATA statement. This reference variable is a data object that can contain any data object (TYPE REF TO data) or a data object of the specified type. You work with data references using references. That is, when you access a data reference variable the data reference itself is accessed, so that changes are made to the addresses.
Only
You can also assign an existing data reference from another data reference variable or generate a data object dynamically using it. (This will be discussed in more detail later.)
SAP Use Internal
For example: DATA ref TYPE REF TO sflight. CREATE DATA ref.
08-03-2004
© 2004 SAP AG. All rights reserved.
427
Only
If the data reference is statically typed as structured, you can also use the component selector -> to address the components of the referenced data object directly and use them in any operand position.
Partner
The expression data_reference->* is comparable to the expression .
SAP
Static references can be dereferenced directly using the dereferencing operator ->* ; this means they can access the content of the data object to which the reference points. For compatibility reasons, you must dereference generically typed data references (TYPE REF TO data) and assign them to a field symbol. You can then access their contents through the field symbol. (This will be explained in more detail later.)
Use
Partner
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 the statement GET REFERENCE OF to obtain a reference to a data object that has already been defined.
Internal
Data references are handled in ABAP Objects 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.
Unit 5: Exception Handling and Dynamic Programming
BC401
ref->fldate = ref->fldate + 5. WRITE: / ref->seatsmax.
Validity of References – Logical Expression ... ref IS [NOT] BOUND ...
The logical expression is true for a data reference if it can be dereferenced. The logical expression is true for an object reference if it points to an object. The logical expression is always false if ref contains the null reference.
SAP
Dynamic Instantiation and Calls
Use
Only
Internal
Partner
Syntax elements can be transferred dynamically for many statements. The syntax for doing this differs, depending on the statement you use:
SAP
In contrast, you can only use the expression ... ref IS [NOT] INITIAL ... to determine if ref contains the null reference or not.
Use
Partner
The expression ref IS [NOT] BOUND is used to query whether the reference variable ref contains a valid reference. ref must be a data or object reference variable.
Internal
Only
Here, the component selector is similar to the hyphen used with regular component access to structured data objects.
428
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
Partner
Only
Internal
Figure 179: Dynamic Statements
SAP Use
For more information on which of these options you can use with a specific ABAP statement – if any – refer to the ABAP keyword documentation for that statement. In Open SQL statements, you can also specify the logical conditions of the WHERE clause dynamically at runtime, by entering the ABAP source code in a variable. In the FROM clause of the SELECT statement, you can specify either individual table names or a dynamic JOIN expression using a variable. Similarly, you can program the GROUP-BY and HAVING clauses in SELECT statements. For more information, refer to the ABAP keyword documentation. This principle also applies to the object-oriented statements in ABAP Objects. Using the following statement, you can instantiate objects dynamically:
08-03-2004
© 2004 SAP AG. All rights reserved.
429
Only
Internal
Caution: Note: you must use upper case when filling data objects with literals.
Partner
For some statements, you can use a single-column internal table instead of one or more literals or identifiers.
SAP
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.
Use
If you pass the attribute as a literal in the static form of the statement, you can replace the literal with a variable.
Unit 5: Exception Handling and Dynamic Programming
BC401
Dynamic Instantiation of Objects DATA: classname TYPE seoclsname, o_ref TYPE REF TO object. ... CREATE OBJECT o_ref TYPE (classname) PARAMETER-TABLE it_par
The class name must be in the data object classname at runtime. The object reference o_ref must be compatible with this class or a common superclass, or it must be typed using TYPE REF TO object.
The current parameters and the return values of the exceptions must be passed dynamically using special internal tables. (This will be discussed in more detail later.) Instance methods are called dynamically according to the same principle:
SAP
SAP
Calling Instance Methods Dynamically CALL METHOD o_ref->(meth_name) PARAMETER-TABLE it_par
Use
Partner
EXCEPTION-TABLE it_exc.
or static methods
CALL METHOD (classname)=>(meth_name) PARAMETER-TABLE it_par EXCEPTION-TABLE it_exc.
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Calling Static Methods Dynamically
430
Use
Partner
Note: Compare to TYPE REF TO data.
Internal
Only
EXCEPTION-TABLE it_exc.
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
Partner
SAP
The table kind has three columns:
Partner
Use
The types ABAP_PARMBIND_TAB and ABAP_EXCPBINDTAB of both internal tables are defined globally in the ABAP type group. The parameter table must have the attributes of the ABAP_PARMBIND_TAB table kind.
Use
SAP
Only
Internal
Figure 180: Parameter Transfer and Exception Allocation for Dynamic Instantiations and Calls
NAME Name of the formal parameter
VALUE Value of the actual parameter (type: REF TO data) The way the parameter is passed is specified for each formal parameter in the declaration of the called method. Thus, the content of the KIND column can be initial. For the value of the actual parameter, the VALUE reference of the row in the table must point to the data object containing that value. You can use the GET REFERENCE statement to achieve this.
08-03-2004
© 2004 SAP AG. All rights reserved.
431
Only
Internal
KIND Type of parameter transfer (exporting, importing, changing, or receiving)
Unit 5: Exception Handling and Dynamic Programming
BC401
The exception table must have the attributes of the ABAP_EXCPBIND_TAB table kind. The table has two columns: NAME Name of exception VALUE Value for the return variable SY-SUBRC (type: I)
Only
Use
Partner
Internal
Caution: Exceptions can only be entered into the table according to the old concept. Alternatively, you can use the new class-based exception concept with implicit propagation (CX_NO_CHECK as the superclass), instead of the exception table.
SAP
SAP
In this example, the GET_MAKE method of the LCL_VEHICLE class is called dynamically. It has only one export parameter and no exceptions. First, define a parameter table called PTAB, with the global table kind ABAP_PARMBIND_TAB from the type group ABAP. The associated work area is called WA_PTAB. The WA_PTAB work area is filled with values: 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. Also define the data reference
432
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Use
Partner
Figure 181: Dynamic Method Calls – Syntax Example
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
variable REF and fill the corresponding reference using GET REFERENCE. The KIND component of the work area does not need to be provided, as the runtime system gets the parameter type from the method’s signature. Then insert this work area in the parameter table PTAB using the INSERT statement. Finally, assign the name of the calling method to the data object METH. Then call the method using the syntax already shown.
Dynamic Instantiation and Cast Assignments for Data Objects
Partner
Using data references and the statement CREATE DATA, you can create data objects at runtime, as you can with class instances.
Use
Instantiation of Data Objects at Runtime DATA ref TYPE REF TO typename.
SAP
SAP
CREATE DATA ref.
Partner
Use
Then data reference ref then points to the created data object. As an alternative to the static variant, you can also set the data type at runtime.
Generic Typing of Data Objects at Runtime
CREATE DATA ref TYPE typename.
The reference ref must be generically-typed using TYPE REF TO data. The following dynamic variant shows how the type name typename can also be specified using a variable var_type:
Dynamic Instantiation of Data Objects at Runtime DATA ref TYPE REF TO data. DATA var_type TYPE ... . var_type = ... . CREATE DATA ref TYPE (var_type).
© 2004 SAP AG. All rights reserved.
433
Only
Internal
DATA ref TYPE REF TO data.
08-03-2004
Internal
Only
After the method call, the actual parameter GD_MAKE contains the passed value.
Unit 5: Exception Handling and Dynamic Programming
BC401
To access the contents of this data object, you need to dereference the data reference first. For compatibility reasons, you need to use a field symbol if you are working with generically typed data references (TYPE REF TO data).
SAP
SAP
Use
Partner
Only
Internal
Figure 182: Dereferencing Generically Typed Data References
Use Internal
If the data reference is initial or invalid, it cannot be dereferenced. In that case the field symbol remains unchanged and SY-SUBRC is set to 4.
Generating Data Objects at Runtime – Application Example REPORT ... . DATA: ref_itab TYPE REF TO data,
434
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
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.
Partner
This statement ASSIGN ref_itab->* TO assigns the relevant data object (the one to which the data reference in the reference variable ref_itab points) to the field symbol . If the data object is assigned successfully, SY_SUBRC is set to 0.
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
ref_wa
TYPE REF TO data.
FIELD-SYMBOLS: TYPE ANY TABLE,
TYPE ANY,
TYPE ANY.
Internal
Only
PARAMETERS pa_tab TYPE dd02l-tabname DEFAULT ’SPFLI’. START-OF-SELECTION. CREATE DATA ref_itab TYPE STANDARD TABLE OF (pa_tab) WITH NON-UNIQUE DEFAULT KEY.
Partner
ASSIGN ref_itab->* TO . SELECT * FROM (pa_tab) INTO TABLE
Use
UP TO 100 ROWS. CREATE DATA ref_wa LIKE LINE OF . "or: TYPE (pa_tab).
SAP
SAP
ASSIGN ref_wa->* TO . LOOP AT INTO . DO. ASSIGN COMPONENT sy-index OF STRUCTURE TO . IF sy-subrc NE 0.
Partner
Use
NEW-LINE. EXIT. ENDIF. WRITE .
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 row type compatible with that of the table being displayed. Since the name – and thus the row type – of the table is not known until runtime, you should not create the data object until then. Unlike conventional data objects, you can dynamically specify the type of a data object created at runtime. The TYPE addition of the CREATE DATA statement contains the name of the table, so that the system creates the “appropriate” structure.
08-03-2004
© 2004 SAP AG. All rights reserved.
435
Only
Internal
ENDDO. ENDLOOP.
Unit 5: Exception Handling and Dynamic Programming
BC401
The statement ASSIGN ref_wa->* TO assigns the data object to the field symbol. The data type of the table is inherited by the field symbol, so type casting is no longer necessary. You can now write each data record from the SELECT statement into the compatibly-typed data object using the field symbol .
Only
Use
Partner
Internal
If you knew the component names, you could display the fields directly using WRITE -.... 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 are assigned one-by-one to the field symbol and then displayed. When the loop runs out of components, the program requests the next data record.
SAP
SAP
Like object references, data references can be copied using cast operators in reference variables. However, the data reference’s static type must be the same as the dynamic type of the source reference. In this example, the first case meets this condition, the second does not. Note: Without the cast assignment operator ?=, these assignments would be impossible for syntactical reasons alone, because the source and target type are not compatible.
436
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Use
Partner
Figure 183: Cast Assignment for Data References
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
If a data reference variable has been typed statically, it passes on its type attributes whenever it is assigned to an untyped data reference. This is particularly advantageous for the additional information of global data types.
Use
Partner
Only
Internal
SAP Use
Only
Internal
Partner
During dereferencing, the type of reference variable, not data object, to which the reference “points” is the deciding factor. This will be demonstrated in the following example:
SAP
Figure 184: Copying Global Type Information for References – Principle
08-03-2004
© 2004 SAP AG. All rights reserved.
437
Unit 5: Exception Handling and Dynamic Programming
BC401
SAP Use
Caution: This example has been set up intentionally to display that the type of a statically typed reference variable is actually the decisive factor.
Only
Internal
Hint: To get a more consistent result, the reference REF_CITYTO would have had to be typed either generically or in agreement with the data object CITYFROM.
Partner
438
SAP
In the example given here, the reference variable REF_CITYTO has been typed statically using a data element. At runtime, it contains a reference to the data object CITYFROM, which has been typed differently. The reference is then dereferenced through the generically typed field symbol , and it therefore adopts the type attributes of the reference. In this way, for example, the field documentation of the data element is listed during list output.
Use
Partner
Only
Internal
Figure 185: Copying Global Type Information for References – Syntax Example
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
Type Analysis at Runtime Since the introduction of ABAP Objects, there is now a class-based concept called Run Time Type Information (RTTI), which you can use to find out type attributes at runtime. This concept includes all ABAP types, and so covers all of the functions of the now obsolete statements DESCRIBE FIELD and DESCRIBE TABLE. There is a description class for each type with special attributes for special type attributes:
Use
Partner
Only
Internal
Internal
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.
08-03-2004
© 2004 SAP AG. All rights reserved.
439
Only
The class hierarchy of the description classes corresponds to the hierarchy of the types in ABAP Objects. 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.
Partner
Use
SAP
SAP
Figure 186: Dynamic Type Analysis for RTTI Classes
Unit 5: Exception Handling and Dynamic Programming
BC401
Dynamic Data Type Analysis – Application Example ... DATA: ref_descr TYPE REF TO cl_abap_structdescr, wa_comp
TYPE abap_compdescr.
...
Only
Internal
START-OF-SELECTION. ... * get reference to type descripion object by widening cast:
ref_descr ?= cl_abap_typedescr=>describe_by_data( ).
Use
Partner
...
TOP-OF-PAGE. LOOP AT ref_descr->components INTO wa_comp. WRITE wa_comp-name.
SAP Internal
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 REF_DESCR has the type of the subclass CL_ABAP_STRUCTDESCR, we need to assign the object using a widening cast. You can then access the attributes of the description instance in any form. In this example, the component names are displayed as the column headers. We have omitted the formatting options for the sake of clarity.
440
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
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).
Partner
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 row type.
SAP
We can now enhance the application example of dynamic data object instantiation so that the system also displays the column names of the transparent table in the list.
Use
ENDLOOP.
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
Dynamic Object Type Analysis – Application Example CLASS lcl_rental IMPLEMENTATION. ... METHOD
add_vehicle.
*
only interested in busses - implemented using RTTI:
*
(alternative solution would be
*
using caught widening cast: ref_bus ?= sender)
Only
ref_class_descr ?= cl_abap_typedescr=>describe_by_object_ref( sender ). IF ref_class_descr->get_relative_name( ) = ’LCL_BUS’. ENDIF. ENDMETHOD.
"add_vehicle
...
SAP Use
The functional method call again returns the reference to the description instance of the vehicle instance. Only the abstract class CL_ABAP_TYPEDESCR owns the method DESCRIBE_BY_OBJECT_REF. Its returning parameter is typed as a reference to this superclass. However, since the actual parameter REF_CLASS_DESCR has the type of the subclass CL_ABAP_CLASSDESCR, we need to assign the object using a widening cast.
08-03-2004
© 2004 SAP AG. All rights reserved.
441
Only
Internal
The reference to the triggering vehicle instance is mentioned in the SENDER parameter of the aforementioned event handler method. Its dynamic object type is to be analyzed to determine whether the vehicle in question is a bus or a truck.
Partner
We will now build upon this example: The vehicle rental company is now only interested in buses.
SAP
This application example is based on an example about event handling. In that simplified example, we specified that an instance of the vehicle rental class LCL_RENTAL reacts to an appropriate event by entering the vehicle instance that triggered the event into the list of owned vehicles, VEHICLE LIST. So far, the triggering instances could be buses (LCL_BUS) or trucks (LCL_TRUCK).
Use
Partner
APPEND sender TO vehicle_list.
Internal
DATA ref_class_descr TYPE REF TO cl_abap_classdescr.
Unit 5: Exception Handling and Dynamic Programming
BC401
You can then access the attributes of the description instance in any form. The functional method GET_RELATIVE_NAME supplies the class name. Note: You could also fulfill the same purpose without using RTTI classes: You could use a widening cast assignment from SENDER to a reference variable of static type LCL_BUS. That would cause a runtime error for an vehicle instances that are not buses. The system could then catch this runtime error. Not triggering a runtime error would therefore be the condition for entering a vehicle into the vehicle list.
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
442
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
Exercise 25: Type Casting with Data Elements (Optional) Exercise Objectives
Only
Business Example
Use
Partner
In the program for separating the character string into structured flight dates, the default value for the key date is to be calculated differently. The default value in the selection screen should now always be the first day of the next month.
Task 1: Copy the template.
SAP
Copy template: SAPBC401_TABS_PROCESS_DATA or ZBC401_##_PROCESS_DATA
SAP
1.
Program name: ZBC401_##_CASTING
Use
Partner
(Where ## is your two-digit group number). 2.
Activate your copy (or copies). Familiarize yourself with the program and its existing functions.
Define a suitable field symbol for structured access to an elementary date variable. 1.
Define a structure type (suggested name: ST_DATE) with three components: year, month, and day. Assign an appropriate type to each component.
2.
Define a field symbol based on this type (suggested name: ).
Continued on next page
© 2004 SAP AG. All rights reserved.
443
Only
Internal
Task 2:
08-03-2004
Internal
After completing this exercise, you will be able to: • Use field symbols to cast types • Calculate dates
Unit 5: Exception Handling and Dynamic Programming
BC401
Task 3:
Copy the date to the entry parameter PA_DATE.
2.
Assign the input parameter to the field symbol.
3.
Now fill the input parameter with the first day of the next month by using the field symbol to access the pseudo-components for the year, month, and day.
Use
Partner
1.
Internal
Only
Use the field symbol in the event block LOAD-OF-PROGRAM to calculate the default value.
SAP
SAP Only
Internal
Use
Partner
444
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
Solution 25: Type Casting with Data Elements (Optional) Task 1: Copy the template. Copy template: SAPBC401_TABS_PROCESS_DATA or ZBC401_##_PROCESS_DATA Program name: ZBC401_##_CASTING (Where ## is your two-digit group number).
Partner SAP
Familiarize yourself with the program and its existing functions. a)
Carry out this step in the usual manner. Additional information is available in the SAP Library.
Define a structure type (suggested name: ST_DATE) with three components: year, month, and day. Assign an appropriate type to each component. a)
2.
See the source code extract from the model solution
Define a field symbol based on this type (suggested name: ). a)
Only
Internal
Define a suitable field symbol for structured access to an elementary date variable.
See the source code extract from the model solution
Task 3: Use the field symbol in the event block LOAD-OF-PROGRAM to calculate the default value. 1.
Copy the date to the entry parameter PA_DATE. a)
See the source code extract from the model solution Continued on next page
08-03-2004
Partner
1.
Activate your copy (or copies).
SAP
Task 2:
b)
Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_DYNS_CASTING
Use
2.
Use
a)
Internal
Only
1.
© 2004 SAP AG. All rights reserved.
445
Unit 5: Exception Handling and Dynamic Programming
2.
BC401
Assign the input parameter to the field symbol. a)
3.
See the source code extract from the model solution
Now fill the input parameter with the first day of the next month by using the field symbol to access the pseudo-components for the year, month, and day. a)
See the source code extract from the model solution
Only
Internal
Result Source code extract:
Partner
SAPBC401_DYNS_CASTING REPORT sapbc401_dyns_casting. TYPE-POOLS col.
Use
TYPES: BEGIN OF st_flight_c,
SAP
END OF st_flight,
SAP
Use
... END OF st_flight_c, BEGIN OF st_flight, ...
Partner
BEGIN OF st_date, year(4)
TYPE n,
Internal
month(2) TYPE n, day(2)
TYPE n,
END OF st_date.
Only
... FIELD-SYMBOLS TYPE st_date.
PARAMETERS: pa_date LIKE sy-datum, pa_alv
AS CHECKBOX DEFAULT ’X’.
Continued on next page
446
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
LOAD-OF-PROGRAM. pa_date = sy-datum. ASSIGN pa_date TO CASTING.
-day = ’01’. IF -month < 12. -month = -month + 1.
Internal
Only
ELSE. -month = ’01’. -year
= -year + 1.
Partner
ENDIF.
AT SELECTION-SCREEN. IF pa_date < sy-datum. " date in the past
Use
MESSAGE e085(bc401). ENDIF.
SAP
SAP
START-OF-SELECTION.
Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
447
Unit 5: Exception Handling and Dynamic Programming
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
448
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
Exercise 26: Creating Data Objects at Runtime Exercise Objectives
Only
Business Example
Hint: This program should help you to become familiar with the new programming techniques and to create an executable sample application. The Data Browser is already installed a standard tool for the ABAP Workbench.
Partner
SAP Use
Optimization of runtime requirements is not the focus of this exercise.
Task 1: Copy the template.
Internal
1.
Copy template: SAPBC401_DYNT_CREATE_DATA_SQL Program name: ZBC401_##_CREATE_DATA_SQL
Only
(Where ## is your two-digit group number). 2.
Activate your copy (or copies). Familiarize yourself with the program and its existing functions.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
SAP
Here, the user should only be able to select a table name. Filtering by field contents and other functions should be delegated to the SAP Grid Control, which should be used for outputting the data.
Use
Partner
You are to develop a program that can be used as an “ad-hoc data browser”.
Internal
After completing this exercise, you will be able to: • Dynamically instantiate data objects • Program dynamic Open SQL statements
449
Unit 5: Exception Handling and Dynamic Programming
BC401
Task 2:
Define a reference for the internal table that is to be generated (suggested name REF_ITAB).
2.
At program runtime, create a standard table with a non-unique default key. At this time, it is known which row type must be used.
3.
Assign a suitably-typed field symbol to the generated internal table so that its contents can be accessed (suggested name: ).
4.
Before calling the screen, program an Open SQL statement that copies data records from the selected database table into the internal table using an array fetch. If an error occurs, make sure the program terminates.
Task 3: Display the content of the internal table with an SAP Grid Control instance.
Use
Define a reference for the SAP Grid Control instance to be created (suggested name: REF_ALV).
2.
Within the PBO module INIT_CONTROLS_0100 already created, create an instance of the SAP Grid Control.
3.
Pass the filled internal table to this SAP Grid Control instance. If an error occurs, make sure that the program terminates. Hint: The relevant method is called SET_TABLE_FOR_FIRST_DISPLAY. It is sufficient to pass the row type to the parameter I_STRUCTURE_NAME and the name of the internal table to the parameter IT_OUTTAB.
450
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
Hint: The relevant class is called CL_GUI_ALV_GRID.
Partner
1.
SAP
SAP
Hint: For simplicity reasons, use the addition UP TO ... ROWS to limit the runtime requirements of the program. Later, you can program a more elegant solution for this.
Use
Partner
1.
Internal
Only
At runtime, create an internal table whose row type is compatible with the user’s selection. Import data from the selected transparent table into the internal table.
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
Solution 26: Creating Data Objects at Runtime Task 1: Copy the template. 1.
Copy template: SAPBC401_DYNT_CREATE_DATA_SQL
Only
(Where ## is your two-digit group number). Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_DYPS_CREATE_DATA_SQL 2.
Activate your copy (or copies). Familiarize yourself with the program and its existing functions. Carry out this step in the usual manner. Additional information is available in the SAP Library.
Task 2:
Use
1.
Define a reference for the internal table that is to be generated (suggested name REF_ITAB).
2.
At program runtime, create a standard table with a non-unique default key. At this time, it is known which row type must be used. a)
3.
See the source code extract from the model solution
See the source code extract from the model solution
Assign a suitably-typed field symbol to the generated internal table so that its contents can be accessed (suggested name: ). a)
See the source code extract from the model solution
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
451
Only
Internal
a)
Partner
At runtime, create an internal table whose row type is compatible with the user’s selection. Import data from the selected transparent table into the internal table.
SAP
SAP
a)
Use
Partner
a)
Internal
Program name: ZBC401_##_CREATE_DATA_SQL
Unit 5: Exception Handling and Dynamic Programming
4.
BC401
Before calling the screen, program an Open SQL statement that copies data records from the selected database table into the internal table using an array fetch. If an error occurs, make sure the program terminates. Hint: For simplicity reasons, use the addition UP TO ... ROWS to limit the runtime requirements of the program. Later, you can program a more elegant solution for this.
Only
See the source code extract from the model solution
Task 3: 1.
Define a reference for the SAP Grid Control instance to be created (suggested name: REF_ALV).
Use
Partner
Display the content of the internal table with an SAP Grid Control instance.
Hint: The relevant class is called CL_GUI_ALV_GRID.
SAP
Within the PBO module INIT_CONTROLS_0100 already created, create an instance of the SAP Grid Control. a)
See the source code extract from the model solution
Pass the filled internal table to this SAP Grid Control instance. If an error occurs, make sure that the program terminates.
Internal
a)
See the source code extract from the model solution
Result Source code extract:
Continued on next page
452
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Hint: The relevant method is called SET_TABLE_FOR_FIRST_DISPLAY. It is sufficient to pass the row type to the parameter I_STRUCTURE_NAME and the name of the internal table to the parameter IT_OUTTAB.
Partner
3.
See the source code extract from the model solution
SAP
2.
Use
a)
Internal
a)
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
SAPBC401_DYNS_CREATE_DATA_SQL REPORT
sapbc401_dyns_create_data_sql
.
DATA: ok_code LIKE sy-ucomm, popans.
Only
Internal
DATA: ref_docking TYPE REF TO cl_gui_docking_container, ref_alv TYPE REF TO cl_gui_alv_grid.
Partner
DATA ref_itab TYPE REF TO data.
FIELD-SYMBOLS TYPE ANY TABLE.
Use SAP
SAP
PARAMETERS pa_tab TYPE dd02l-tabname DEFAULT ’SPFLI’.
START-OF-SELECTION.
Use
Partner
CREATE DATA ref_itab TYPE STANDARD TABLE OF (pa_tab) WITH NON-UNIQUE DEFAULT KEY. ASSIGN ref_itab->* TO .
Internal
SELECT * FROM (pa_tab) INTO TABLE UP TO 100 ROWS. IF sy-subrc <> 0.
Only
MESSAGE a702(bc401). ENDIF.
CALL SCREEN 100.
*&---------------------------------------------------------------------*
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
453
Unit 5: Exception Handling and Dynamic Programming
*&
Module
clear_ok_code
BC401
OUTPUT
*&---------------------------------------------------------------------* *
text
*----------------------------------------------------------------------* MODULE clear_ok_code OUTPUT. CLEAR ok_code. " clear_ok_code
OUTPUT
*&---------------------------------------------------------------------* *&
Module
STATUS_0100
OUTPUT
*&---------------------------------------------------------------------* *
text
Partner
*----------------------------------------------------------------------* MODULE status_0100 OUTPUT. SET PF-STATUS ’ST100’. ENDMODULE.
" STATUS_0100
Use
SET TITLEBAR ’T100’. OUTPUT
SAP
Module
init_controls_0100
OUTPUT
*&---------------------------------------------------------------------* *
text
SAP
*&---------------------------------------------------------------------* *&
Internal
Only
ENDMODULE.
Use
CREATE OBJECT ref_docking
Partner
MODULE init_controls_0100 OUTPUT.
Internal
*----------------------------------------------------------------------*
IF ref_docking IS INITIAL.
EXPORTING *
SIDE
= DOCK_AT_LEFT
Only
extension
= 2000
EXCEPTIONS OTHERS
= 6
. IF sy-subrc <> 0. MESSAGE a015(rfw). ENDIF.
CREATE OBJECT ref_alv
Continued on next page
454
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
EXPORTING i_parent
= ref_docking
EXCEPTIONS error_cntl_create = 1 error_cntl_init
= 2
error_cntl_link
= 3
error_dp_create
= 4
OTHERS
= 5
Internal
Only
. IF sy-subrc <> 0. MESSAGE a702(bc401).
Partner
ENDIF.
CALL METHOD ref_alv->set_table_for_first_display
i_structure_name
Use
EXPORTING = pa_tab
CHANGING it_outtab
=
SAP
SAP
EXCEPTIONS invalid_parameter_combination = 1 program_error
= 2
too_many_lines
= 3
OTHERS
= 4
Partner
Use
. IF sy-subrc <> 0. MESSAGE a702(bc401).
Internal
ENDIF.
ENDIF. " init_controls_0100
Only
ENDMODULE.
OUTPUT
*&---------------------------------------------------------------------* *&
Module
leave_programm
INPUT
*&---------------------------------------------------------------------* *
text
*----------------------------------------------------------------------* MODULE leave_programm INPUT. CLEAR popans.
Continued on next page
08-03-2004
© 2004 SAP AG. All rights reserved.
455
Unit 5: Exception Handling and Dynamic Programming
BC401
CALL FUNCTION ’POPUP_TO_CONFIRM_STEP’ EXPORTING textline1
= text-dml
textline2
= text-rcn
titel
= text-cnc
cancel_display = ’ ’ IMPORTING answer
= popans.
Internal
Only
CASE popans. WHEN ’J’. LEAVE PROGRAM. WHEN ’N’. CLEAR ok_code. " leave_programm
INPUT
*&---------------------------------------------------------------------* *&
Module
USER_COMMAND_0100
INPUT
*&---------------------------------------------------------------------*
SAP
text
*----------------------------------------------------------------------* MODULE user_command_0100 INPUT. CASE ok_code.
SAP
*
Use
Partner
ENDCASE. ENDMODULE.
WHEN ’BACK’.
Partner
Use
CLEAR popans. CALL FUNCTION ’POPUP_TO_CONFIRM_STEP’
Internal
EXPORTING textline1
= text-dml
textline2
= text-rbk
titel
= text-bak
cancel_display = ’ ’
Only
IMPORTING answer
= popans.
CASE popans. WHEN ’J’. LEAVE TO SCREEN 0. WHEN ’N’. ENDCASE. WHEN ’EXIT’.
Continued on next page
456
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20
CLEAR popans. CALL FUNCTION ’POPUP_TO_CONFIRM_STEP’ EXPORTING textline1
= text-dml
textline2
= text-rex
titel
= text-ext
cancel_display = ’ ’ IMPORTING = popans.
Internal
Only
answer IF popans = ’J’. LEAVE PROGRAM. ENDIF.
Partner
WHEN OTHERS. ENDCASE. " USER_COMMAND_0100
INPUT
Use
ENDMODULE.
SAP
SAP
Flow Logic Screen 100 PROCESS BEFORE OUTPUT. MODULE clear_ok_code. MODULE status_0100.
Partner
Use
MODULE init_controls_0100.
PROCESS AFTER INPUT. MODULE leave_programm AT EXIT-COMMAND.
Only
Internal
MODULE user_command_0100.
08-03-2004
© 2004 SAP AG. All rights reserved.
457
Unit 5: Exception Handling and Dynamic Programming
BC401
Lesson Summary
Only Partner
Related Information ... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.
Internal
You should now be able to: • Dynamically create objects • Dynamically access class and object components • Define field symbols • Define data references • Dereference data references • Dynamically create data objects • Ascertain the attributes of data objects at runtime
Use
SAP
SAP Only
Internal
Use
Partner
458
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Unit Summary
Unit Summary
Use
Only Partner
Internal
You should now be able to: • Create exception classes • Trigger class-based exceptions in ABAP Objects programs • Propagate class-based exceptions in ABAP Objects programs • Handle class-based exceptions in ABAP Objects programs • Map class-based exceptions in ABAP Objects programs to each other • Dynamically create objects • Dynamically access class and object components • Define field symbols • Define data references • Dereference data references • Dynamically create data objects • Ascertain the attributes of data objects at runtime
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
459
Unit Summary
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
460
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Test Your Knowledge
Test Your Knowledge 1.
The new exception concept replaces the old one. Thus, all old source code sections must be rewritten. As of SAP Web AS 6.20, function modules from the SAP standard system automatically raise object-oriented exceptions. Determine whether this statement is true or false.
Only
Unlike the old exceptions, those embodying the new concept can also be raised from subroutines and propagated. Determine whether this statement is true or false.
□ □ 3.
True False
The new exception classes can only be defined globally. This ensures central maintenance and reuse.
SAP
SAP
Determine whether this statement is true or false.
Internal
4.
True False
When you define an exception class, the superclass you choose specifies whether or not its exceptions must be caught explicitly with a TRY-CATCH-ENDTRY block and, if so, how the system reacts if the exception is not caught. Determine whether this statement is true or false.
08-03-2004
True False
Only
□ □
Partner
Use
□ □
Use
Partner
2.
True False
Internal
□ □
© 2004 SAP AG. All rights reserved.
461
Test Your Knowledge
5.
BC401
Which of the following statements about dynamic programming are correct?
Partner SAP
D
□
E
□
F
□
G
□
H
□
I
□
J
□
K
Internal
Use
□
462
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
C
Partner
□
Field symbols contain addresses of data objects at runtime. If you change the contents of a field symbol, you also change the address of the assigned data object. If you change the contents of a field symbol, you consequently change an address. That is, the field symbol then does not point to the data object anymore. You can use field symbols to access data objects as if their type was not static. There are no data references in ABAP Objects. Instead, there are only dereferenced pointers with field symbols. If you change the contents of an assigned data reference, you consequently change an address. That is, the reference then does not point to the data object anymore. In ABAP Objects, you can set the type of an object when you define the reference or you can do it later when the generation takes place at runtime. In ABAP Objects, you can set the type of a data object during the definition or you can do it later when the generation takes place at runtime. A globally typed data reference points to a data object that was typed with a different global type. Furthermore, the data reference is dereferenced using a generically typed field symbol. If this field symbol is then used to access the data object, the type attributes of the data object, not the data reference, take effect. If a data reference variable has been typed statically, it passes on its type attributes whenever it is assigned to an untyped data reference. RTTI classes can be used in ABAP Objects to specify all type attributes of a (data) object at runtime.
SAP
A B
Use
□ □
Internal
Only
Choose the correct answer(s).
BC401
Test Your Knowledge
Answers 1.
The new exception concept replaces the old one. Thus, all old source code sections must be rewritten. As of SAP Web AS 6.20, function modules from the SAP standard system automatically raise object-oriented exceptions.
Refer to the relevant section of the lesson. Unlike the old exceptions, those embodying the new concept can also be raised from subroutines and propagated. Answer: True Refer to the relevant section of the lesson. The new exception classes can only be defined globally. This ensures central maintenance and reuse.
SAP
SAP
3.
Answer: False Refer to the relevant section of the lesson.
Use
Answer: True Refer to the relevant section of the lesson. 5.
Which of the following statements about dynamic programming are correct? Answer: A, D, F, G, H, J, K Refer to the relevant section of the lesson.
08-03-2004
© 2004 SAP AG. All rights reserved.
463
Only
Internal
When you define an exception class, the superclass you choose specifies whether or not its exceptions must be caught explicitly with a TRY-CATCH-ENDTRY block and, if so, how the system reacts if the exception is not caught.
Partner
4.
Use
Partner
2.
Internal
Only
Answer: False
Course Summary
BC401
Course Summary You should now be able to: •
Use
Partner
• • •
Internal
Only
• • •
Name and use the syntax elements for Unicode-compatible character string processing Use internal tables to optimum effect Use fundamental elements of object-oriented modeling in UML Create ABAP Objects programs that contain all useful object-oriented programming techniques Use the relevant tools to create object-oriented Repository objects Define, raise, and handle class-based exceptions Name and use the syntax elements for dynamic programming
SAP
SAP Only
Internal
Use
Partner
464
© 2004 SAP AG. All rights reserved.
08-03-2004
Appendix 1 Calling Programs and Passing Data
In ABAP Objects, there are two main ways of starting programs from within other programs:
SAP
Restart The current program is terminated and the called program is started.
SAP
Background Information The flow of the calling program is interrupted while the called program runs and is then continued after the called program has finished.
Use
Partner
Only
Internal
Calling Programs
Only
Internal
Use
Partner
Figure 187: Calling Programs
08-03-2004
© 2004 SAP AG. All rights reserved.
465
Appendix 1: Calling Programs and Passing Data
BC401
Complete programs within a single user session can run only sequentially. We refer to this technique as sequential calling. If you want to run activities in parallel, you must use function modules. Note: More information about this technique is available in other courses and the ABAP keyword documentation for the statement CALL FUNCTION ... STARTING NEW TASK ... .
Use
Partner
Only
Internal
SAP
SAP
Use
If you use the AND RETURN addition, the system resumes processing with the first statement after the SUBMIT statement, once the called program has finished. Note: For further information, refer to the ABAP keyword documentation for the SUBMIT statement.
466
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
To start an executable program, use the SUBMIT statement. If you use the VIA SELECTION-SCREEN addition, the system displays the standard selection screen of the program (if one has been defined).
Partner
Figure 188: Calling an Executable Program
BC401
Appendix 1: Calling Programs and Passing Data
Use
Partner
Only
Internal
Figure 189: Calling a Transaction
SAP Use
To force the termination of a program, use the LEAVE PROGRAM statement. If the statement is used in a program that you called using CALL TRANSACTION ’T_CODE’ or SUBMIT prog_name AND RETURN , the system resumes processing at the next statement after the call in the calling program. Otherwise, the user returns to the application menu from which he or she started the program. If you use the ... AND SKIP FIRST SCREEN addition, the system does not display the screen contents of the first screen in the transaction.
08-03-2004
© 2004 SAP AG. All rights reserved.
467
Only
Internal
The statement CALL TRANSACTION ’T_CODE’ allows you to insert ABAP programs that have a transaction code.
Partner
LEAVE TO TRANSACTION ’T_CODE’ statement you terminate the current program and start the transaction with the transaction code T_CODE. The statement is the equivalent to entering /nT_CODE in the command field.
SAP
With the
Appendix 1: Calling Programs and Passing Data
BC401
Caution: The flow logic is processed. If the transaction you called with CALL TRANSACTION ’T_CODE’ uses update techniques, you can use the UPDATE ... addition to specify the update technique (asynchronous (default), synchronous, or local) that the program should use.
Only
Management of Working Memory
Use
Partner
The way in which the working memory is organized from the program’s point of view can be represented easily using a model.
Internal
Note: For further information, refer to the course BC414 (Programming Database Updates) and the SAP Library.
SAP
SAP Only
Internal
Use
Partner
Figure 190: Logical Memory Model
468
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Appendix 1: Calling Programs and Passing Data
There is a distinction between internal and external sessions: •
Data for a program is only visible within an internal session. In general, data visibility is restricted to the relevant program.
Partner
The following illustrates how the stack inside an external session changes with various program calls. The starting situation for the first case is the execution of the statement SUBMIT ... AND RETURN or CALL TRANSACTION within a program.
Internal
Only
•
Generally, an external session is connected to an SAP Web AS window. The session can be opened with System → New session or by entering /oT_CODE in the command field. You can have up to six external sessions open simultaneously in one terminal session. External sessions are subdivided into internal sessions (placed on a stack). Each program that you run occupies its own internal session. Each external session can contain up to nine internal sessions.
Use
SAP
SAP Only
Internal
Use
Partner
Figure 191: Inserting a Program -1
08-03-2004
© 2004 SAP AG. All rights reserved.
469
Appendix 1: Calling Programs and Passing Data
BC401
Use
Partner
Only
Internal
Figure 192: Inserting a Program -2
SAP
SAP
When you insert a program, the system creates a new internal session, which in turn creates a new program context. The new session is placed on the stack. The program context of the calling program therefore remains intact.
Only
Internal
Use
Partner
Figure 193: Terminating the Inserted Program
470
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Appendix 1: Calling Programs and Passing Data
When the called (inserted) program finishes, its internal session (the top one in the stack) is deleted. Processing is resumed in the next-highest internal session in the stack. When you end a program and start a new one, there is a distinction between calling an executable program and calling a transaction, with regard to memory areas. The starting situation for the second case is therefore the execution of the statement SUBMIT within a program.
Use
Partner
Only
Internal Partner
Use
SAP
SAP Only
Internal
Figure 194: Restarting an Executable Program -1
08-03-2004
© 2004 SAP AG. All rights reserved.
471
Appendix 1: Calling Programs and Passing Data
BC401
Use
Partner
Only
Internal
SAP
Only
Internal
Partner
The starting situation for the third case is therefore the execution of the statement LEAVE TO TRANSACTION within a program.
SAP
If you call an executable program using its program name (terminating the calling program), the system deletes the internal session of the program that you are terminating (the top one from the stack). The system creates a new internal session, which in turn creates the program context of the called program. The new session is placed on the stack. Existing program contexts remain intact. The topmost internal session on the stack is replaced.
Use
Figure 195: Restarting an Executable Program -2
472
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Appendix 1: Calling Programs and Passing Data
Use
Partner
Only
Internal
Figure 196: Restarting a Transaction -1
SAP
SAP Only
Internal
Use
Partner
Figure 197: Restarting a Transaction -2
If you start a program using its transaction code (if one was defined), all of the internal sessions on the stack are deleted. The system creates a new internal session, which in turn creates the program context of the called program.
08-03-2004
© 2004 SAP AG. All rights reserved.
473
Appendix 1: Calling Programs and Passing Data
BC401
Caution: Therefore, the ABAP memory is also initialized after the call.
Data Transfer There are various ways of passing data to programs running in separate internal sessions. However, we are only dealing with those that are platform-independent and only exchange data transiently.
Use
Partner
Only
Internal
• • • • •
The interface of the called program (usually a standard selection screen) ABAP memory SAP Memory Database tables Local files on your presentation server
The following only introduces the first three techniques, because only these meet the specified requirements.
474
© 2004 SAP AG. All rights reserved.
08-03-2004
Only
Internal
You can use the following techniques to pass data:
Partner
Use
SAP
SAP
Figure 198: Passing Data Between Programs – Overview
BC401
Appendix 1: Calling Programs and Passing Data
Figure 199: Passing Data Using the Program Interface
• •
By specifying a variant for the selection screen when you call the program When the program is called, you predefine specific values for the input fields
Use
Partner
When you call ABAP programs that have a standard selection screen, you can pass data for the input fields in the call. There are two ways to do this:
Internal
Only
For further information about passing data using database tables or the shared buffer, refer to the ABAP keyword documentation for the EXPORT and IMPORT statements. For further information about transferring data between an ABAP program and your presentation server, refer to the documentation for the function modules GUI_UPLOAD and GUI_DOWNLOAD.
SAP
SAP Only
Internal
Use
Partner
Figure 200: Preassigning Values for Input Fields
The WITH addition to the SUBMIT statement allows you to preassign values for parameters and selection options on a standard selection screen of the called executable program. The relational operators EQ, NE, ... and the inclusion operators I and E have the same meanings as with select-options.
08-03-2004
© 2004 SAP AG. All rights reserved.
475
Appendix 1: Calling Programs and Passing Data
BC401
If you want to predefine several selections for a selection option, you can use the RANGE statement instead of individual WITH additions. The RANGES statement creates a selection table, which you can fill as though it were a selection option. You then pass the whole table to the executable program. If you want to display the standard selection screen when you call the program, use the VIA SELECTION-SCREEN addition.
Only
Use
Partner
For further information about working with variants and other syntax variants of the WITH addition, refer to the ABAP keyword documentation for the SUBMIT statement.
Internal
In the ABAP Editor, use the statement pattern to insert a program call using SUBMIT. The pattern supplies the names of the parameters and selection options that are available on the standard selection screen.
SAP
SAP
Internal
Use
Partner
476
© 2004 SAP AG. All rights reserved.
Only
Figure 201: ABAP Memory and SAP Memory
08-03-2004
BC401
Appendix 1: Calling Programs and Passing Data
You can use the SAP Memory and the ABAP memory to pass data between programs: •
SAP Memory is a user-specific memory area for storing field values. It is therefore of limited use when passing data between internal sessions. Values in SAP Memory are retained for the duration of the user’s terminal session. The memory can be used between sessions in the same terminal session. All external sessions can access SAP Memory.
Only
ABAP memory is also user-specific. There is a local ABAP memory for each external session. You can use it to exchange any ABAP data objects (fields, structures, internal tables, complex objects) between the internal sessions in any one external session. When the user exits an external session (/i in the command field), the corresponding ABAP memory is automatically initialized or released.
Use
Partner
•
Internal
You can use the contents of SAP Memory as default values for screen fields.
SAP
SAP Only
Internal
Use
Partner
Figure 202: Passing Data Using the ABAP Memory
Use the EXPORT ... TO MEMORY statement to copy any number of ABAP variables with their current values (data cluster) to the ABAP memory. The ID... addition (maximum 32 characters long) enables you to identify different clusters.
08-03-2004
© 2004 SAP AG. All rights reserved.
477
Appendix 1: Calling Programs and Passing Data
BC401
If you use a new EXPORT TO MEMORY statement for an existing data cluster, the new one will overwrite the old. The IMPORT ... FROM MEMORY ID ... statement allows you to copy data from the ABAP memory into the corresponding fields of your ABAP program.
To release a data cluster, use the FREE MEMORY ID ... statement.
Use
Partner
Caution: Remember when you call programs using transaction codes that you can use the ABAP memory to pass data to the transaction only when calling it (CALL TRANSACTION).
Internal
Only
In the IMPORT statement, you can also restrict the selection to a part of the data cluster. The variables into which you want to read data from the cluster in the ABAP memory must have the same types in both the exporting and the importing programs.
SAP
SAP
Internal
Use
Partner
Figure 203: Passing Parameters Using the SAP Memory
Only
478
© 2004 SAP AG. All rights reserved.
08-03-2004
BC401
Appendix 1: Calling Programs and Passing Data
You can define memory areas (parameters) in the SAP Memory in various ways: •
By creating input/output fields with reference to the ABAP Dictionary. These adopt the parameter name of the data element to which they refer. Alternatively, you can enter a name in the attributes of the input/output fields.
Only
To find out about the names of the parameters assigned to input fields, display the input help (F4) for the field, and choose Technical info.
SAP
SAP
•
You can also fill a memory area directly using the statement SET PARAMETER ID ’PAR_ID’ FIELD var. then read it using GET PARAMETER ID ’PAR_ID’ FIELD var. . Finally, you can define parameters in the Object Navigator and let the user fill them with values.
Use
Partner
•
Internal
Here, you can also choose whether the entries from the field should be transferred to the parameter (SET), or whether the input field should be filled with the value from the parameter (GET).
Only
Internal
Use
Partner
Figure 204: Passing Data Using an Internal Table – Preview
08-03-2004
© 2004 SAP AG. All rights reserved.
479
Appendix 1: Calling Programs and Passing Data
BC401
When you call a transaction using the statement CALL TRANSACTION ’T_CODE’ USING bi_itab, you can run the transaction T_CODE using the values from bi_itab in the screen fields. The internal table must have the structure BDCDATA and be filled accordingly.
You can use the MESSAGES INTO statement to specify an internal table into which any system messages should be written. The internal table must be typed according to the structure BDCMSGCOLL.
This technique is useful if, for example: •
SAP
SAP
•
You are processing in the foreground, but the input fields have not been filled using GET parameters You want to process the transaction in the background. In this case, you normally have to pass function codes as well.
Use
Partner
You can find out if the transaction was executed successfully from the return value SY-SUBRC.
Internal
Only
The MODE addition allows you to specify whether the screen contents should all be displayed (A - the default setting), only displayed when an error occurs (E), or not displayed at all (N).
Internal
Use
Partner
480
© 2004 SAP AG. All rights reserved.
Only
Figure 205: Fields of the Global Type BDCDATA
08-03-2004
BC401
Appendix 1: Calling Programs and Passing Data
Filling the internal table in “batch input format”: •
•
Each screen that is to be processed and filled automatically in the transaction must be identified by a row in which only the fields PROGRAM, DYNPRO, and DYNBEGIN are filled. After the record that identifies the screen, use a separate BDCDATA record for each field you want to fill. These records use the table fields FNAM and FVAL. You can fill the following fields:
Only
Input/output fields (with data) The command field BDC_OKCODE (with a function code) The cursor positioning field, BDC_CURSOR (with a field name)
For further information, refer to the course BC420 (Data Transfer) and the SAP Library.
Use
Partner
This technique is also one of the possible ways of transferring data from non-SAP systems. To do so, the internal table in the BDCDATA format must be filled completely.
Internal
– – –
SAP
SAP Only
Internal
Use
Partner
Figure 206: Passing Data Using an Internal Table – Application Example
The above example refers to the example transaction BC401_CALD_CTA_U in package BC401. When the user creates a new customer entry, the program calls transaction BC401_CALD_CRE_CUST. This transaction has
08-03-2004
© 2004 SAP AG. All rights reserved.
481
Appendix 1: Calling Programs and Passing Data
BC401
not implemented an import from the ABAP memory, and its input fields are not set as GET parameters. The customer data is therefore passed using an internal table and the transaction is processed in the background. If the operation is successful, the new customer data record can be entered in the waiting list. The filled internal table in BDCDATA format is illustrated above.
Only
Use
Partner
Internal
At runtime, CURRENT_NAME stands for the customer name adopted from the input field, CURRENT_CITY stands for the city. You address the command field using BDC_OKCODE. Here you enter the function code that is triggered by the user choosing a function key, pushbutton, or menu entry during the dialog flow (or by entering a code directly in the command field).
SAP
SAP Only
Internal
Use
Partner
482
© 2004 SAP AG. All rights reserved.
08-03-2004
Index Only SAP Use Internal
08-03-2004
© 2004 SAP AG. All rights reserved.
483
Only
basis class, 371 BINARY SEARCH, 47
CA, 6 CALL METHOD, 139–140 EXCEPTION-TABLE, 429 EXCEPTIONS, 129 EXPORTING, 128 IMPORTING, 128 PARAMETER-TABLE, 429–430 calling methods dynamically, 430 cardinality, 112 cast assignment operator, 436 CATCH, 386 CHANGING, 128 character length, 3, 5 character representation internal, 3 character set table, 3 character-type, 5 class, 106, 121 abstract, 352 CL_ABAP_CHAR_UTILITIES, 5
Partner
B
C
SAP
abstraction, 108 ACTIVATION, 269 aggregation, 113, 137 alias name, 230, 238 ALIASES, 230 alignment, 7 alignment gap, 7 alignment requirement, 7 APPEND, 30–31, 39 SORTED BY, 31 ASCII character set, 3 ASSIGN, 423, 434 CASTING, 424 CASTING TYPE, 424 association, 112 binary, 112 recursive, 112 AT NEW, 37, 42 attribute, 122 AGENT, 371 KERNEL_ERRID, 386 PREVIOUS, 397 private, 124 public, 124 static, 126
Use
Partner
A
byte sequence processing, 4–5 BYTE-CA, 7 BYTE-CN, 7 BYTE-CO, 7 BYTE-CS, 7 BYTE-NA, 7 BYTE-NS, 7 byte-type, 5
Internal
Numerics/Symbols ~, 229–230 ?=, 200, 235, 436 [], 38 ->*, 427, 434
Index
BC401
Only Partner SAP Use Internal
Only
08-03-2004
Partner
DATA TYPE REF TO, 134, 427, 437 TYPE REF TO data, 427 data reference variables, 426 data references, 426 data type table-type, 23 database management system object-oriented, 370 DEFAULT, 128 DEFAULT KEY, 26 DEFINITION, 122 definition part, 122 delegation, 115 delegation principle, 102 DELETE, 32, 34
SAP
© 2004 SAP AG. All rights reserved.
D
Use
484
CN, 6 CO, 6 COLLECT, 30 ASSIGNING, 43 REFERENCE INTO, 43 COMMIT WORK, 371 component interface, 237 composition, 113 compound interface, 237 constructor, 144, 191 static, 146 CONSTRUCTOR, 144 container control, 326 control level processing, 37, 42 CP, 6 CREATE DATA, 433 TYPE, 433 CREATE OBJECT, 135 TYPE, 429 CS, 6
Internal
CL_ABAP_CLASSDESCR, 441 CL_ABAP_STRUCTDESCR, 440 CL_ABAP_TYPEDESCR, 439–441 CL_GUI_ALV_GRID, 326 CL_GUI_CUSTOM_CONTAINER, 326 definition part, 122 final, 353 friendship, 355 instantiation, 354 persistent, 370 CLASS, 121, 307 ABSTRACT, 352 CREATE, 354 DEFINITION, 121 FINAL, 353 FRIENDS, 355 INHERITING FROM, 188 PRIVATE SECTION, 125 PUBLIC SECTION, 125 class actor, 371 class agent, 371 class attribute, 126 Class Builder display settings, 319 editing class components, 313 class diagram, 111 CLASS EVENTS, 266 class method, 131 CLASS_CONSTRUCTOR, 146 CLASS-METHODS, 131 classes without multiple instantiation, 357 CLEANUP, 387, 392 CLEAR, 33
BC401
Index
G Garbage Collector, 136 generalization, 113, 186 global class
© 2004 SAP AG. All rights reserved.
485
Only SAP Use Internal
Only
field symbol, 422 FIELD-SYMBOLS, 423 fragment view, 7 FREE, 33 friend concept, 355 friendship relationship, 355 inheritance, 356 function CHARLEN, 5 STRLEN, 6 XSTRLEN, 6 function group data management, 96
Partner
08-03-2004
F
SAP
encapsulation, 96, 124 ENDAT, 37, 42 ENDTRY, 386 Enjoy Demo Center, 328 event static, 263 event handler method, 264 event-controlling, 103 EVENTS, 266 exception, 383 class-based, 383 mapping, 397–398 propagate, 386, 390 exception chain, 384, 397 exception class CX_DYNAMIC_CHECK, 385, 396 CX_NO_CHECK, 385, 396, 432 CX_OS_OBJECT_EXISTING, 371 CX_OS_OBJECT_NOT_FOUND, 372 CX_ROOT, 385, 397 CX_STATIC_CHECK, 385, 396
Use
Partner
E
CX_SY_ARITHMETIC_ERROR, 388 CX_SY_ARITHMETIC_OVERFLOW, 387 CX_SY_MOVE_CAST_ERROR, 202, 235 CX_SY_ZERODIVIDE, 386 global, 384 inheritance hierarchy, 396 local, 384 superclass, 396 Exception class, 384 exception handling, 384, 386 static check, 396 syntax check, 396 exception instance, 384 exception texts multiple, 385 EXPORT TO DATA BUFFER, 5
Internal
ADJACENT DUPLICATES FROM, 32 TRANSPORTING, 32 WHERE, 32 dereferencing, 427, 434, 437–438 dereferencing operator, 427, 434, 437 DESCRIBE FIELD, 439 LENGTH, 6 DESCRIBE TABLE, 439 destructor, 145 downcast, 200, 235
Index
BC401
print, 313 test, 314
H
Only
I
LOOP AT, 36–37 ASSIGNING, 42, 48 REFERENCE INTO, 43, 48 TRANSPORTING NO FIELDS, 37 WHERE, 47
M ME, 147 MESSAGE, 388 method, 128
08-03-2004
Only
Partner SAP Use Internal
L
Partner
© 2004 SAP AG. All rights reserved.
KEY, 26
SAP
486
K
Use
IMPORT FROM DATA BUFFER, 5 IN BYTE MODE, 6 IN CHARACTER MODE, 5 indicator OO transaction model, 329 information hiding, 124 inheritance, 103 INITIAL SIZE, 28, 32 INSERT, 30–31 ASSIGNING, 43 REFERENCE INTO, 43 instance, 107 instance attribute, 126 instance constructor, 144, 191 visibility section, 354 instance event, 263 instance method, 131 instantiating objects dynamically, 429 instantiation class, 133 data type, 433 interface class, 124 compound, 237 method, 128 INTERFACE, 229 interface resolution operator, 229–230
Internal
handler table, 270 hash algorithm, 45 hash function, 45 hashed table, 24, 45, 52 HASHED TABLE, 25 header line, 38
INTERFACES, 229 internal table attributes, 23 column, 22 control level processing, 37, 42 data type, 23 entry, 22 hash, 24 hash management, 45 header line, 38 index access, 23 initial size, 28 key, 23 key access, 23 row type, 23 sorted, 24 standard, 24 standard key, 26 standard type, 26 table kind, 23 table scan, 47 unstructured row type, 26, 44 IS ASSIGNED, 424 IS BOUND, 428 IS INITIAL, 428
BC401
Index
Only Partner SAP
object, 106 behavior, 110 identity, 107 persistent, 370 status, 107, 110 Object GUID, 370 object link, 112 Object Management Group (OMG), 109 offset access, 9–10 OO transaction, 328 Open SQL statement dynamic, 429 OPTIONAL, 128
P
© 2004 SAP AG. All rights reserved.
487
Only
package, 110 Persistence Service, 370 persistent, 369 pointer dereferenced, 422 polymorphism, 103, 199, 233 prefix BYTE-, 7 PRIVATE SECTION, 125 processing character strings, 4–5 programming model object-oriented, 100 procedural, 95 PROTECTED SECTION, 192 PUBLIC SECTION, 125
Partner
Use
O
SAP
Internal
NA, 6 namespace class, 130 narrowing cast, 195, 232 NON-UNIQUE, 25 NP, 6 NS, 6 null reference, 134, 428
Use
08-03-2004
N
Internal
abstract, 352 call, 139–140 CREATE_PERSISTENT, 371 DESCRIBE_BY_DATA, 440 DESCRIBE_BY_OBJECT_REF, 441 final, 353 functional, 141 GET_PERSISTENT, 372 GET_RELATIVE_NAME, 442 GET_SOURCE_POSITION, 385 GET_TEXT, 385, 387, 390, 392 private, 130 public, 130 redefinition, 189 REFRESH_TABLE_DISPLAY, 328 SET_TABLE_FOR_FIRST_DISPLAY, 327 signature, 128 static, 131, 353 METHODS, 131 ABSTRACT, 352 FINAL, 353 FOR EVENT, 267 MODIFY, 32, 34 ASSIGNING, 43 REFERENCE INTO, 43 TRANSPORTING, 32 WHERE, 32 MOVE, 135 ?TO, 200, 235, 436 multiple inheritance, 188 multiple instantiation, 100 multiplicity, 112
Index
BC401
R
08-03-2004
Only Partner SAP Use Internal
Only
© 2004 SAP AG. All rights reserved.
Partner
488
table scan, 47 TABLE_LINE, 26, 44, 136 text ID, 391 transaction code, 328 transaction service, 328 transient, 369 TRY, 386 type ABAP_EXCPBIND_TAB, 431 ABAP_PARMBIND_TAB, 431 dynamic, 195 static, 195 TYPE REF TO, 134 TYPE REF TO data, 426
SAP
SAP Control Framework, 324 SAP Grid Control, 325 Self-Reference, 147 SENDER, 267 sequence diagram, 114 SET HANDLER, 269 ACTIVATION, 269
T
Use
S
FOR ALL INSTANCES, 269 signature, 128 singleton, 357 singleton class, 357 SORT, 34 SORTED BY, 31 sorted table, 24, 51 SORTED TABLE, 25 specialization, 113, 185–186 standard key, 26 standard table, 24, 51 STANDARD TABLE, 25 static attribute, 126 static constructor, 146 static method, 131 subclass, 185–186 SUPER, 189 superclass, 185–186 syntax check Unicode check, 4 system field SY-TABIX, 35, 37 SY-TFILL, 35 SY-TLENG, 35
Internal
RAISE EVENT, 267 RAISING, 391 READ TABLE, 35–36 ASSIGNING, 42, 48 BINARY SEARCH, 47 COMPARING, 35 REFERENCE INTO, 43, 48 TRANSPORTING, 36 TRANSPORTING NO FIELDS, 36 READ-ONLY, 123, 125 redefinition, 189 Refactoring Assistant, 322 reference independent, 136 validity, 428 reference semantics, 427 reference types, 437 reference variable, 134, 426 data type, 437 REFRESH, 33 registration, 268, 270 RETURNING, 128 role, 112 role design pattern, 204 RTTI, 439 runtime error BCD_ZERODIVIDE, 386 catchable, 384 Runtime Type Identification (RTTI), 439
TYPE REF TO object, 430 TYPES TYPE REF TO, 426, 437 TYPE REF TO data, 426
V
U
W
UML, 109 UNASSIGN, 424 Unicode, 3 fragment view, 7 Unified Modeling Language, 109 UNIQUE, 25 upcast, 195, 232
widening cast, 200, 235 widening cast assignment operator, 200, 235 WITH, 25 DEFAULT KEY, 26 WITH HEADER LINE, 38
value semantics, 423 visibility section protected, 192
Use
Partner
Index
Internal
Only
BC401
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
489
Index
BC401
Use
Partner
Only
Internal
SAP
SAP Only
Internal
Use
Partner
490
© 2004 SAP AG. All rights reserved.
08-03-2004
Feedback Only
Use
Partner
Internal
SAP AG has made every effort in the preparation of this course to ensure the accuracy and completeness of the materials. If you have any corrections or suggestions for improvement, please record them in the appropriate place in the course evaluation.
SAP
SAP Only
Internal
Use
Partner
08-03-2004
© 2004 SAP AG. All rights reserved.
491