BC401 - ABAP Objects

Page 1

BC401 ABAP Objects mySAP Technology

Date Training Center Instructors Education Website

Instructor Handbook

Course Version: 2004 Q1 Course Duration: 5 Day(s) Material Number: 50065634 Owner: Axel Treusch (D021184)

An SAP Compass course - use it to learn, reference it for work


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.

Trademarks •

Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint® and SQL Server® are registered trademarks of Microsoft Corporation.

IBM®, DB2®, OS/2®, DB2/6000®, Parallel Sysplex®, MVS/ESA®, RS/6000®, AIX®, S/390®, AS/400®, OS/390®, and OS/400® are registered trademarks of IBM Corporation.

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.


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.

Typographic Conventions American English is the standard used in this handbook. The following typographic conventions are also used. 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. Also used for cross-references to other documentation both internal (in this documentation) and external (in other locations, such as SAPNet).

08-03-2004

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.

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.

© 2004 SAP AG. All rights reserved.

iii


About This Handbook

BC401

Icons in Body Text The following icons are used in this handbook. Icon

Meaning For more information, tips, or background Note or further explanation of previous point Exception or caution Procedures

Indicates that the item is displayed in the instructor’s presentation.

iv

© 2004 SAP AG. All rights reserved.

08-03-2004


Contents Course Overview ......................................................... vii Course Goals .......................................................... viii Course Objectives ..................................................... ix

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

Unit 2: Introduction to Object-Oriented Programming .......... 87 The Object-Oriented Programming Model......................... 89 Analysis and Design with UML .....................................104 Fundamental Object-Oriented Syntax Elements................. 118

Unit 3: Object-Oriented Concepts and Programming Techniques ............................................................... 179 Inheritance and Casting .............................................182 Interfaces and Casting ..............................................226 Events .................................................................265

Unit 4: Object-Oriented Repository Objects ...................... 305 Global Classes and Interfaces .....................................307 Special Object-Oriented Programming Techniques .............354 Persistent Objects in ABAP Objects for SAP Web Application Server 6.20 .......................................................371

Unit 5: Exception Handling and Dynamic Programming ...... 385 Exception Handling in ABAP Objects for the SAP Web Application Server 6.20 .......................................................387 Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20 .........................................431

Appendix 1: Calling Programs and Passing Data

............ 475

Index ....................................................................... 491

08-03-2004

© 2004 SAP AG. All rights reserved.

v


Contents

vi

BC401

© 2004 SAP AG. All rights reserved.

08-03-2004


Course Overview 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. 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. Furthermore, you will become familiar with the tools in the ABAP Workbench that are used for object-oriented programming with ABAP Objects. 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. 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. 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.

vii


Course Overview

BC401

Course Prerequisites Required Knowledge • • •

Programming experience SAPTEC (SAP NetWeaver: Application Platform Fundamentals) BC400 (ABAP Workbench - Concepts & Tools)

Course Duration Details Unit 1: Completing the Procedural Parts of ABAP Objects Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20 Exercise 1: Unicode-Compatible Character String Processing Optimized Working with Internal Tables Exercise 2: Internal Tables with an Unstructured Row Type Exercise 3: Table Kinds Exercise 4: Data Processing and Transfer to Modularization Units (Optional) Unit 2: Introduction to Object-Oriented Programming The Object-Oriented Programming Model Analysis and Design with UML Exercise 5: UML Class Diagrams Fundamental Object-Oriented Syntax Elements Exercise 6: Local Classes Exercise 7: Objects Exercise 8: Method Calls Exercise 9: Constructors Exercise 10: Private Methods

60 Minutes 30 Minutes 190 Minutes 20 Minutes 30 Minutes 30 Minutes 30 Minutes 45 Minutes 15 Minutes 255 Minutes 40 Minutes 20 Minutes 30 Minutes 15 Minutes 30 Minutes

Unit 3: Object-Oriented Concepts and Programming Techniques 225 Minutes Inheritance and Casting 40 Minutes Exercise 11: Class Hierarchies 20 Minutes Exercise 12: Polymorphism 30 Minutes Exercise 13: Aggregation and Generic Calls 135 Minutes Interfaces and Casting 30 Minutes Exercise 14: Interface Implementation Exercise 15: Aggregation, Generic Calls, and 30 Minutes Polymorphism 105 Minutes Events 30 Minutes Exercise 16: Events in Superclasses 30 Minutes Exercise 17: Events in Interfaces (optional) Unit 4: Object-Oriented Repository Objects

viii

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Course Overview

Global Classes and Interfaces Exercise 18: Global Classes Exercise 19: Global Interfaces Exercise 20: Refactoring Assistant Special Object-Oriented Programming Techniques Exercise 21: Singleton Classes (Optional) Exercise 22: Friendship Relationships (optional) Persistent Objects in ABAP Objects for SAP Web Application Server 6.20

150 Minutes 30 Minutes 30 Minutes 15 Minutes 90 Minutes 15 Minutes 45 Minutes 45 Minutes

Unit 5: Exception Handling and Dynamic Programming Exception Handling in ABAP Objects for the SAP 120 Minutes Web Application Server 6.20 45 Minutes Exercise 23: Class-Based Exceptions 30 Minutes Exercise 24: Mapping Exceptions to Each Other Dynamic Programming with ABAP Objects for the 120 Minutes SAP Web Application Server 6.20 Exercise 25: Type Casting with Data Elements 15 Minutes (Optional) 30 Minutes Exercise 26: Creating Data Objects at Runtime

Course Goals This course will prepare you to: • • •

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

Course Objectives After completing this course, you will be able to: • • • • • • •

08-03-2004

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

© 2004 SAP AG. All rights reserved.

ix


Course Overview

BC401

SAP Software Component Information The information in this course pertains to the following SAP Software Components and releases: •

SAP Web AS 6.20

Make sure you read these notes, even if you have already taught a previous version of this course. Also make sure that you have read the list of known errors in this course, if available. If it exists, this list has deliberately been saved separately from this printed course in SAPNet, so as to keep the course as up-to-date as possible while minimizing the necessary technical effort. There you will also find additional material from the various instructors that relates to this course. Training courses recommended as preparation: • • • • • •

SAPTEC BC400 BC401 BC410 BC412 BC425

Apart from SAPTEC and BC412, you should have taught these courses several times. Ideally, you should also be familiar with other object-oriented programming languages like Java or C++. We advise you to proceed as follows when preparing for this course: 1.

2. 3. 4. 5.

x

Familiarize yourself with the topics of the course, including all the articles in the SAP Library. Complete all the exercises yourself at least once, including all details and optional sections, without resorting to the model solution Get answers to any questions you have about the course materials and the exercises Develop your own presentation methods and run through each demonstration at least once yourself Clear up any questions you have on these methods Attend this course at least once when it is held by an experienced instructor, possibly supervising participants during an exercise yourself

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Course Overview

Training system: You need the technology component (that is, system) SAP Web AS 6.20 or later. The training administration team will provide you with this component along with training course clients and other entries. Use this system and these clients only for your training course. Prepare for the following two points according to the “General Instructor Guide for All BC4XX Courses” . It is located in the same area in SAPNet as this handbook. Read the general handbook first. Then use the activity group SAP_TRAINING to make the necessary system preparations as described in the following paragraphs. Data for exercises and demonstrations: The dataset will generally have been generated for your training clients. If not, (for example if your training course takes place at a customer’s site) you will have to run the data generation program. You will be asked about the type and quantity of the data. Choose the standard setting and set the flag for Canceled Bookings Also. User IDs and initial passwords for participants: Unlike the application data, you must always regenerate the user IDs yourself. Use the (locked) user ID BC401_USER as a copy template. Change request for the participants: We recommend simulating a one-week project. That is, create a change request with activities for all user groups. Presentation: Make sure you can open the offline presentation for version 41 of this training course. Example objects: All Repository objects for this course belong to the package BC401. We have used the following naming conventions for this course: • • •

...BC401<CCC>D_...: Demonstration and example objects ...BC401<CCC>S_...: Model solutions ...BC400<CCC>T_...: Copy templates

In each case, <CCC> is a three-character lesson code. Caution: Never modify these standard objects. Always create copies if you want to change something for demonstration purposes. Otherwise, you may cause errors in other objects, or prevent other courses from being held in this system. The same applies for the participants. If, however, you use the copy template for their user IDs, they should not have the authorization to do so.

08-03-2004

© 2004 SAP AG. All rights reserved.

xi


Course Overview

BC401

General notes for the whole course: The times given for the duration of units are recommendations only. You must make sure, however, that you can present the entire course contents. Sections of the course containing key topics for participants must be presented extensively and in detail. These sections generally provide the basis for the exercises. The course materials should be suitable for participants to work through again after the course. This is why we provide extensive explanations and additional information. Your task is to extract the most important statements from the whole. The decisive factor should be the graphics that appear in the offline presentation and the aspects they represent. Similar principles apply to the objects in the package BC401. It contains many more Repository objects than are required for carrying out this course. Much of the code is also available as source code extracts in the presentation or in participants’ material (or both). It is up to you whether you want to discuss these in detail, use the demonstration objects, or create similar objects yourself to use during the presentation. To make SAP training courses effective, they are developed with the assumption that participants really do possess the prerequisite knowledge. Naturally this also applies to this course. However, we consider it important to point this out explicitly once again. Special note about the exclusively object-oriented part of the course: For didactic/methodical reasons, the whole introduction to object-oriented concepts is based on local classes. The Class Builder is introduced in a later step. In practice, global classes are more or less the only classes that are still used. Local classes are only used in exceptional cases. But be sure to point out that the related skills are still valuable because global classes can contain local auxiliary classes. We definitely recommend that you demonstrate the programming successively in the introductory lesson. This results in a good methodical effect in the lesson about interfaces: The demonstration and the exercises – which build up on each other – can then be merged into one application, which can then be extended. Special notes about displaying lists in the demonstration and exercise programs: In most cases, lists are displayed without using SAP Grid Control, although it is the default output tool as of SAP R/3 4.6A. The reasons for this are easy to understand: Displaying the data in a list only serves to simulate the ongoing processing of the data. In other words, it tests that the various program steps are correct. This ensures that the participants only have to concentrate on the important aspects of the material and the instructor can keep the course within a reasonable time frame. Nevertheless, SAP Grid Control is used in select parts of this course.

xii

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Course Overview

For more information on SAP Grid Control, see: • • •

The SAP Library The Object Navigator under Environment → Examples → Control Examples Courses BC400, BC405, and especially BC412

Other notes for instructors In addition to these general notes, you will find other, more detailed notes in each unit and lesson. You will also find other short notes in the material wherever we think it necessary to ensure that the course is held successfully.

Introductory phase at the start of the course: • • • •

Introduce yourself as course instructor Organizational issues Overview of the range of online courses and the complete curriculum surrounding this course Overview of the course content Caution: Although the following aspect is already contained in the course description and elsewhere – including the relevant literature – please repeat it at this point for emphasis. The term “ABAP Objects” is the brand name of SAP’s own programming language. It does not mean that the course only contains the object-oriented aspects of ABAP Objects.

• • •

Participants introduce themselves (optional – only if you have time) Overview of the course material References to more in-depth information

As a test, have the participants log on to the system. You could also have them create their ZBC401_## package at the same time. Alternatively, they can create it before they start the first exercise.

08-03-2004

© 2004 SAP AG. All rights reserved.

xiii


Course Overview

xiv

BC401

© 2004 SAP AG. All rights reserved.

08-03-2004


Unit 1 1

Completing the Procedural Parts of ABAP Objects

This unit asks a lot of the participants right at the beginning of the course: The first lesson is a self-contained learning unit. Its contents should be new to all participants. Still, there are no exercises for that lesson, as all of our previous courses have always only taught those “safe” statements for character string processing that are now Unicode-compatible. Use the exercise to level out the participants varying degrees of previous knowledge regarding the ABAP Workbench and to give them an opportunity to get used to exercise-guided programming. It also contains three preparatory projects that precede the three actual exercises in the second lesson. The second lesson is challenging to present, because the familiar concepts and the “new” ones are completely mixed throughout the different syntax concepts. The participants only learned very basic operations with standard tables in course BC400. In this course, they will get to know all syntactical possibilities. You should conclude the section by looking at the different uses for different table kinds, as this knowledge will be crucial for working successfully with internal tables. It is essential that participants understand this subject, particularly the required runtime resources. Caution: Therefore, focus specifically on the last sections of the second lesson. Although we already addressed the issue in the previous instruction handbook for this course (BC401, version 22), we still receive comments that the first part of this course is purely repetition. Once again, we emphasize that this is not the case. You absolutely must be sure to correct the participants if they express this view. Experience shows that participants react to the second lesson with surprise and enthusiasm if the course is presented effectively – this especially applies for participants who have extensive previous knowledge.

08-03-2004

© 2004 SAP AG. All rights reserved.

1


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Unit Overview 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. The first lesson deals exhaustively with a topic that was completely new in the SAP Web AS 6.10. 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.

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

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 Exercise 3: Table Kinds..................................................... 63 Exercise 4: Data Processing and Transfer to Modularization Units (Optional) ..................................................................... 71

2

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: 2

Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20

Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20 Lesson Duration: 60 Minutes

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

Lesson Objectives After completing this lesson, 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

In our opinion, the last section contains by far the most important statements in this entire unit. You should point this out over and over again during the lecture itself. It is important that the participants are aware that in the ideal situation, in case of a Unicode conversion, their programs should not need to be adapted whatsoever.

Business Example You need to develop a Unicode-enabled ABAP Objects program in the SAP Web AS 6.20.

System-Internal Representation of Characters Under Unicode 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. 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

3


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

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.

Figure 1: Unicode Character Set Table

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

4

© 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

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). 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. 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. The standard class CL_ABAP_CHAR_UTILITIES contains numerous characters, also CHARSIZE, that - at runtime - contain the length of a character, measured in bytes. 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.

Character and Byte Processing 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. 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


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

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.

Figure 2: Character String and Byte Sequence Processing

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

Functions and Compare Operators 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. 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. 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.

6

© 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

Figure 3: Lengths and Compares

Conversion Rules for Structures 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. 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. 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 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

7


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Figure 4: Conversion Between Flat Structures

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

8

© 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

Figure 5: Conversion Between Structures and Elementary Data Objects

Hint: Internal tables can be converted if row types can be converted. 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.

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

9


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Figure 6: Access Using Offset and Length Specification for Elementary Data Objects

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.

Figure 7: Access Using Offset and Length Specification for Structures

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.

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

General Recommendations: 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: • •

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.

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

11


Unit 1: Completing the Procedural Parts of ABAP Objects

12

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

11

Lesson: Unicode-Compatible String Processing in ABAP Objects for SAP Web Application Server 6.20

Exercise 1: Unicode-Compatible Character String Processing Exercise Duration: 30 Minutes

Exercise Objectives 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

Business Example Assume that a data record of a specific flight is stored as an unstructured character string in the memory. 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. 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. For now, we will focus on a formatted list output.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

08-03-2004

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

© 2004 SAP AG. All rights reserved.

13


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Task 1: Copy the template. 1.

Copy template: SAPBC401_DTOT_SPLIT_STRING Program name: ZBC401_##_SPLIT_STRING (Where ## is your two-digit group number).

2.

Activate your copy (or copies).

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. Hint: Think of the function module itself as a “black box”. A deeper understanding of how it works is not part of this exercise.

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

2.

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. Continued on next page

14

© 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

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

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 Program name: ZBC401_##_SPLIT_STRING (Where ## is your two-digit group number). a)

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.

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. Hint: Think of the function module itself as a “black box”. A deeper understanding of how it works is not part of this exercise.

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

Continued on next page

16

© 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

For this, SET_STRING has to be defined appropriately. Hint: Use the statements FIND and SPLIT. a) 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. 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. a)

See the source code extract from the model solution

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

2.

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

Result Source code extract:

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

17


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

SAPBC401_DTOS_SPLIT_STRING REPORT

sapbc401_dtos_split_string.

TYPES: BEGIN OF st_flight_c, mandt(3)

TYPE c,

carrid(3)

TYPE c,

connid(4)

TYPE n,

fldate(8)

TYPE n,

price(20)

TYPE c,

currency(5)

TYPE c,

planetype(10)

TYPE c,

seatsmax(10)

TYPE n,

seatsocc(10)

TYPE n,

paymentsum(22) TYPE c, seatsmax_b(10) TYPE n, seatsocc_b(10) TYPE n, seatsmax_f(10) TYPE n, seatsocc_f(10) TYPE n, END OF st_flight_c,

BEGIN OF st_flight, carrid(3)

TYPE c,

connid(4)

TYPE n,

fldate

TYPE d,

price(9)

TYPE p DECIMALS 2,

currency(5)

TYPE c,

planetype(10) TYPE c, seatsmax

TYPE i,

seatsocc

TYPE i,

END OF st_flight. DATA: datastring

TYPE string,

set_string

TYPE string,

wa_flight_c TYPE st_flight_c, wa_flight

TYPE st_flight.

START-OF-SELECTION.

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

CALL FUNCTION ’BC401_GET_SEP_STRING’ * EXPORTING *

IM_NUMBER

= ’1’

*

IM_TABLE_NAME

= ’SFLIGHT’

*

IM_SEPARATOR

= ’#’

*

IM_UNIQUE

= ’X’

IMPORTING ex_string

= datastring

EXCEPTIONS no_data

= 1

OTHERS

= 2.

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

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

SPLIT set_string AT ’#’ INTO wa_flight_c-mandt wa_flight_c-carrid wa_flight_c-connid wa_flight_c-fldate wa_flight_c-price wa_flight_c-currency wa_flight_c-planetype wa_flight_c-seatsmax wa_flight_c-seatsocc wa_flight_c-paymentsum wa_flight_c-seatsmax_b wa_flight_c-seatsocc_b wa_flight_c-seatsmax_f wa_flight_c-seatsocc_f.

MOVE-CORRESPONDING wa_flight_c TO wa_flight.

WRITE: /

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

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

Related Information ... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.

08-03-2004

© 2004 SAP AG. All rights reserved.

21


Unit 1: Completing the Procedural Parts of ABAP Objects

Lesson: 20

BC401

Optimized Working with Internal Tables Lesson Duration: 190 Minutes

Lesson Overview 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. Therefore, this lesson goes far beyond the material that you may have covered in other courses about internal tables.

Lesson Objectives After completing this lesson, you will be able to: • • •

Define internal tables Perform operations on internal tables Identify table kinds and use them appropriately in different situations

Approach this lesson flexibly because it contains so much information. It is designed to encompass all information about internal tables so that participants could theoretically learn about internal tables without having any prior experience of working with them. If that is the case, you should focus on the first three sections. Generally, however, participants have some prior knowledge of the subject. Experience shows that the participants’ experience is based on standard tables with header lines. Surprisingly, this is still the case even though the use of header lines has been discouraged since SAP R/3 4.0. Therefore, it is important to emphasize that the first three sections should be understood as a “reference” for virtually all syntactical possibilities. It is not necessary to memorize each individual statement pattern. The information is effectively the same as what is contained in the SAP Library and the ABAP keyword documentation. Highlighting the aspects that are new to the majority of the participants is much more important. This particularly applies to the use of field symbols and references as well as looking at runtime requirements.

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

22

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Internal Tables as Dynamic Data Objects 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. 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. Parts of this graphic refer to aspects that are treated later on in this lesson. Focus on the new terms and syntactical possibilities rather than possible uses.

Figure 8: Attributes of Internal Tables

The data type of an internal table is fully specified by its: Row type The row type defines the attributes of the individual columns. You normally enter a structure type, but any data type is possible. 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

23


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Access type •

Key access – like database tables – works via field contents. 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.

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. 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. Hashed tables The runtime-optimized data records are maintained here. This requires a unique key. Hashed tables only allow for key access.

Figure 9: Link Between Table Kind and Access Type

24

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

On a case-by-case basis, the table kind is decided by which access types will primarily be used with the table entries. • • •

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

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. Depending on the participants’ interest or existing knowledge, you could give a short demonstration of creating a global table kind before taking a detailed look at the syntactical possibilities for local types.

08-03-2004

© 2004 SAP AG. All rights reserved.

25


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Figure 10: Definition of Tables or Table Kinds In a Local Program

There are three syntax additions that you use to specify a table kind for your internal table: STANDARD TABLE, SORTED TABLE and HASHED TABLE. 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 . •

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. If necessary, analyze the program SAPBC401_TABD_SINGLE_COLUMN in detail and run it.

26

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

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: For standard tables Only non-unique For sorted tables Unique or non-unique For hashed tables Only unique There is a standard type for internal tables. You can use a shorter syntax to define it.

Shorter Syntax for the Definition of Standard Tables with a Bound Type DATA itab_name TYPE TABLE OF line_type.

Interpretation of the Short Syntax by the Runtime System DATA itab_name TYPE [STANDARD] TABLE OF line_type [WITH NON-UNIQUE DEFAULT KEY].

08-03-2004

© 2004 SAP AG. All rights reserved.

27


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Figure 11: Standard Table With a Local, Explicitly Defined Type – Example

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. 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. In the course of this example, you could demonstrate the use of the DEFAULT KEY addition. You could also show the new syntax variant in SAP R/3 4.0 and compare it to the obsolete variant.

28

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Figure 12: Sorted and Hashed Table – Examples

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.

Caution: These are only examples of syntax for examining the technical concepts! You do not need to discuss possible areas of use yet. 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. Memory Allocation and Initial Size

08-03-2004

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.

29


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

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

The actual sizes are determined by certain rules. Explaining these rules would exceed the intended scope of this course. They have been changed often and are of no consequence to application developers. The important thing to understand is that as of SAP Web AS 6.20, an empty internal table requires virtually no memory and the INITIAL SIZE addition is useful for nested tables.

Figure 13: Generic Table Kinds

Incomplete table kinds are known as generic. You can only use them to assign types to table-type interface parameters. This may be a good time to carry out the exercise for defining and using a single-column internal table. The participants should be able to program a LOOP based on their previous knowledge, even though this is not covered until the following section. If not, you will need to hold the exercise as part of the next section.

30

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Internal Table Operations 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. 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.

Figure 14: Inserting With Key Access

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. standard table The data record is appended to the internal table, just as with the APPEND statement. 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. hashed table The data record is appended, but an entry is made in the hash index. 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. When index tables are inserted successfully, the system field SY-TABIX is set to the insert position. 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

08-03-2004

© 2004 SAP AG. All rights reserved.

31


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

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. If necessary, analyze the program SAPBC401_TABD_COLLECT in detail and run it.

Figure 15: Appending and Inserting with Index Access

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. Within a loop, the INSERT statement adds the data record before the current record in the table. 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. 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.

32

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

This statement is an easy way to make a ranked list: APPEND wa INTO rank_itab SORTED BY f. 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.

Figure 16: Changing and Deleting With Key Access

If you use these key accesses with the variants FROM wa, the key fields in the work area must be filled. 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

33


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

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: DELETE ADJACENT DUPLICATES FROM itab [ COMPARING {f_1 .. f_n} | ALL FIELDS } ] . 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. The best way to delete the entire internal table is to use any of the following three statements: 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. 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. 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.

34

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Figure 17: Changing and Deleting with Index Access

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. Within a loop, MODIFY changes the current data record. 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.

Figure 18: Sorting Standard and Hashed Tables

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

08-03-2004

© 2004 SAP AG. All rights reserved.

35


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

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. Emphasize the last two additions that were mentioned. They are often very important for the participants.

Figure 19: Reading with Key Access

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. 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. Hint: You can force the system to use a binary search with a standard table using the BINARY SEARCH addition. 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. If there are duplicate records that match your search criteria, the first data record that is found is displayed. 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.

36

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

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. In the TRANSPORTING addition, you can restrict the data transport to selected fields. 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. Alternatively, you can use field symbols or references to access data. To do so, use ASSIGNING <fs_line> or REFERENCE INTO ref_line. This will be discussed in more detail later.

Figure 20: Reading a Single Record with Index Access

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

Figure 21: Loop Processing with Key Access

08-03-2004

© 2004 SAP AG. All rights reserved.

37


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

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. 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. 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. 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. Alternatively, you can use field symbols or references to access data. To do so, use ASSIGNING <fs_line> or REFERENCE INTO ref_line. This will be discussed in more detail later. 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.

Figure 22: Loop Processing with Index Access

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.

38

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Once again, the additions and return value function as described above.

Figure 23: Internal Tables With or Without Header Line – Comparison

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. 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. However, internal tables with a header line do offer shorter syntax in several statements (APPEND, INSERT, MODIFY, COLLECT, DELETE, READ, LOOP AT). 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.

Example for Using an Internal Table with a Header Line DATA itab1 TYPE TABLE OF i WITH HEADER LINE.

08-03-2004

© 2004 SAP AG. All rights reserved.

39


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

DATA itab2 LIKE itab1.

itab1

= itab2.

" <- just the header line contents!

itab1[] = itab2[]. " <- just the table contents

Figure 24: Overview of Fundamental Operations

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

40

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

This may be a good time to carry out the exercise for defining and using sorted tables with unique keys. If some participants finish early, they can start working on the last (optional) exercise. It does not expand upon the following contents, but was included at the end of the lesson for methodical reasons.

Using Field Symbols and References with Internal Tables The pointer concept in ABAP Objects has evolved throughout several release cycles. Now, we form a distinction between field symbols, references, and dereferenced references. 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. 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. 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. Following are a number of interesting variants for using the aforementioned access possibilities in conjunction with internal tables.

08-03-2004

© 2004 SAP AG. All rights reserved.

41


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Figure 25: Using Field Symbols and References for Row Access

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. Even after they have been sorted, field symbols and references still point to the assigned row. 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.

42

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Figure 26: References When Reading and Loop Processing

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 <field_symbol> . The field symbol <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. However, there are also certain restrictions when you use this referencing technique: • •

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 <fs_line> and UNASSIGN <fs_line> 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

43


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

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.

Figure 27: References to Inserted or Changed Single Rows

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 <field_symbol> or REFERENCE INTO ref_name.

44

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Figure 28: Referencing vs. Copying a Reference – Comparison

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. 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. 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. Even if the participants feel that referencing references is unrealistic, you must discuss in detail the table pattern and the copying of references. This is a very common use of single-column internal tables.

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

45


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Figure 29: Data Management for Hashed Tables

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

46

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Figure 30: Completely Qualified Key vs. Partially Qualified Key with Single-Record Access

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. 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. If the table is a standard table, the runtime system performs a sequential search. 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 = (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.

08-03-2004

© 2004 SAP AG. All rights reserved.

47


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

If necessary, analyze the program SAPBC401_TABD_COMPARE_READ_KEY in detail and run it.

Hint: For standard tables, you can use the optional addition BINARY SEARCH to make the system do a binary search. 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.

Figure 31: Mass Processing and Table Kinds

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.

48

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Figure 32: Access to Nested Tables Using Field Symbols

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. 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. The same applies to LOOP ... INTO compared with LOOP ... ASSIGNING or LOOP ... REFERENCE INTO. 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. If necessary, analyze the programs SAPBC401_TABD_COMPARE_READ, SAPBC401_TABD_COMPARE_LOOP, and/or SAPBC401_TABD_TABLE_PROPS in detail and run them.

08-03-2004

© 2004 SAP AG. All rights reserved.

49


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Figure 33: Partial Sequential Loop Through Standard Tables

To recap: If you program a loop through a standard table to match a specific field criterion, the runtime system always executes a table scan. You can use the 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. Since you are usually not yet interested in the data record itself, you may wish to use the addition TRANSPORTING NO FIELDS.

3.

Program an index-controlled loop, starting with the row number that you just determined. Within the loop, terminate the loop if it leaves the desired control level. Caution: If you combine the starting row number and the original search criterion (FROM startline WHERE cityfrom = ’FRANKFURT’) the rest of the internal table after the starting row will also be processed!

50

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

An alternative to the termination criterion could be: READ TABLE ... INTO ... WITH KEY cityfrom = ’NEW YORK’ TRANSPORTING NO FIELDS BINARY SEARCH. endline = sy-tabix - 1.

Then the loop could be completely index-controlled: LOOP AT ... INTO ... FROM startline TO endline. ... 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.

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. 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. If necessary, analyze the program SAPBC401_TABD_STANDARD in detail and run it.

08-03-2004

© 2004 SAP AG. All rights reserved.

51


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

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. If necessary, analyze the program SAPBC401_TABD_SORTED in detail and run it.

52

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

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.) If necessary, analyze the program SAPBC401_TABD_HASHED in detail and run it.

Finally, we will look at a fully programmed syntax example that demonstrates the use of nested internal tables and access through a field symbol. In this example, the user should be able to enter a departure city, for which all possible flights and connecting flights are then listed.

08-03-2004

© 2004 SAP AG. All rights reserved.

53


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Figure 34: Definition of Nested Tables in the Application Example

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

54

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Figure 35: Loop Processing with Field Symbols for Inserting New Data

We also need to define three field symbols with the row types of the internal tables. First, the flight connections starting in the city entered in PA_START are assigned to the field symbol <FS_CONN>. 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.

Figure 36: Loop Processing with Field Symbols for Output

08-03-2004

© 2004 SAP AG. All rights reserved.

55


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

The output is generated by a nested loop through the outer and internal tables. Using this control level processing, only the new arrival cities are written into the list. If necessary, analyze the program SAPBC401_TABD_NESTED in detail and run it.

At this point, you may want to fill out this lesson with the exercise for further data processing with internal tables. It was included at the end of this lesson for purely methodical reasons and focuses on loop processing, transfer to a modularization unit, and the associated external restrictions that affect the choice of the data type.

56

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

53

Lesson: Optimized Working with Internal Tables

Exercise 2: Internal Tables with an Unstructured Row Type Exercise Duration: 20 Minutes

Exercise Objectives 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

Business Example The character string that was used in this lesson’s previous exercise now needs to contain more than one data record. 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.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Copy the template. Make sure that there is more than one data record in the character string. 1.

Copy template: SAPBC401_DTOS_SPLIT_STRING or ZBC401_##_SPLIT_STRING Program name: ZBC401_##_SPLIT_ITAB (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.

57


Unit 1: Completing the Procedural Parts of ABAP Objects

3.

BC401

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.

Task 2: Use an internal table to separate the data records and extend the list output.

58

1.

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.

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

Copy template: SAPBC401_DTOS_SPLIT_STRING or ZBC401_##_SPLIT_STRING Program name: ZBC401_##_SPLIT_ITAB (Where ## is your two-digit group number). a)

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_TABS_SPLIT_ITAB

2.

Activate your copy (or copies). Familiarize yourself with the program and its existing functions. a)

3.

Carry out this step in the usual manner. Additional information is available in the SAP Library.

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

See the source code extract from the model solution

Task 2: Use an internal table to separate the data records and extend the list output. 1.

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.

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)

3.

See the source code extract from the model solution

See the source code extract from the model solution

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. Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

59


Unit 1: Completing the Procedural Parts of ABAP Objects

a)

BC401

See the source code extract from the model solution

Result Source code extract:

SAPBC401_TABS_SPLIT_ITAB REPORT

sapbc401_tabs_split_itab.

TYPES: BEGIN OF st_flight_c, mandt(3)

TYPE c,

carrid(3)

TYPE c,

connid(4)

TYPE n,

fldate(8)

TYPE n,

price(20)

TYPE c,

currency(5)

TYPE c,

planetype(10)

TYPE c,

seatsmax(10)

TYPE n,

seatsocc(10)

TYPE n,

paymentsum(22) TYPE c, seatsmax_b(10) TYPE n, seatsocc_b(10) TYPE n, seatsmax_f(10) TYPE n, seatsocc_f(10) TYPE n, END OF st_flight_c, BEGIN OF st_flight, carrid(3)

TYPE c,

connid(4)

TYPE n,

fldate

TYPE d,

price(9)

TYPE p DECIMALS 2,

currency(5)

TYPE c,

planetype(10) TYPE c, seatsmax

TYPE i,

seatsocc

TYPE i,

END OF st_flight. CONSTANTS c_number TYPE i VALUE 30.

DATA: datastring

TYPE string,

set_string

TYPE string,

Continued on next page

60

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

wa_flight_c TYPE st_flight_c, wa_flight

TYPE st_flight.

DATA: it_sets TYPE STANDARD TABLE OF string WITH NON-UNIQUE DEFAULT KEY INITIAL SIZE c_number.

START-OF-SELECTION.

CALL FUNCTION ’BC401_GET_SEP_STRING’ EXPORTING im_number

= c_number

*

IM_TABLE_NAME

= ’SFLIGHT’

*

IM_SEPARATOR

= ’#’

IM_UNIQUE

= ’X’

*

IMPORTING ex_string

= datastring

EXCEPTIONS no_data

= 1

OTHERS

= 2.

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

SHIFT datastring BY 2 PLACES IN CHARACTER MODE. FIND ’##’ IN datastring. IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF. SPLIT datastring AT ’##’ INTO TABLE it_sets.

LOOP AT it_sets INTO set_string.

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

08-03-2004

© 2004 SAP AG. All rights reserved.

61


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

wa_flight_c-price wa_flight_c-currency wa_flight_c-planetype wa_flight_c-seatsmax wa_flight_c-seatsocc wa_flight_c-paymentsum. MOVE-CORRESPONDING wa_flight_c TO wa_flight. WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate DD/MM/YYYY, wa_flight-price CURRENCY wa_flight-currency, wa_flight-currency, wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc. ENDLOOP.

62

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

59

Lesson: Optimized Working with Internal Tables

Exercise 3: Table Kinds Exercise Duration: 30 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Select the appropriate kinds of internal table • Process data using internal tables

Business Example The character string that was used in this lesson’s previous exercise will now contain duplicate data records. 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.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Copy the template. Make sure there are non-unique data records in the character string. 1.

Copy template: SAPBC401_TABS_SPLIT_ITAB or ZBC401_##_SPLIT_ITAB Program name: ZBC401_##_TABKIND (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.

63


Unit 1: Completing the Procedural Parts of ABAP Objects

3.

BC401

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.

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

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

64

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.

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

Copy template: SAPBC401_TABS_SPLIT_ITAB or ZBC401_##_SPLIT_ITAB Program name: ZBC401_##_TABKIND (Where ## is your two-digit group number). a)

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_TABS_TABKIND

2.

Activate your copy (or copies). Familiarize yourself with the program and its existing functions. a)

3.

Carry out this step in the usual manner. Additional information is available in the SAP Library.

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

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.

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)

See the source code extract from the model solution

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

65


Unit 1: Completing the Procedural Parts of ABAP Objects

2.

BC401

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

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

4.

See the source code extract from the model solution

See the source code extract from the model solution

Display the contents of both internal tables in the list. a)

See the source code extract from the model solution

Result Source code extract:

SAPBC401_TABS_TABKIND REPORT

sapbc401_tabs_tabkind.

TYPES: BEGIN OF st_flight_c, mandt(3)

TYPE c,

carrid(3)

TYPE c,

connid(4)

TYPE n,

fldate(8)

TYPE n,

price(20)

TYPE c,

currency(5)

TYPE c,

planetype(10)

TYPE c,

seatsmax(10)

TYPE n,

seatsocc(10)

TYPE n,

paymentsum(22) TYPE c, seatsmax_b(10) TYPE n, seatsocc_b(10) TYPE n, seatsmax_f(10) TYPE n, seatsocc_f(10) TYPE n, END OF st_flight_c,

Continued on next page

66

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

BEGIN OF st_flight, carrid(3)

TYPE c,

connid(4)

TYPE n,

fldate

TYPE d,

price(9)

TYPE p DECIMALS 2,

currency(5)

TYPE c,

planetype(10) TYPE c, seatsmax

TYPE i,

seatsocc

TYPE i,

END OF st_flight. CONSTANTS c_number TYPE i VALUE 30.

DATA: datastring

TYPE string,

set_string

TYPE string,

wa_flight_c TYPE st_flight_c, wa_flight

TYPE st_flight.

DATA: it_sets TYPE STANDARD TABLE OF string WITH NON-UNIQUE DEFAULT KEY INITIAL SIZE c_number,

it_flights TYPE SORTED TABLE OF st_flight WITH UNIQUE KEY carrid connid fldate INITIAL SIZE c_number,

it_doubles TYPE SORTED TABLE OF st_flight WITH NON-UNIQUE KEY carrid connid fldate INITIAL SIZE c_number.

START-OF-SELECTION. CALL FUNCTION ’BC401_GET_SEP_STRING’ EXPORTING im_number

= c_number

*

IM_TABLE_NAME

= ’SFLIGHT’

*

IM_SEPARATOR

= ’#’

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

67


Unit 1: Completing the Procedural Parts of ABAP Objects

im_unique

BC401

= space

IMPORTING ex_string

= datastring

EXCEPTIONS no_data

= 1

OTHERS

= 2.

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

SHIFT datastring BY 2 PLACES IN CHARACTER MODE. FIND ’##’ IN datastring. IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF. SPLIT datastring AT ’##’ INTO TABLE it_sets.

LOOP AT it_sets INTO set_string.

SPLIT set_string AT ’#’ INTO wa_flight_c-mandt wa_flight_c-carrid wa_flight_c-connid wa_flight_c-fldate wa_flight_c-price wa_flight_c-currency wa_flight_c-planetype wa_flight_c-seatsmax wa_flight_c-seatsocc wa_flight_c-paymentsum.

MOVE-CORRESPONDING wa_flight_c TO wa_flight. INSERT wa_flight INTO TABLE it_flights. IF sy-subrc <> 0. INSERT wa_flight INTO TABLE it_doubles. ENDIF.

ENDLOOP.

* output:

Continued on next page

68

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

*********

LOOP AT it_flights INTO wa_flight. WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate DD/MM/YYYY, wa_flight-price CURRENCY wa_flight-currency, wa_flight-currency, wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc. ENDLOOP.

SKIP. WRITE: / ’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, wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc. ENDLOOP.

08-03-2004

© 2004 SAP AG. All rights reserved.

69


Unit 1: Completing the Procedural Parts of ABAP Objects

70

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

67

Lesson: Optimized Working with Internal Tables

Exercise 4: Data Processing and Transfer to Modularization Units (Optional) Exercise Duration: 30 Minutes

Exercise Objectives 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

Business Example 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. If desired, the data is to be displayed using SAP Grid Control. Once again, we are faced with the problem of having to concentrate on the core contents of the course and setting strict limits for the subject matter. Ideally, the participants would have the chance to use SAP Grid Control themselves, especially since a suitable lesson is already included in BC400. As of SAP R/3 4.6A at the latest, individual lists should always be created using SAP Grid Control. However, this would probably cause problems with the color coding of the grid lines. Therefore, one of the main reasons we developed the function module was to restrict this exercise to an appropriate time frame while still showing the participants how they should ideally be working. This resulted in another useful exercise scenario: As developers, the participants should use reusable components whenever possible. This will often require preparatory data formatting. This can be practiced at this point.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

08-03-2004

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

© 2004 SAP AG. All rights reserved.

71


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

Task 1: Copy the template. 1.

Copy template: SAPBC401_TABS_TABKIND or ZBC401_##_TABKIND Program name: ZBC401_##_PROCESS_DATA (Where ## is your two-digit group number).

2.

Activate your copy (or copies). Familiarize yourself with the program and its existing functions.

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

3.

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. 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. You can reverse any color set using the FORMAT RESET statement.

Continued on next page

72

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

Task 3: If desired, display the data using SAP Grid Control. 1.

Define a selection screen check box for displaying the data with the standard tool, SAP Grid Control (suggested name: PA_ALV). Hint: Use the addition AS CHECKBOX. Ensure that the data is only displayed in the usual ABAP list if the user does not check the SAP Grid Control box.

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

08-03-2004

3.

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.

© 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 Program name: ZBC401_##_PROCESS_DATA (Where ## is your two-digit group number). a)

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

Carry out this step in the usual manner. Additional information is available in the SAP Library.

Task 2: 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. a)

2.

See the source code extract from the model solution

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. Display flights that occurred between today’s date and the key date with the background color COL_TOTAL. Continued on next page

74

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

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. You can reverse any color set using the FORMAT RESET statement. a)

See the source code extract from the model solution

Task 3: If desired, display the data using SAP Grid Control. 1.

Define a selection screen check box for displaying the data with the standard tool, SAP Grid Control (suggested name: PA_ALV). Hint: Use the addition AS CHECKBOX. Ensure that the data is only displayed in the usual ABAP list if the user does not check the SAP Grid Control box. a)

2.

See the source code extract from the model solution

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

See the source code extract from the model solution

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

75


Unit 1: Completing the Procedural Parts of ABAP Objects

3.

BC401

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

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

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:

SAPBC401_TABS_PROCESS_DATA REPORT sapbc401_tabs_process_data.

TYPE-POOLS col.

... DATA: ... it_flights TYPE SORTED TABLE OF st_flight WITH UNIQUE KEY fldate carrid connid INITIAL SIZE c_number,

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

Continued on next page

76

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

... PARAMETERS: pa_date LIKE sy-datum, pa_alv

AS CHECKBOX DEFAULT ’X’.

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

AT SELECTION-SCREEN. IF pa_date < sy-datum. MESSAGE e085(bc401).

" date in the past

ENDIF.

START-OF-SELECTION. ... * output: ********* IF pa_alv = ’X’.

LOOP AT it_flights INTO wa_flight. MOVE-CORRESPONDING wa_flight TO wa_col_flight. IF wa_col_flight-fldate < sy-datum. wa_col_flight-color = col_negative. ELSEIF wa_col_flight-fldate < pa_date. wa_col_flight-color = col_total. ELSE. wa_col_flight-color = col_positive. ENDIF. INSERT wa_col_flight INTO TABLE it_col_flights. ENDLOOP.

LOOP AT it_doubles INTO wa_flight. MOVE-CORRESPONDING wa_flight TO wa_col_flight. wa_col_flight-color = col_background. INSERT wa_col_flight INTO TABLE it_col_doubles. ENDLOOP.

CALL FUNCTION ’BC401_ALV_LIST_OUTPUT’ EXPORTING it_list1

= it_col_flights

it_list2

= it_col_doubles

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

77


Unit 1: Completing the Procedural Parts of ABAP Objects

BC401

EXCEPTIONS control_error = 1 OTHERS

= 2.

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

ELSE. LOOP AT it_flights INTO wa_flight. IF wa_flight-fldate < sy-datum. FORMAT COLOR = col_negative. ELSEIF wa_flight-fldate < pa_date. FORMAT COLOR = col_total. ELSE. FORMAT COLOR = col_positive. ENDIF.

WRITE: / wa_flight-carrid, wa_flight-connid, wa_flight-fldate DD/MM/YYYY, wa_flight-price CURRENCY wa_flight-currency, wa_flight-currency, wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc. ENDLOOP. FORMAT RESET.

SKIP. WRITE: / ’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, wa_flight-planetype, wa_flight-seatsmax, wa_flight-seatsocc. ENDLOOP. ENDIF.

78

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Optimized Working with Internal Tables

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

Related Information ... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.

08-03-2004

© 2004 SAP AG. All rights reserved.

79


Unit Summary

BC401

Unit 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 • Define internal tables • Perform operations on internal tables • Identify table kinds and use them appropriately in different situations

80

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

77

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? Choose the correct answer(s).

□ □ □ □ □ □ □ 3.

A B C D E F G

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

□ □ □ □ □ □ □ 4.

A B C D E F G

D C X T N STRING XSTRING

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.

□ □

08-03-2004

True False

© 2004 SAP AG. All rights reserved.

81


Test Your Knowledge

5.

BC401

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.

□ □ 6.

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

□ □ □ □ □ □

8.

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.

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.

□ □ 9.

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

□ □

82

True False

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

10. Which of the following statements are correct? Choose the correct answer(s).

□ □

A B

□ □

C D

□ □

E F

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.

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.

□ □

True False

12. Which of the following statements are correct? Choose the correct answer(s).

08-03-2004

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.

© 2004 SAP AG. All rights reserved.

83


Test Your Knowledge

80

BC401

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. Refer to the relevant section of the lesson.

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? Answer: A, B, D, E, F Refer to the relevant section of the lesson.

3.

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.

4.

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

84

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

6.

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? Answer: B, D Refer to the relevant section of the lesson.

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. Answer: True Refer to the relevant section of the lesson.

9.

One way that generic table types enable dynamic programming is by not determining the table kind of a globally defined internal table until runtime. Answer: False Refer to the relevant section of the lesson.

10. Which of the following statements are correct? 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. 12. Which of the following statements are correct? Answer: A, B, C, E Refer to the relevant section of the lesson.

08-03-2004

© 2004 SAP AG. All rights reserved.

85


Unit 1: Completing the Procedural Parts of ABAP Objects

86

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


Unit 2 83

Introduction to Object-Oriented Programming

Surprisingly, we have noticed that many participants are not yet used to the object-oriented way of thinking. Their thoughts often still follow procedural patterns. However, the last few years have shown that participants are increasingly willing to deal with object-orientation and need less prompting. Most participants have accepted that they now have to confront the issue. The first lesson will probably not be enough to convert them completely and they may still need some motivational help. Ideally, each participant will have learned by experience by the end of the course and will be fully convinced by the advantages of object-oriented programming. The second lesson is only intended as a brief introduction to modeling. We are convinced that modeling alone – without the background knowledge to determine what is or is not possible in a programming context – is not sufficient for effective learning. We say: Learn by doing! That way, participants create executable programs and can see the effects of what they are doing right away. This course therefore takes a more introductory approach to modeling. After a brief introduction, other aspects of UML notation will be examined in relation to the different object-oriented concepts. This is the only way for participants to learn both object-oriented programming with ABAP Objects and basic modeling at the same time.

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

08-03-2004

© 2004 SAP AG. All rights reserved.

87


Unit 2: Introduction to Object-Oriented Programming

BC401

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

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

Unit Contents Lesson: The Object-Oriented Programming Model ......................... 89 Lesson: Analysis and Design with UML .....................................104 Exercise 5: UML Class Diagrams ........................................ 115 Lesson: Fundamental Object-Oriented Syntax Elements ................. 118 Exercise 6: Local Classes .................................................145 Exercise 7: Objects ........................................................151 Exercise 8: Method Calls ..................................................155 Exercise 9: Constructors ..................................................161 Exercise 10: Private Methods.............................................167

88

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: 85

Lesson: The Object-Oriented Programming Model

The Object-Oriented Programming Model Lesson Duration: 30 Minutes

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

Lesson Objectives After completing this lesson, you will be able to: • •

Explain the differences between procedural and object-oriented programming models List the advantages of the object-oriented programming model

Finding the best way to handle this lesson depends on the individual group of participants. Experience shows that participants often have some previous knowledge of procedural programming, particularly the contents of the previous course BC400. Sometimes, for no apparent reason, these participants hesitate to use object-orientation. Try to overcome this hesitation. Therefore, it would be counterproductive to put too much emphasis on the last section. The properties that are described there need to be dealt with gradually in the specific lessons. The final section is more suitable for participants with object-oriented experience in other programming languages. You can assure these participants that they will soon be seeing some familiar concepts. It is important to clarify that the object-oriented programming model does not extend the range of problems that can be solved algorithmically. Object orientation is just another programming approach. It can solve exactly the same number of problems as other approaches.

08-03-2004

© 2004 SAP AG. All rights reserved.

89


Unit 2: Introduction to Object-Oriented Programming

BC401

Business Example You need to explain the basics of the object-oriented programming model and its advantages to your development project manager.

Moving from the Procedural to the Object-Oriented Programming Model 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.

Figure 37: History of Selected Programming Languages

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.

90

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: The Object-Oriented Programming Model

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. Refer to these statements whenever they are relevant throughout the entire course and illustrate them with specific syntax examples. Make sure that they are not seen as empty phrases.

Figure 38: Characteristics of the Procedural 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

91


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 39: Typical Procedural ABAP Program

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.

Figure 40: Encapsulating Data Using Function Groups

92

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: The Object-Oriented Programming Model

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. 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. 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. 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. It may be helpful to mention some other characteristics of function modules, such as remote-enablement or the possibility of parallelization. This risks being drawn away from the core subject matter, but it can emphasize how powerful and versatile even the procedural part of ABAP Objects is. It can also help participants to understand that object-orientation is just another programming method and does not necessarily lead to more technical possibilities.

08-03-2004

© 2004 SAP AG. All rights reserved.

93


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 41: Example of a Function Group

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.

Figure 42: Example of Using a Function Group

The main program cannot access the function group’s data object SPEED directly.

94

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: The Object-Oriented Programming Model

We feel that the best way to learn about the new aspects is to highlight the differences from the old characteristics. Multiple instantiation is a new characteristic that could be suitable for this purpose. Some other object-oriented concepts also exist in procedural languages or they are easy to imagine. However, this is not the case for inheritance. It is more difficult, and therefore less suitable for defining the limits of the object-oriented approach.

Figure 43: Several Instances of One Function Group?

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.

Figure 44: Multiple Instantiation in Object-Oriented Programming

08-03-2004

© 2004 SAP AG. All rights reserved.

95


Unit 2: Introduction to Object-Oriented Programming

BC401

The possibility of creating several runtime instances in a capsule for each program context is one of the key characteristics of object-oriented programming. 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.

Figure 45: ABAP Main Memory and Encapsulation

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.

96

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: The Object-Oriented Programming Model

Figure 46: Data Management in the Procedural and Object-Oriented Models – Summary

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.

The Object-Oriented Programming Model of ABAP Objects 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. 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

97


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 47: ABAP Objects as a Compatible Extension of ABAP

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. Type checks in the object-oriented contexts of ABAP Objects are stricter than those in the procedural contexts. 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. 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. 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. It may be useful to mention the great advantages of SAP’s approach: The upward compatibility saves developers from having to carry out a migration when a new release is implemented. With a small number of exceptions, the Repository objects from the first SAP R/3 Basis release can still be used freely in SAP Web AS 6.20. No competitor can match that.

98

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: The Object-Oriented Programming Model

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. To be able to separate requests and deliveries of services, the following must be true: • •

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

08-03-2004

© 2004 SAP AG. All rights reserved.

99


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 49: Additional Concepts of the Object-Oriented Programming Model

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. polymorphism In object-orientation, polymorphism is when instances of different classes respond differently to the same messages. 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. To summarize, the object-oriented programming model of ABAP Objects is characterized by the following: Characteristics of the Object-Oriented Programming Model • • •

100

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.

08-03-2004


BC401

Lesson: The Object-Oriented Programming Model

Advantages of the Object-Oriented Programming Model over the Procedural Programming Model •

Improved software structure and consistency in the development process 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.

• • •

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

The features will only become apparent to the participants after they have completed the relevant lessons. Make sure they understand that the claims made in this course will be verified by their own experience. In object-oriented programming, analysis and design decisions have an even greater effect on the implementation than they do in procedural programming.

Figure 50: The Software Development Process

Therefore, you should already structure and formally standardize the analysis and design phase. This is done using modeling languages.

08-03-2004

© 2004 SAP AG. All rights reserved.

101


Unit 2: Introduction to Object-Oriented Programming

BC401

Facilitated Discussion This is an opportunity to discuss any open issues that may have arisen. In most cases, however, we suggest moving swiftly forwards to the more practice-based lessons.

Discussion Questions Use the following questions to engage the participants in the discussion.Feel free to use your own additional questions. Use the questions as appropriate to find out what participants know.

102

© 2004 SAP AG. All rights reserved.

08-03-2004


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

08-03-2004

© 2004 SAP AG. All rights reserved.

103


Unit 2: Introduction to Object-Oriented Programming

Lesson: 97

BC401

Analysis and Design with UML Lesson Duration: 45 Minutes

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

In this lesson, it is important to make clear distinctions between modeling concepts and the related programming concepts. Example: When looking at a class diagram, we often speak of “inheritance”, although we actually mean a “generalization/specialization relationship”. This requires strict discipline, especially from people who are new to the subject matter and may still be somewhat unsure. For the moment, we are only dealing with modeling.

Business Example A business application requirement is to be modeled before it is implemented.

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

104

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Analysis and Design with UML

Figure 51: Classification of Objects

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. 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. For example: 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. 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.

105


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 52: Classes as Abstraction Forms

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. 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. In reality, classification is the decisive step. Therefore, it requires extensive considerations that would go far beyond the framework of this course. This must be emphasized to the participants. At this point, you will need to keep questions to a minimum and ask participants to be patient to keep up the necessary pace. As this is a training situation, a certain starting situation has to be accepted as given.

106

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Analysis and Design with UML

Figure 53: Classes and Objects – Comparison

A sure understanding of the relationship between classes and objects is an absolute prerequisite for proceeding with the following lessons successfully.

Modeling in UML 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. 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. 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.

107


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 Later, we will need to find concrete methods for realizing the first two aspects in the list in the programming language. 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.

Figure 54: Representation of a Class

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

108

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Analysis and Design with UML

Figure 55: Example of a Class Diagram

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. Generalization / Specialization In this example: A car, a bus, and a truck are all vehicles. 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.

Figure 56: association

08-03-2004

© 2004 SAP AG. All rights reserved.

109


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

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

Figure 57: Aggregation and Composition

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

110

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Analysis and Design with UML

For example, a car partly consists of wheels. 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. 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. In UML notation, composition is denoted by a filled-in rhombus.

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.

111


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 59: sequence diagram

Sequence diagrams are used to display certain processes or situations. Sequence diagrams focus on the time sequence of the behavior: • •

Creating and deleting objects Exchanging messages between objects

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. The control focus is shown as a vertical rectangle on the object lifeline. The control focus shows the object’s “active” period: • •

An object is active when actions are executed An object is indirectly active if it is waiting for a subordinate procedure to end

Messages are shown as horizontal arrows between the object lines. The message is written above the arrow in the form 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.

112

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Analysis and Design with UML

Figure 60: Delegation Principle in a Sequence Diagram

In delegation, two objects are involved in handling a request: The recipient of the request delegates the execution of the request to a delegate. 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

113


Unit 2: Introduction to Object-Oriented Programming

114

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

107

Lesson: Analysis and Design with UML

Exercise 5: UML Class Diagrams Exercise Duration: 15 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Design simple UML class diagrams • Model basic object classifications

Business Example Modeling simple airplane management.

Task 1: Model some key classes for simple airplane management. 1.

2.

Your UML class diagram should contain the following classes: LCL_CARRIER

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.

Task 2: Define relationships between your classes.

08-03-2004

1.

Choose suitable association types.

2.

Choose suitable cardinalities.

© 2004 SAP AG. All rights reserved.

115


Unit 2: Introduction to Object-Oriented Programming

BC401

Solution 5: UML Class Diagrams Task 1: Model some key classes for simple airplane management. 1.

Your UML class diagram should contain the following classes: 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.

Task 2: Define relationships between your classes. 1.

Choose suitable association types. a) b)

2.

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.

116

© 2004 SAP AG. All rights reserved.

08-03-2004


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

08-03-2004

© 2004 SAP AG. All rights reserved.

117


Unit 2: Introduction to Object-Oriented Programming

Lesson: 110

BC401

Fundamental Object-Oriented Syntax Elements Lesson Duration: 255 Minutes

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

Define classes Generate and delete objects Access attributes Call methods

This is one of the most comprehensive lessons. It introduces many new concepts and syntax elements in quick succession. It is very important that you proceed one small step at a time. We highly recommend showing all demonstrations in the system. Otherwise, the participants will not be able to complete the exercises. The best approach is for you to create an empty program. First define an empty local class in the program and then build on it with each step. However, remember to emphasize that the example you are implementing relates to the graphics and the presentation in the lesson and that it differs from the program the participants will use in the accompanying exercises. This lesson is the key to understanding all further lessons about object-oriented programming in ABAP Objects . Make sure there are no unanswered questions.

Business Example You want to the implement classes, objects, and associations of your model in ABAP Objects.

Classes, Attributes, and Methods The concept of classes is the foundation for all object-oriented thinking. This section will explain and define the main components of a class.

118

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

Figure 61: Example of a Class

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

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

08-03-2004

© 2004 SAP AG. All rights reserved.

119


Unit 2: Introduction to Object-Oriented Programming

BC401

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.

Figure 63: Example of Attributes

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. Examples of attributes for the class LCL_VEHICLE are:

120

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.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

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. 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. Using TYPE REF TO, an attribute can be typed as any reference. This will be discussed in more detail later.

Figure 65: Visibility Sections of Attributes

08-03-2004

© 2004 SAP AG. All rights reserved.

121


Unit 2: Introduction to Object-Oriented Programming

BC401

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. Note: The “friendship” concept is an exception to this rule. 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”. 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. 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.

Figure 66: Accessing Private Attributes

Define private attributes in the PRIVATE SECTION of a class. Define public attributes in the PUBLIC SECTION. 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:

122

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

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. 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. To save runtime, individual attributes are sometimes defined in the public visibility section, but they must then be given the READ-ONLY addition.

Figure 67: Comparison of Instance Attributes with Static Attributes

There are two kinds of 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. 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: • • •

08-03-2004

Types and constants Central application data buffers Administration information, for example instance counters

© 2004 SAP AG. All rights reserved.

123


Unit 2: Introduction to Object-Oriented Programming

BC401

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

Figure 68: Instance Attributes and Static Attributes in the Program Context

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

124

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

Figure 69: Methods – Syntax

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

08-03-2004

© 2004 SAP AG. All rights reserved.

125


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 70: Visibility Sections of Methods

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.

Figure 71: Accessing Private Methods

Define private methods in the PRIVATE SECTION of a class. Define public attributes in the PUBLIC SECTION.

126

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

It is not possible to directly access private methods from outside. However, a private method can be called by a public method. 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. Caution: This is an introductory example. Later, you will learn more programming techniques for evaluating formal parameters. 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.

Figure 72: Comparison of Instance Methods with Static Methods

Instance methods are defined using the syntax keyword METHODS. 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. 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

127


Unit 2: Introduction to Object-Oriented Programming

BC401

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

Figure 73: Visibility Sections and UML Notation

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. 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. Static components are marked with an underscore. The method signature is represented as follows (optional): •

The input and output parameters and the parameters to be changed are shown in brackets 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.

Your demonstration program should now look somewhat like the executable program SAPBC401_VEHICLE_MAIN_A.

128

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

This is a good time to carry out the first exercise of this lesson.

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.

Figure 74: Overview of Instances of Classes

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. 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. For example: Instantiation of class LCL_VEHICLE creates a vehicle object. The private attributes still contain the technical initial values.

08-03-2004

© 2004 SAP AG. All rights reserved.

129


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 75: Definition of Reference Variables

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

Figure 76: Creating Objects

The statement CREATE OBJECT creates an object in the memory. Its attribute values are then either initial or assigned according to the VALUE specification.

130

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

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. Sometimes, experienced participants suggest using field symbols for this. If this happens, it is a good opportunity to clarify the principal differences again. This material is also contained in previous lessons.

Figure 78: Garbage Collector

08-03-2004

© 2004 SAP AG. All rights reserved.

131


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. It is not worth spending more than 60 seconds discussing the Garbage Collector. Application developers cannot influence it. Developers also do not have to work any differently depending on whether the Garbage Collector is running or not. Some experienced participants refuse to accept that they can no longer have access to objects, if those objects’ addresses have been lost.

Figure 79: Reference Administration with Multiple Instantiation

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.

132

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

Figure 80: Aggregation Example

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. References are transferred to objects in class LCL_VEHICLE to create the desired association. Your demonstration program should now look somewhat like the executable program SAPBC401_VEHICLE_MAIN_B.

This is a good time to carry out the second exercise of this lesson.

Accessing Attributes and Methods 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

133


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 81: Calling Methods

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

134

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

Figure 82: Calling Instance Methods – Syntax

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. 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. 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. It is not worth making a big thing of the shorter syntax. It was introduced to make ABAP Objects syntax resemble C++ and Java even more closely. However, participants will also have to maintain older source code, so they need to know the explicit syntax as well.

08-03-2004

© 2004 SAP AG. All rights reserved.

135


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 83: Calling Static Methods – Syntax

Static methods (also referred to as class methods) are called using CALL METHOD classname=>method_name .... Like static attributes, static methods are addressed with their class name, since they do not need instances. 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.

136

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

Figure 84: Functional Methods

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. Functional methods can be called directly within various expressions: • • • • •

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

Functional method calls are sometimes confused with the short form of other method calls. The former are possible from the beginning (so, as ofSAP R/3 4.6A). The latter are only possible as of SAP Web AS 6.10.

08-03-2004

© 2004 SAP AG. All rights reserved.

137


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 85: Functional Methods – Examples

In the first of these examples, two calls of functional instance methods represent the two addends of an addition. 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: DATA number TYPE i. ... CALL METHOD lcl_vehicle=>get_n_o_vehicles RECEIVING re_count = number.

138

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

Figure 86: Accessing Public Attributes

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. Your demonstration program should now look somewhat like the executable program SAPBC401_VEHICLE_MAIN_C.

This is a good time to carry out the third exercise of this lesson.

Constructors 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. At this point, some participants struggle with their experiences with other object-oriented languages. Some languages understand the constructor differently than ABAP Objects. This can cause confusion. Avoid any unclarity, as the concept is actually very simple.

08-03-2004

© 2004 SAP AG. All rights reserved.

139


Unit 2: Introduction to Object-Oriented Programming

BC401

Figure 87: (Instance) Constructor

The constructor is a special instance method in a class and is always named CONSTRUCTOR. This abbreviated term actually means the instance constructor. The constructor is automatically called at runtime with the CREATE OBJECT statement. Always consider the following points when you define constructors: • • • • •

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 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. (The corresponding comments in the SAP Library and the menu paths outside of the ABAP Workbench are only contained in internal system calls.)

140

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

Unfortunately, they are not dynamically hidden. Therefore, you may still be faced with the participants’ questions. Avoid any discussion about this topic.

Figure 88: Constructor – Example

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

Your demonstration program should now look somewhat like the executable program SAPBC401_VEHICLE_MAIN_D.

08-03-2004

© 2004 SAP AG. All rights reserved.

141


Unit 2: Introduction to Object-Oriented Programming

BC401

This is a good time to carry out the fourth exercise of this lesson.

Figure 89: Example of a Static Constructor

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

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

Always consider the following points when you define static constructors: • • • •

142

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

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

You could make a careful comparison with the LOAD-OF-PROGRAM ABAP event for function groups.

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

Figure 90: Self-Reference

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

08-03-2004

© 2004 SAP AG. All rights reserved.

143


Unit 2: Introduction to Object-Oriented Programming

BC401

Your demonstration program should now look somewhat like the executable program SAPBC401_VEHICLE_MAIN_E.

This is a good time to carry out the fifth exercise of this lesson.

144

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

137

Lesson: Fundamental Object-Oriented Syntax Elements

Exercise 6: Local Classes Exercise Duration: 40 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Declare local classes • Define attributes • Define and implement methods

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Create a new program. 1.

Create an executable program without a TOP include. Program name: ZBC401_##_MAIN (Where ## is your two-digit group number).

2.

Create an include program and include it in your ZBC401_##_MAIN main program. Program name: ZBC401_##_AIRPLANE (Where ## is your two-digit group number).

Task 2: Declare a class for airplanes. 1.

Within your include program, declare the local class LCL_AIRPLANE. Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

145


Unit 2: Introduction to Object-Oriented Programming

2.

BC401

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.

3.

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.

Define the public instance method DISPLAY_ATTRIBUTES for displaying the private instance attributes. 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. Hint: Use the statement TYPE-POOLS icon. to do this. 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.

5.

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.

146

© 2004 SAP AG. All rights reserved.

08-03-2004


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 (Where ## is your two-digit group number). a)

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_AIRS_MAIN_A

2.

Create an include program and include it in your ZBC401_##_MAIN main program. Program name: ZBC401_##_AIRPLANE (Where ## is your two-digit group number). a)

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_AIRS_A

b)

See the source code extract from the model solution

Task 2: Declare a class for airplanes. 1.

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

3.

See the source code extract from the model solution

Define the public instance method SET_ATTRIBUTES for setting the private instance attributes.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

147


Unit 2: Introduction to Object-Oriented Programming

BC401

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

See the source code extract from the model solution

Define the public instance method DISPLAY_ATTRIBUTES for displaying the private instance attributes. 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. Hint: Use the statement TYPE-POOLS icon. to do this. 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. a)

5.

See the source code extract from the model solution

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

Result Source code extract:

SAPBC401_AIRS_MAIN_A REPORT

sapbc401_airs_main_a.

Continued on next page

148

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

TYPE-POOLS icon.

INCLUDE sapbc401_airs_a.

SAPBC401_AIRS_A *&---------------------------------------------------------------------* *&

Include

SAPBC401_AIRS_A

*

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

CLASS lcl_airplane DEFINITION

*

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

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

METHODS: set_attributes IMPORTING im_name

TYPE string

im_planetype TYPE saplane-planetype, display_attributes.

CLASS-METHODS: display_n_o_airplanes.

PRIVATE SECTION. "---------------------------------DATA: name

TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i.

"lcl_airplane DEFINITION

ENDCLASS.

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

CLASS lcl_airplane IMPLEMENTATION

*

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

METHOD set_attributes.

*

name

= im_name.

planetype

= im_planetype.

doesn’t make sense so much -

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

149


Unit 2: Introduction to Object-Oriented Programming

*

only in order to get an effect

*

after calling display_n_o_airplanes:

BC401

n_o_airplanes = n_o_airplanes + 1. "set_attributes

ENDMETHOD.

METHOD display_attributes. WRITE: / icon_ws_plane AS ICON, / ’Name des Flugzeugs:’(001), AT pos_1 name, / ’Flugzeugtyp’(002), AT pos_1 planetype. "display_attributes

ENDMETHOD.

METHOD display_n_o_airplanes. WRITE: /, / ’Gesamtzahl der Flugzeuge’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. ENDMETHOD.

ENDCLASS.

150

"display_n_o_airplanes "lcl_airplane IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

143

Lesson: Fundamental Object-Oriented Syntax Elements

Exercise 7: Objects Exercise Duration: 20 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Define reference variables • Instantiate objects • Process object references using an internal table

Business Example Create instances of your airplane type and ensure that their addresses are not lost.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Define reference variables. 1.

Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. Define a reference variable for the instances of your class LCL_AIRPLANE.

2.

Define an internal table for buffering references to instances of the class LCL_AIRPLANE.

Task 2: Create airplane objects.

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.

151


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. Define a reference variable for the instances of your class LCL_AIRPLANE. a) b)

2.

Model solution: SAPBC401_AIRS_MAIN_B See the source code extract from the model solution

Define an internal table for buffering references to instances of the class LCL_AIRPLANE. a)

See the source code extract from the model solution

Task 2: Create airplane objects. 1.

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

Continued on next page

152

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

SAPBC401_AIRS_MAIN_B REPORT

sapbc401_airs_main_b.

TYPE-POOLS icon. INCLUDE sapbc401_airs_a.

DATA: r_plane TYPE REF TO lcl_airplane, plane_list TYPE TABLE OF REF TO lcl_airplane.

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

CREATE OBJECT r_plane. APPEND r_plane TO plane_list.

CREATE OBJECT r_plane. APPEND r_plane TO plane_list.

CREATE OBJECT r_plane. APPEND r_plane TO plane_list.

08-03-2004

© 2004 SAP AG. All rights reserved.

153


Unit 2: Introduction to Object-Oriented Programming

154

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

147

Lesson: Fundamental Object-Oriented Syntax Elements

Exercise 8: Method Calls Exercise Duration: 30 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Call non-functional methods • Define functional methods • Call functional methods:

Business Example You need to fill the attributes of the “empty” airplane objects with suitable values.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Call the methods of your class. 1.

Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. Call the static method DISPLAY_N_O_AIRPLANES twice: Once before and once after the instantiations. Caution: For reasons explained in the first exercise, you may not notice any effects at the moment.

2.

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. Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

155


Unit 2: Introduction to Object-Oriented Programming

BC401

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.

2.

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.

156

© 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. Call the static method DISPLAY_N_O_AIRPLANES twice: Once before and once after the instantiations. Caution: For reasons explained in the first exercise, you may not notice any effects at the moment. a) b)

2.

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)

3.

Model solution: SAPBC401_AIRS_MAIN_C See the source code extract from the model solution

See the source code extract from the model solution

Display the attribute values in the ABAP list using the DISPLAY_ATTRIBUTES method. a)

See the source code extract from the model solution

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

157


Unit 2: Introduction to Object-Oriented Programming

BC401

Result Source code extract:

SAPBC401_AIRS_MAIN_C REPORT

sapbc401_airs_main_c.

TYPE-POOLS icon. INCLUDE sapbc401_airs_c. DATA: r_plane TYPE REF TO lcl_airplane, plane_list TYPE TABLE OF REF TO lcl_airplane, count TYPE i.

START-OF-SELECTION. *############################## lcl_airplane=>display_n_o_airplanes( ).

CREATE OBJECT r_plane. APPEND r_plane TO plane_list. r_plane->set_attributes( im_name = ’LH Berlin’ im_planetype = ’A321’ ).

CREATE OBJECT r_plane. APPEND r_plane TO plane_list. r_plane->set_attributes( im_name = ’AA New York’ im_planetype = ’747-400’ ).

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.

* long syntax for functional call: * CALL METHOD lcl_airplane=>get_n_o_airplanes *

RECEIVING

Continued on next page

158

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

*

re_count = count.

* a little bit shorter: * 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. WRITE: / ’Gesamtzahl der Flugzeuge’(ca1), count.

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

Include

SAPBC401_AIRS_C

*&

Show functional static method get_n_o_airplanes

* *

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

CLASS lcl_airplane DEFINITION

*

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

TYPE string

im_planetype TYPE saplane-planetype, display_attributes. CLASS-METHODS: display_n_o_airplanes, get_n_o_airplanes RETURNING value(re_count) TYPE i.

PRIVATE SECTION. "---------------------------------DATA: name

TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS.

"lcl_airplane DEFINITION

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

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

159


Unit 2: Introduction to Object-Oriented Programming

*

CLASS lcl_airplane IMPLEMENTATION

BC401

*

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. METHOD set_attributes. name

= im_name.

planetype

= im_planetype.

n_o_airplanes = n_o_airplanes + 1. ENDMETHOD.

"set_attributes

METHOD display_attributes. WRITE: / icon_ws_plane AS ICON, / ’Name des Flugzeugs:’(001), AT pos_1 name, / ’Flugzeugtyp’(002), AT pos_1 planetype. ENDMETHOD.

"display_attributes

METHOD display_n_o_airplanes. WRITE: /, / ’Gesamtzahl der Flugzeuge’(ca1), AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /. ENDMETHOD.

"display_n_o_airplanes

METHOD get_n_o_airplanes. re_count = n_o_airplanes. ENDMETHOD.

ENDCLASS.

160

"get_n_o_airplanes "lcl_airplane IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

153

Lesson: Fundamental Object-Oriented Syntax Elements

Exercise 9: Constructors Exercise Duration: 15 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Define and implement instance constructors • Create instances of classes that contain an instance constructor

Business Example Make your program more realistic: The airplane objects receive their attributes as soon as they are created.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

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). Define a reference variable with a suitable signature for the instances of your class LCL_AIRPLANE. Implement it so that the two instance attributes are set and the instance counter N_O_AIRPLANES is increased by one.

2.

If you previously used the SET_ATTRIBUTES method to increase the instance counter, remove the relevant statement from the method now.

Task 2: Create airplane objects. 1.

Your CREATE OBJECT statements from the previous exercise should now be syntactically incorrect. Adapt and correct them. Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

161


Unit 2: Introduction to Object-Oriented Programming

162

BC401

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.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

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). Define a reference variable with a suitable signature for the instances of your class LCL_AIRPLANE. Implement it so that the two instance attributes are set and the instance counter N_O_AIRPLANES is increased by one. a) b)

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

Task 2: Create airplane objects. 1.

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

3.

See the source code extract from the model solution

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.

TYPE-POOLS icon.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

163


Unit 2: Introduction to Object-Oriented Programming

BC401

INCLUDE sapbc401_airs_d. DATA: r_plane TYPE REF TO lcl_airplane, plane_list TYPE TABLE OF REF TO lcl_airplane.

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

lcl_airplane=>display_n_o_airplanes( ).

CREATE OBJECT r_plane EXPORTING im_name = ’LH Berlin’ im_planetype = ’A321’. APPEND r_plane TO plane_list. r_plane->display_attributes( ).

CREATE OBJECT r_plane EXPORTING im_name = ’AA New York’ im_planetype = ’747-400’. APPEND r_plane TO plane_list. r_plane->display_attributes( ). CREATE OBJECT r_plane EXPORTING im_name = ’US Hercules’ im_planetype = ’747-500’. APPEND r_plane TO plane_list. r_plane->display_attributes( ).

lcl_airplane=>display_n_o_airplanes( ).

SAPBC401_AIRS_D *&---------------------------------------------------------------------* *&

Include

SAPBC401_AIRS_D

*

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

CLASS lcl_airplane DEFINITION

*

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

Continued on next page

164

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

PUBLIC SECTION. "-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: constructor IMPORTING im_name

TYPE string

im_planetype TYPE saplane-planetype, display_attributes. CLASS-METHODS: display_n_o_airplanes.

PRIVATE SECTION. "---------------------------------DATA: name

TYPE string,

planetype TYPE saplane-planetype. CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS.

"lcl_airplane DEFINITION

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

CLASS lcl_airplane IMPLEMENTATION

*

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. METHOD constructor. name

= im_name.

planetype

= im_planetype.

n_o_airplanes = n_o_airplanes + 1. "constructor

ENDMETHOD.

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, /. ENDMETHOD. ENDCLASS.

08-03-2004

"display_n_o_airplanes "lcl_airplane IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

165


Unit 2: Introduction to Object-Oriented Programming

166

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

157

Lesson: Fundamental Object-Oriented Syntax Elements

Exercise 10: Private Methods Exercise Duration: 30 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Use the delegation principle • Realize business application objects based on database contents

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Declare another method. 1.

Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. Within the class LCL_AIRPLANE, define the private instance method GET_TECHNICAL_ATTRIBUTES. 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.

2.

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:

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

167


Unit 2: Introduction to Object-Oriented Programming

BC401

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.

Task 2: Call the method.

168

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.

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?

© 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. Within the class LCL_AIRPLANE, define the private instance method GET_TECHNICAL_ATTRIBUTES. 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. 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. 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. a)

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)

2.

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.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

169


Unit 2: Introduction to Object-Oriented Programming

3.

BC401

Are there any alternative solutions that fulfill the same purpose, but still adhere to the delegation principle? What are they? Answer: •

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.

Result Source code extract:

SAPBC401_AIRS_E *&---------------------------------------------------------------------* *&

Include

SAPBC401_AIRS_E

*

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

CLASS lcl_airplane DEFINITION

*

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

PUBLIC SECTION. "-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: constructor IMPORTING im_name

TYPE string

im_planetype TYPE saplane-planetype, display_attributes.

CLASS-METHODS: display_n_o_airplanes. PRIVATE SECTION. "---------------------------------METHODS: get_technical_attributes

Continued on next page

170

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Fundamental Object-Oriented Syntax Elements

IMPORTING im_type

DATA: name

TYPE saplane-planetype

EXPORTING ex_weight

TYPE s_plan_wei

ex_tankcap

TYPE s_capacity.

TYPE string,

planetype TYPE saplane-planetype. CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS.

"lcl_airplane DEFINITION

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

CLASS lcl_airplane IMPLEMENTATION

*

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. METHOD constructor. name

= im_name.

planetype

= im_planetype.

n_o_airplanes = n_o_airplanes + 1. ENDMETHOD.

"constructor

METHOD display_attributes. DATA: weight TYPE saplane-weight, cap TYPE saplane-tankcap. WRITE: / icon_ws_plane AS ICON, / ’Name 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

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

"display_n_o_airplanes

METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) WHERE planetype = im_type. IF sy-subrc <> 0.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

171


Unit 2: Introduction to Object-Oriented Programming

BC401

ex_weight = 100000. ex_tankcap = 10000. ENDIF. ENDMETHOD.

ENDCLASS.

172

"get_technical_attributes

"lcl_airplane IMPLEMENTATION

© 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

Related Information ... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.

08-03-2004

© 2004 SAP AG. All rights reserved.

173


Unit Summary

BC401

Unit 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 • Name the most important diagram types in UML • Create class diagrams • Create sequence diagrams • Define classes • Generate and delete objects • Access attributes • Call methods

174

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

165

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.

□ □

08-03-2004

True False

2.

What does multiple instantiation mean?

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?

6.

In ABAP Objects, what is meant by the term constructor?

© 2004 SAP AG. All rights reserved.

175


Test Your Knowledge

7.

176

BC401

You are defining a class. Must you always also define a constructor?

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

167

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. Answer: False Refer to the relevant section of the lesson.

2.

What does multiple instantiation mean? Answer: The ability to create and manage any number of runtime instances for each program context Refer to the relevant section of the lesson.

3.

What does encapsulation mean? Answer: Gathering data and functions into reusable units from which users can only call certain functions and cannot access the data directly. Refer to the relevant section of the lesson.

4.

In ABAP Objects, what is meant by the term class? 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.

5.

What is the difference between a class’s static components and its instance components? 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. Refer to the relevant section of the lesson.

08-03-2004

© 2004 SAP AG. All rights reserved.

177


Test Your Knowledge

6.

BC401

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.

7.

You are defining a class. Must you always also define a constructor? Answer: No Refer to the relevant section of the lesson.

178

© 2004 SAP AG. All rights reserved.

08-03-2004


Unit 3 169

Object-Oriented Concepts and Programming Techniques The idea behind Compass courses is that individual lessons are effective without being restricted to a certain context. In this case, that means that participants could theoretically understand the lesson about interfaces even if they had not covered the lesson about inheritance yet. To facilitate this, some information is repeated throughout the units, meaning that the second lesson can often be compressed into a few sentences. Except for the different syntax, you can show the complete analogy between interfaces and abstract superclasses that have exclusively public abstract methods. So that the lessons are not dependent on a certain context, the key contents and demonstrations have to be repeated. However, throughout the whole course, we suggest that you refer to regular inheritance in relation to interfaces as often as possible. This is not to save time, but highlight the relationships. That should make it easier for participants to understand the connections. This lesson contains a lot of new material for the participants, so you may see the first signs of irritation or waning interest. In such cases, point out that this unit deals with general concepts of object-orientation. They can be very useful in other object-oriented languages as well. Work with participants to deduce the purpose of every single concept and determine where they would use them. Occasionally, comparisons to the procedural programming model can also help to create a clearer understanding. The exercises are there to show that the material really is fairly simple. Once participants realize that they do understand the course contents, you might observe increases in motivation levels – especially from those participants who were anxious about the course.

08-03-2004

© 2004 SAP AG. All rights reserved.

179


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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

Unit Objectives After completing this unit, you will 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

Unit Contents Lesson: Inheritance and Casting .............................................182 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 ..................................243 Exercise 15: Aggregation, Generic Calls, and Polymorphism ........257

180

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Unit 3: Object-Oriented Concepts and Programming Techniques

Lesson: Events..................................................................265 Exercise 16: Events in Superclasses ....................................275 Exercise 17: Events in Interfaces (optional) ............................287

08-03-2004

© 2004 SAP AG. All rights reserved.

181


Unit 3: Object-Oriented Concepts and Programming Techniques

Lesson:

Inheritance and Casting

171

Lesson Duration: 225 Minutes

BC401

Lesson Overview 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: • • • • • •

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

The last part of this lesson is definitely the most important: Inheritance must always be used correctly. Do note define inheritance relationships between semantically unrelated classes simply to achieve technical advantages (such as centralized maintenance, polymorphism, extensibility). Instead, inheritance must always derive from a generalization/specialization relationship that was recognized as early as the modeling phase. This will result in the advantageous programming possibilities. As in the previous lesson, work your way through a demonstration program in parallel to the theoretical material. At this point at the latest, you should start using the term “signature” when you refer to the parameters of a method. The term “interface” is used to mean several different things. Avoid using it as of the following lesson as it could create confusion.

Business Example You want to implement generalization/specialization relationships from your model in ABAP Objects.

182

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

Realization of Generalization/Specialization Relationships Using Iheritance 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.

Figure 91: Example of Generalization/Specialization

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. Specialization is often described as an “is a” relationship. In this example, you would say: “A truck is a (specific) vehicle.” Reversing the point of view is referred to as generalization.

08-03-2004

© 2004 SAP AG. All rights reserved.

183


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Figure 92: Characteristics of Generalization/Specialization

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

184

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

Figure 93: Inheritance – Syntax

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

08-03-2004

© 2004 SAP AG. All rights reserved.

185


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Figure 94: Redefining Methods

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

186

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

Figure 95: Preserving Semantics During Redefinition

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.

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

08-03-2004

© 2004 SAP AG. All rights reserved.

187


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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

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.

188

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

Figure 98: Inheritance and Visibility

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. When defining local classes in ABAP Objects, you must follow the syntactical sequence of PUBLIC SECTION, PROTECTED SECTION, PRIVATE SECTION.

08-03-2004

© 2004 SAP AG. All rights reserved.

189


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Figure 99: Protected vs. Private Section

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. 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. 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. There is only one static component per program context. To summarize: Static Components and Inheritance • •

190

A class that defines a public or protected static attribute shares this attribute with all its subclasses Static methods cannot be redefined

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

Your demonstration program should now look somewhat like the executable program SAPBC401_VEHICLE_MAIN_F.

Once again, remind participants of the benefit of these steps: Centralized maintenance of all general components of all vehicles!

At this point, we recommend having the participants do the first exercise of this lesson.

narrowing cast Variables of the type “reference to superclass” can also refer to subclass instances at runtime.

08-03-2004

© 2004 SAP AG. All rights reserved.

191


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Some relationships cannot be portrayed well in static diagram. At this point, we recommend that you draw the following diagram by hand and hide the slides: 1. 2. 3. 4. 5. 6. 7.

Draw the reference variable R_TRUCK (as an example) on the left side. Write “CREATE OBJECT r_truck ...” above the reference variable. Draw the object display of a truck on the right side and connect it to the reference variable. Within this object, draw an area with a few inherited components. Draw another reference variable R_VEHICLE some distance below the first one. Write “R_VEHICLE = R_TRUCK” above the second reference variable. Then ask the participants what the second reference variable contains. Now, it depends what you want to show with the diagram: From a technical point of view, only an address is copied, so you can draw an arrow from R_VEHICLE to the object. You must ask which components are addressed with R_VEHICLE. In contrast, in the following graphic we want to indicate the syntactic restriction of the second reference variable. (The only reason why the inherited components can be accessed using the second variable is because the static type is critical for the syntax check.)

Figure 100: Narrowing Cast With Object References

192

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

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

Figure 101: Static and Dynamic Types of References

A reference variable always has two types at runtime: static and dynamic. 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

08-03-2004

© 2004 SAP AG. All rights reserved.

193


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

object_id<\PROGRAM=program_name\CLASS=dynamic_type>

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. Your demonstration program should now contain something that looks like the executable program SAPBC401_VEHICLE_MAIN_G. You should run your program in debugging mode. Caution: At this point, the main program is still the client of the vehicle classes. This will change soon.

Remind participants of the benefits of narrowing cast assignments: It makes it easy to extend the vehicle management with new specific vehicles.

At this point, we recommend having the participants do the second exercise of this lesson. Strictly speaking, the exercise assumes some knowledge that will not be taught until the next paragraph, however this is unlikely to cause problems as many participants have probably already programmed in the manner that is required here. For those participants, this exercise is therefore obsolete anyway.

194

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

Figure 102: Generic Access After Narrowing Cast Assignments

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

Figure 103: Line Type of the Internal Table in the Applied Example

08-03-2004

© 2004 SAP AG. All rights reserved.

195


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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.

Figure 104: Narrowing Cast and Generic Access in the Applied Example

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.

196

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

Figure 105: Polymorphism – Generic Access Using the Superclass Reference

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

08-03-2004

© 2004 SAP AG. All rights reserved.

197


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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.

Figure 106: Generic Calls in the Procedural Programming Model

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. Your demonstration program should now look somewhat like the executable program SAPBC401_VEHICLE_MAIN_H.

At this point, we recommend having the participants do the third exercise of this lesson.

198

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

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”. At this point, we recommend that you add to your narrowing cast diagram and hide the slides: 1. 2.

3.

Draw another reference variable called R_TRUCK2 under R_VEHICLE. Write “R_TRUCK2 ?= R_VEHICLE” above the third reference variable and discuss the necessity of the “?” with the participants. Then ask the participants what the content of the third reference variable is. Draw an arrow from R_TRUCK2 to the object. You must ask which components can be addressed with R_TRUCK2.

Figure 107: Widening Cast With Object References

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

199


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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

Figure 108: Specific Access After Widening Cast Assignments

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

200

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

Figure 109: Widening Cast Assignment and Exception Handling in the Application Example

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. 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. We recommend you do a separate demonstration to show the necessity of identifying the exception. You can use program SAPBC401_VEHICLE_MAIN_I as the copy template for this. Note: You must refer to the specific lesson about the exception concept. You do not have enough time to discuss this topic now!

08-03-2004

© 2004 SAP AG. All rights reserved.

201


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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

Figure 110: Using Inheritance

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.

Figure 111: Examples: Misuse of Inheritance

202

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

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: 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. 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”. In some cases, specialization relationships are identified that do not allow for the semantics to be preserved. For example: 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. 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

203


Unit 3: Object-Oriented Concepts and Programming Techniques

204

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

191

Lesson: Inheritance and Casting

Exercise 11: Class Hierarchies Exercise Duration: 40 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Define subclasses • Redefine superclass methods in subclasses • Use visibility sections effectively

Business Example Your airplane management program is to be refined further. Put specific airplanes in relation to their general airplane class.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: In the class LCL_AIRPLANE, define the local subclass LCL_PASSENGER_PLANE for passenger planes. 1.

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.

2.

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.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

205


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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.

3.

Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed using the WRITE statement.

Task 3: Create instances of your new classes and display their attributes. 1.

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.

Task 4: Analyze your program.

206

1.

Observe the program flow in the ABAP Debugger, paying special attention to the call of the DISPLAY_ATTRIBUTES method.

2.

Could the method GET_TECHNICAL_ATTRIBUTES be called directly from the redefined method DISPLAY_ATTRIBUTES of the subclasses?

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

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

2.

The class must have a private instance attribute MAX_SEATS with the same type as the table field SFLIGHT-SEATSMAX. a)

3.

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)

4.

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_INHS_MAIN_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

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

2.

Define and implement an instance constructor that assigns values to all instance attributes in the class. a)

3.

See the source code extract from the model solution

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 Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

207


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Task 3: Create instances of your new classes and display their attributes. 1.

In the main program, define a suitably typed reference variable for each of your new classes. a)

2.

See the source code extract from the model solution

Call the static method DISPLAY_N_O_AIRPLANES (before instantiating any objects). a)

3.

See the source code extract from the model solution

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)

4.

See the source code extract from the model solution

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

See the source code extract from the model solution

Task 4: Analyze your program. 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

Result Source code extract:

SAPBC401_INHS_MAIN_A REPORT

sapbc401_inhs_main_a.

TYPE-POOLS icon.

Continued on next page

208

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

INCLUDE sapbc401_inhs_a.

DATA: r_plane TYPE REF TO lcl_airplane, r_cargo TYPE REF TO lcl_cargo_plane, r_passenger TYPE REF TO lcl_passenger_plane, plane_list TYPE TABLE OF REF TO lcl_airplane.

START-OF-SELECTION. *############################## lcl_airplane=>display_n_o_airplanes( ).

CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345.

CREATE OBJECT r_cargo EXPORTING im_name = ’US Hercules’ im_planetype = ’747-500’ im_cargo = 533.

r_cargo->display_attributes( ).

r_passenger->display_attributes( ).

lcl_airplane=>display_n_o_airplanes( ).

SAPBC401_INHS_A *&---------------------------------------------------------------------* *&

Include

SAPBC401_INHS_A

*

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

CLASS lcl_airplane DEFINITION

*

*------------------------------------------------------------------* CLASS lcl_airplane DEFINITION. PUBLIC SECTION.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

209


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

"-------------------------------CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: constructor IMPORTING im_name

TYPE string

im_planetype TYPE saplane-planetype, display_attributes.

CLASS-METHODS: display_n_o_airplanes. PRIVATE SECTION. "---------------------------------METHODS: get_technical_attributes IMPORTING im_type

DATA: name

TYPE saplane-planetype

EXPORTING ex_weight

TYPE s_plan_wei

ex_tankcap

TYPE s_capacity.

TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS.

"lcl_airplane DEFINITION

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

CLASS lcl_airplane IMPLEMENTATION

*

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

METHOD constructor. name

= im_name.

planetype

= im_planetype.

n_o_airplanes = n_o_airplanes + 1. ENDMETHOD.

"constructor

METHOD display_attributes. DATA: weight TYPE saplane-weight, cap TYPE saplane-tankcap. WRITE: / icon_ws_plane AS ICON, / ’Name 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: / ’Gewicht:’(003), weight,

Continued on next page

210

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

’Tankkap:’(004), cap. ENDMETHOD.

"display_attributes

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

"display_n_o_airplanes

METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) WHERE planetype = im_type. IF sy-subrc <> 0. ex_weight = 100000. ex_tankcap = 10000. ENDIF.

ENDMETHOD.

"get_technical_attributes

ENDCLASS.

"lcl_airplane IMPLEMENTATION

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

CLASS lcl_cargo_plane DEFINITION

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

PUBLIC SECTION. "---------------------METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype im_cargo TYPE scplane-cargomax. METHODS: display_attributes REDEFINITION.

PRIVATE SECTION. "---------------------DATA: max_cargo TYPE scplane-cargomax.

ENDCLASS.

"lcl_cargo_plane DEFINITION

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

CLASS lcl_cargo_plane IMPLEMENTATION

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

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

211


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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

METHOD constructor. CALL METHOD super->constructor( im_name = im_name im_planetype = im_planetype ). max_cargo = im_cargo. ENDMETHOD.

"constructor

METHOD display_attributes. super->display_attributes( ). WRITE: / ’Max Cargo = ’, max_cargo. ULINE. ENDMETHOD.

"display_attributes

"lcl_cargo_plane IMPLEMENTATION

ENDCLASS.

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

CLASS lcl_passenger_plane DEFINITION

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

PUBLIC SECTION. METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype im_seats TYPE sflight-seatsmax. METHODS: display_attributes REDEFINITION.

PRIVATE SECTION. DATA: max_seats TYPE sflight-seatsmax. "lcl_passenger_plane DEFINITION

ENDCLASS.

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

CLASS lcl_passenger_plane IMPLEMENTATION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION.

METHOD constructor. CALL METHOD super->constructor( EXPORTING im_name

= im_name

Continued on next page

212

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

im_planetype = im_planetype ). max_seats = im_seats. "constructor

ENDMETHOD.

METHOD display_attributes. super->display_attributes( ). WRITE: / ’Max Seats = ’, max_seats. ULINE. ENDMETHOD.

ENDCLASS.

08-03-2004

"display_attributes "lcl_passenger_plane IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

213


Unit 3: Object-Oriented Concepts and Programming Techniques

214

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

201

Lesson: Inheritance and Casting

Exercise 12: Polymorphism Exercise Duration: 20 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Program narrowing cast assignments • Use inheritance relationships for polymorphic method calls

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

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

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.

Task 2: Display the attributes of all airplane types that were created so far. 1.

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.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

215


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Task 3: Analyze your program.

216

1.

Follow the program flow in the ABAP Debugger, paying special attention to the call of the DISPLAY_ATTRIBUTES method.

2.

What would happen if the DISPLAY_ATTRIBUTES method had not been redefined in the subclasses?

© 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). a) b)

2.

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_CASS_MAIN_A

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

Task 2: Display the attributes of all airplane types that were created so far. 1.

Insert the references to your passenger and cargo airplanes into the internal table. a)

2.

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)

See the source code extract from the model solution

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


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Result Source code extract:

SAPBC401_CASS_MAIN_A REPORT

sapbc401_cass_main_a.

TYPE-POOLS icon. INCLUDE sapbc401_inhs_a. DATA: r_plane TYPE REF TO lcl_airplane, r_cargo TYPE REF TO lcl_cargo_plane, r_passenger TYPE REF TO lcl_passenger_plane, plane_list TYPE TABLE OF REF TO lcl_airplane.

START-OF-SELECTION. *############################## lcl_airplane=>display_n_o_airplanes( ).

CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. APPEND r_passenger TO plane_list.

CREATE OBJECT r_cargo EXPORTING im_name = ’US HErcules’ im_planetype = ’747-500’ im_cargo = 533. APPEND r_cargo TO plane_list.

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

lcl_airplane=>display_n_o_airplanes( ).

218

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

205

Lesson: Inheritance and Casting

Exercise 13: Aggregation and Generic Calls Exercise Duration: 30 Minutes

Exercise Objectives 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

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Define a local class for airlines. 1.

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

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.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

219


Unit 3: Object-Oriented Concepts and Programming Techniques

4.

BC401

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.

220

1.

Remove all the statements from the main program that define the global internal table for airplane references and their insertions.

2.

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.

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

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)

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

3.

See the source code extract from the model solution

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)

4.

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_CASS_MAIN_B

See the source code extract from the model solution

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

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


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

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

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

Result Source code extract:

SAPBC401_CASS_MAIN_B REPORT

sapbc401_cass_main_b.

TYPE-POOLS icon. INCLUDE sapbc401_cass_b.

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

START-OF-SELECTION. *############################## ***** Create Carrier ******************************************** CREATE OBJECT r_carrier EXPORTING im_name = ’Smile&Fly Travel’.

***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING

Continued on next page

222

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Inheritance and Casting

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

SAPBC401_CASS_B *&---------------------------------------------------------------------* *&

Include

SAPBC401_CASS_B

*

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

CLASS lcl_airplane DEFINITION

*

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

CLASS lcl_carrier DEFINITION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION. "---------------------------------------METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string, add_airplane IMPORTING im_plane TYPE REF TO lcl_airplane, display_airplanes, display_attributes. PRIVATE SECTION. "----------------------------------DATA: name

TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS.

"lcl_carrier DEFINITION

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

223


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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

CLASS lcl_carrier IMPLEMENTATION

*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD add_airplane. APPEND im_plane TO airplane_list. ENDMETHOD.

"add_airplane

METHOD display_attributes. WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). ENDMETHOD.

"display_attributes

METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane. LOOP AT airplane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP. ENDMETHOD.

"display_airplanes

METHOD constructor. name = im_name. ENDMETHOD.

"constructor

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

Related Information ... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.

08-03-2004

© 2004 SAP AG. All rights reserved.

225


Unit 3: Object-Oriented Concepts and Programming Techniques

Lesson:

Interfaces and Casting

212

Lesson Duration: 135 Minutes

BC401

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.

Lesson Objectives After completing this lesson, you will 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

Although there are no significant technical differences between regular inheritance and the implementation of interfaces, we have still created this full lesson. That means you can use it without having previously explained inheritance. The first section is the most important because it deals precisely with these differences. That means it serves to build on the analogy with regular inheritance rather than presenting particularly important, new programming techniques. While you are teaching, you must strictly differentiate between the terms “signature” and “interface.” Otherwise, you will confuse the participants.

Business Example You want to implement client/server relationships in combination with generic access from your model in ABAP Objects.

Areas of Use for Interfaces Interfaces differ from regular inheritance in their area of use. In terms of programming, there are hardly any differences, however.

226

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

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

Figure 112: Central Definition of Shared Components

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

227


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Figure 113: The Client Defines the Protocol

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

Figure 114: Interfaces in UML Notation

228

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

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. The similarity with representing a generalization/specialization relationship is justified, as we have just described.

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.

We recommend that you do a separate demonstration to show the definition and implementation of an interface. You can use program SAPBC401_VEHICLE_MAIN_J as the copy template for this.

Figure 115: Defining and Implementing an Interface

08-03-2004

© 2004 SAP AG. All rights reserved.

229


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Classes implement interfaces as follows: •

• •

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. 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. The interface method lif_1~method_1 can then be addressed with the shorter form ref->a_1 . At this point, we recommend having the participants do the first exercise of this lesson. Point out to them that the relatively large scope of the preparatory programming work is necessary to have a reasonably satisfactory initial scenario. But you can put this moment to positive effect: It is likely that most participants will not have previously experienced how easy it can be to join totally independent applications using object-oriented programming. The background here is the semantic context in terms of the interface to be defined.

230

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

Figure 116: Addressing Interface Components Using Object References

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. 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 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. Point out that the access to interface components using object references shown here is rarely used. At this point, the completeness of the explanation is what matters. The next section shows the actual way of working with interfaces.

Polymorphism with Interfaces 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

231


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Some relationships cannot be portrayed well in static diagram. At this point, we recommend that you draw the following diagram by hand and hide the slides: 1. 2. 3. 4. 5. 6.

7.

Draw the reference variable R_RENTAL (as an example) on the left side. Write “CREATE OBJECT r_rental ...” above the reference variable. Draw the object display of a car rental company on the right side and connect it to the reference variable. Within this object, draw an area with a few implemented interface components. Draw another reference variable R_PARTNER at some distance below the first one. Write “R_PARTNER = R_RENTAL.”above the second reference variable and ask the participants what the content of the second reference variable is. Now, it depends what you want to show with the diagram: From a technical point of view, only an address is copied so you can draw an arrow from R_PARTNER to the object. You must ask which components are addressed with R_PARTNER. In contrast, in the following graphic we want to indicate the syntactic restriction of the second reference variable. (Using the second variable, only the implementing interface components can therefore be accessed because the static type is critical for the syntax check.)

Figure 117: Narrowing Cast with Interface References

232

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

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

Figure 118: Row Type of the Internal Table in the Application Example

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

233


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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

Figure 119: Polymorphism – Generic Access Using the Interface Reference

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

234

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

actually refers to to search for the implementation of display_partner . The static type for r_partner , which is always REF TO lif_partner , 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. 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. 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. 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. Your demonstration program should now resemble the executable program SAPBC401_VEHICLE_MAIN_K. You should run your program in debugging mode.

At this point, we recommend having the participants do the second exercise of this lesson. Note: If the participants have already done this type of exercise as part of inheritance, reduce the next exercise to a simple recapitulation. In terms of programming, there are no new ideas.

08-03-2004

© 2004 SAP AG. All rights reserved.

235


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

At this point, we recommend that you add to your narrowing cast diagram and hide the slides: 1. 2.

3.

Draw a reference variable R_RENTAL2 below R_PARTNER. Write “R_RENTAL2 ?= R_PARTNER.” above the third reference variable and discuss the necessity of the “?” with the participants. Then ask the participants what the content of the third reference variable is. Draw an arrow from R_RENTAL2 to the object. You must ask which components are addressed with R_RENTAL2.

Figure 120: Widening Cast Assignment and Exception Handling in the Application Example

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

236

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

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

08-03-2004

© 2004 SAP AG. All rights reserved.

237


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

We recommend you do a separate demonstration to show the necessity of identifying the exception. Note: You must refer to the specific lesson about the exception concept. You do not have enough time to discuss this topic now.

Interface Hierarchies 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:

Figure 121: Interface Hierarchy in the Application Example

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

238

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

Figure 122: Compound Interface in UML Notation

In ABAP Objects, interfaces – like regular superclasses – can include other interfaces. As with regular inheritance, the result is interface hierarchies of any “depth.” You can thus regard the including interface as a specialization of the included interface. It represents an extension of the included interface. 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.

239


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Figure 123: Definition and Implementation of Compound Interfaces – Syntax

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. They are therefore not prefixed with the name of the compound interface. 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.

240

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

Figure 124: Addressing Components in Compound Interfaces – Syntax

The same possibilities apply for access its components from a compound interface and for cast assignments.

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

08-03-2004

© 2004 SAP AG. All rights reserved.

241


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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.

242

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

227

Lesson: Interfaces and Casting

Exercise 14: Interface Implementation Exercise Duration: 30 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Define interfaces • Implement interfaces

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

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

Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_CASS_MAIN_B (where ## is your two-digit group number).

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.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

243


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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.

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. Note: In the following, you need to store the relevant list outputs as a general service. 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.

3.

Define the local interface LIF_PARTNERS and the method DISPLAY_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.

4.

244

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.

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

Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_CASS_MAIN_B (where ## is your two-digit group number). a) b)

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

3.

Carry out this step in the usual manner. Additional information is available in the SAP Library.

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

4.

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_INTS_MAIN_A

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.

245


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. Note: In the following, you need to store the relevant list outputs as a general service. Caution: You will therefore not receive any output on the list until the next exercise. a)

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

3.

Carry out this step in the usual manner. Additional information is available in the SAP Library.

Speak to your instructor if you have any questions.

Define the local interface LIF_PARTNERS and the method DISPLAY_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)

4.

See the source code extract from the model solution

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:

SAPBC401_INTS_MAIN_A REPORT

sapbc401_ints_main_a.

TYPES ty_fuel TYPE p DECIMALS 2.

Continued on next page

246

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

TYPES ty_cargo TYPE p DECIMALS 2. TYPE-POOLS icon. INCLUDE sapbc401_vehd_f. INCLUDE sapbc401_ints_a. DATA: r_plane TYPE REF TO lcl_airplane, r_cargo TYPE REF TO lcl_cargo_plane, r_passenger TYPE REF TO lcl_passenger_plane, r_carrier TYPE REF TO lcl_carrier, r_rental TYPE REF TO lcl_rental, r_truck TYPE REF TO lcl_truck, r_bus TYPE REF TO lcl_bus.

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

***** Create CARRIER ******************************************** CREATE OBJECT r_carrier EXPORTING im_name = ’Smile&Fly Travel’.

***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US HErcules’ im_planetype = ’747-500’ im_cargo = 533. ***** insert planes into itab if client *************************** r_carrier->add_airplane( r_passenger ). r_carrier->add_airplane( r_cargo ). ***** show all airplanes inside carrier *************************** r_carrier->display_attributes( ). ******* create RENTAL ***************************************** CREATE OBJECT r_rental EXPORTING im_name = ’HAPPY CAR RENTAL’.

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

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

247


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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

***** show attributes of rental *************************** r_rental->display_attributes( ).

SAPBC401_VEHD_F *&---------------------------------------------------------------------* *&

Include

SAPBC401_VEHD_F

*

*&---------------------------------------------------------------------* *---------------------------------------------------------------------* * define interface lif_partners *---------------------------------------------------------------------* INTERFACE lif_partners. METHODS display_partner. ENDINTERFACE. *---------------------------------------------------------------------* *

CLASS lcl_vehicle DEFINITION

*---------------------------------------------------------------------* CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION. "------------------METHODS: get_average_fuel IMPORTING im_distance TYPE s_distance im_fuel TYPE ty_fuel RETURNING value(re_avgfuel) TYPE ty_fuel. METHODS

constructor IMPORTING im_make TYPE string.

METHODS

display_attributes.

METHODS

set_make IMPORTING im_make TYPE string.

METHODS

get_make EXPORTING ex_make TYPE string.

CLASS-METHODS get_count EXPORTING re_count TYPE i.

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

TYPE string.

METHODS

init_make.

Continued on next page

248

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

CLASS-DATA:

n_o_vehicles TYPE i.

"lcl_vehicle DEFINITION

ENDCLASS.

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

CLASS lcl_vehicle IMPLEMENTATION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_vehicle IMPLEMENTATION. METHOD get_average_fuel. re_avgfuel = im_distance / im_fuel. "get_average_fuel

ENDMETHOD.

METHOD constructor. make = im_make. ADD 1 TO n_o_vehicles. "constructor

ENDMETHOD.

METHOD set_make. IF im_make IS INITIAL. init_make( ).

" me->init_make( ). also possible

ELSE. make = im_make. ENDIF. "set_make

ENDMETHOD.

METHOD init_make. make = ’default make’. "init_make

ENDMETHOD.

METHOD get_make. ex_make = make. "get_make

ENDMETHOD.

METHOD display_attributes. WRITE: make. "display_attributes

ENDMETHOD.

METHOD get_count. re_count = n_o_vehicles. ENDMETHOD.

ENDCLASS.

"get_count "lcl_vehicle 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_truck DEFINITION

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

PUBLIC SECTION. "------------------METHODS:

constructor IMPORTING im_make TYPE string im_cargo TYPE ty_cargo.

METHODS

display_attributes REDEFINITION.

METHODS

get_cargo RETURNING value(re_cargo) TYPE ty_cargo.

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

ENDCLASS.

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

CLASS lcl_truck IMPLEMENTATION

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

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

"constructor

METHOD display_attributes. WRITE: / icon_ws_truck AS ICON. super->display_attributes( ). WRITE: 20 ’ Cargo = ’, max_cargo. ULINE. ENDMETHOD.

"display_attributes

METHOD get_cargo. re_cargo = max_cargo. ENDMETHOD.

"get_cargo

Continued on next page

250

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

ENDCLASS.

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

CLASS lcl_bus DEFINITION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle. PUBLIC SECTION. "------------------METHODS:

constructor IMPORTING im_make TYPE string im_passengers TYPE i.

METHODS

display_attributes REDEFINITION.

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

ENDCLASS.

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

CLASS lcl_bus IMPLEMENTATION

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

METHOD constructor. super->constructor( im_make ). max_passengers = im_passengers. "constructor

ENDMETHOD.

METHOD display_attributes. WRITE: / icon_transportation_mode AS ICON. super->display_attributes( ). WRITE:

20 ’ Passengers = ’, max_passengers.

ULINE. ENDMETHOD.

"display_attributes

ENDCLASS.

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

CLASS lcl_rental DEFINITION

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

PUBLIC SECTION. "------------------METHODS:

constructor IMPORTING im_name TYPE string.

METHODS

add_vehicle IMPORTING im_vehicle

METHODS

display_attributes.

TYPE REF TO lcl_vehicle.

INTERFACES lif_partners.

PRIVATE SECTION. "------------------DATA: name TYPE string, vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS.

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

CLASS lcl_rental IMPLEMENTATION

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

METHOD constructor. name = im_name. "constructor

ENDMETHOD.

METHOD add_vehicle. APPEND im_vehicle TO vehicle_list. "add_vehicle

ENDMETHOD.

METHOD

display_attributes.

DATA: r_vehicle TYPE REF TO lcl_vehicle. WRITE: / WRITE:

icon_transport_proposal AS ICON, name. ’ Here comes the vehicle list: ’. ULINE. ULINE.

LOOP AT vehicle_list INTO r_vehicle. r_vehicle->display_attributes( ). ENDLOOP. ENDMETHOD.

"display_attributes

Continued on next page

252

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

"lcl_rental IMPLEMENTATION

ENDCLASS.

SAPBC401_INTS_A *&---------------------------------------------------------------------* *&

Include

SAPBC401_INTS_A

*

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

CLASS lcl_airplane DEFINITION

*

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

CLASS lcl_airplane IMPLEMENTATION

*

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

CLASS lcl_cargo_plane DEFINITION

*

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

CLASS lcl_cargo_plane IMPLEMENTATION

*

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

CLASS lcl_passenger_plane DEFINITION

*

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

CLASS lcl_passenger_plane IMPLEMENTATION

*

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

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

CLASS lcl_carrier DEFINITION

*

*---------------------------------------------------------------------* * ... *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

253


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

"---------------------------------------INTERFACES lif_partners. METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string, add_airplane IMPORTING im_plane TYPE REF TO lcl_airplane, display_airplanes, display_attributes. PRIVATE SECTION. "----------------------------------DATA: name

TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS.

"lcl_carrier DEFINITION

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

CLASS lcl_carrier IMPLEMENTATION

*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD lif_partners~display_partner. display_airplanes( ). ENDMETHOD.

"lif_partners~display_partner

METHOD add_airplane. APPEND im_plane TO airplane_list. ENDMETHOD.

"add_airplane

METHOD display_attributes. WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). ENDMETHOD.

"display_attributes

METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane. LOOP AT airplane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP. ENDMETHOD.

"display_airplanes

METHOD constructor. name = im_name. ENDMETHOD.

"constructor

METHOD get_name. ex_name = name.

Continued on next page

254

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

ENDMETHOD.

ENDCLASS.

08-03-2004

"get_name

"lcl_carrier IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

255


Unit 3: Object-Oriented Concepts and Programming Techniques

256

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

241

Lesson: Interfaces and Casting

Exercise 15: Aggregation, Generic Calls, and Polymorphism Exercise Duration: 30 Minutes

Exercise Objectives 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

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Define a local class for travel agencies. 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.

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.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

257


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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.

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.

258

1.

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.

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

Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. (Where ## is your two-digit group number). a) b)

2.

If necessary, add a class LCL_TRAVEL_AGENCY that uses the interface LIF_PARTNERS to your UML diagram. a)

3.

See the source code extract from the model solution

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.

Carry out this step in the usual manner. Additional information is available in the SAP Library.

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.

Speak to your instructor if you have any questions.

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

4.

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_INTS_MAIN_B

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

See the source code extract from the model solution

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

259


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)

2.

Using the reference, generate an instance of your class LCL_TRAVEL_AGENCY. Decide for yourself how to fill the attributes. a)

3.

See the source code extract from the model solution

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

See the source code extract from the model solution

Add the attributes of the travel agency by calling its method DISPLAY_AGENCY_PARTNERS. a)

See the source code extract from the model solution

Result Source code extract:

SAPBC401_INTS_MAIN_B REPORT

sapbc401_ints_main_b.

TYPES ty_fuel TYPE p DECIMALS 2. TYPES ty_cargo TYPE p DECIMALS 2. TYPE-POOLS icon. INCLUDE sapbc401_vehd_g. INCLUDE sapbc401_ints_a. DATA: r_plane TYPE REF TO lcl_airplane, r_cargo TYPE REF TO lcl_cargo_plane, r_passenger TYPE REF TO lcl_passenger_plane, r_carrier TYPE REF TO lcl_carrier, r_agency TYPE REF TO lcl_travel_agency, r_rental TYPE REF TO lcl_rental,

Continued on next page

260

© 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 ************************************** CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’.

***** Create CARRIER ******************************************** CREATE OBJECT r_carrier EXPORTING im_name = ’Smile&Fly Travel’.

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

******* create RENTAL ***************************************** CREATE OBJECT r_rental EXPORTING im_name = ’HAPPY CAR RENTAL’. ... ***** insert business-parnter of agency into partner_list*********** r_agency->add_partner( r_rental ).

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

SAPBC401_VEHD_G *---------------------------------------------------------------------* * define client lcl_travel_agency * it will use the interface lif_partners *---------------------------------------------------------------------* INTERFACE lif_partners. METHODS display_partner. ENDINTERFACE.

"lif_partners

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

CLASS lcl_rental DEFINITION

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

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

261


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

*---------------------------------------------------------------------* CLASS lcl_rental DEFINITION. PUBLIC SECTION. "------------------METHODS:

constructor IMPORTING im_name TYPE string.

METHODS

add_vehicle IMPORTING im_vehicle TYPE REF TO lcl_vehicle.

METHODS

display_attributes.

INTERFACES: lif_partners. PRIVATE SECTION. "------------------DATA: name TYPE string, vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS.

"lcl_rental DEFINITION

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

CLASS lcl_rental IMPLEMENTATION

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

CLASS lcl_travel_agency DEFINITION

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

PUBLIC SECTION. "------------------METHODS:

constructor IMPORTING im_name TYPE string.

METHODS

add_partner IMPORTING im_partner

METHODS

display_agency_partners.

TYPE REF TO lif_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

262

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Interfaces and Casting

*---------------------------------------------------------------------* CLASS lcl_travel_agency IMPLEMENTATION. METHOD display_agency_partners. DATA: r_partner TYPE REF TO lif_partners. WRITE: icon_dependents AS ICON, name. WRITE:

’ Here are the partners of the travel agency: ’.

ULINE. ULINE. LOOP AT partner_list INTO r_partner. r_partner->display_partner( ). ENDLOOP. ENDMETHOD. METHOD

"display_agency_partners

constructor.

name = im_name. ENDMETHOD.

METHOD

"constructor

add_partner.

APPEND im_partner TO partner_list.

08-03-2004

ENDMETHOD.

"add_partner

ENDCLASS.

"lcl_travel_agency IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

263


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Lesson Summary 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

Related Information ... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.

264

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: 249

Lesson: Events

Events Lesson Duration: 105 Minutes

Lesson Overview 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: • • • •

Define and trigger events Handle events Register and deregister event handling Explain the key differences between explicit method calls and event-controlled method calls Caution: This application example does not mention specifically that the events are defined in superclasses or interfaces.

Therefore, before you look at the first graphic about the event concept, you could also start the course by turning the approach around and having the participants discuss which class should do the defining and triggering and which one should do the handling. Assuming that the participants have understood the inheritance concept, they should understand these ideas by themselves. The same applies for the optional exercise in which participants define the event in the interface.

Business Example You want to implement event-controlled behavior from your model in ABAP Objects.

Event-Controlled Method Calls 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

265


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Figure 126: Event-Controlled Method Calls

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

266

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Events

Figure 127: Event Handling in a UML Class Diagram

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 The following summarizes all of the required programming steps for event-controlling. They will be explained in more detail later.

Figure 128: Triggering and Handling Events – Overview

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

267


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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

268

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Events

Figure 130: Handling Events – Syntax

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). 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. Therefore, handler methods are usually called by triggered events (RAISE EVENT): However, they can be called explicitly as well (CALL METHOD).

Registering for Events 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. 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

269


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

The most common mistake regarding event-controlling is forgetting the registration. Be sure to explain why the registration is so important. One way to illustrate this would be to execute your demonstration program without the registration, so that you can show that the registration is a necessary step.

Figure 131: Registering Event Handling

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

270

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Events

Figure 132: Registering Event Handling – Syntax

Events are registered using the SET HANDLER statement. Registration is only active at program runtime. 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. The addition ACTIVATION ’X’ is optional. To revoke the registration, use ACTIVATION space. 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 ... .

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

271


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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.

Figure 133: Registration/Deregistration – Handler Tables

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. Objects that are registered for event handling are not deleted by the Garbage Collector if there are no remaining references to them. Your demonstration program should now resemble the executable program SAPBC401_VEHICLE_MAIN_L. You should run your program in debugging mode.

272

© 2004 SAP AG. All rights reserved.

08-03-2004


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. PUBLIC All PROTECTED Can only be handled by users within that class or its subclasses

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. PUBLIC Anywhere in the program PROTECTED Can be handled by users within that class or its subclasses PRIVATE Can only be handled within its class

Event handler methods can only have the same visibility or more restricted visibility than the events they refer to. Our experience shows that some participants are worried when they finish this lesson, as they feel that event-controlling makes it difficult to follow the program flow by looking at the source code. If these queries are voiced, repeat the characteristics of the event concept and its advantages from the beginning of the lesson. Then point out the significance of modeling and the diagrams.

08-03-2004

© 2004 SAP AG. All rights reserved.

273


Unit 3: Object-Oriented Concepts and Programming Techniques

274

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

259

Lesson: Events

Exercise 16: Events in Superclasses Exercise Duration: 30 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Define and trigger events • Handle events • Register event handling

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

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

3.

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.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

275


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

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.

6.

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.

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

276

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.

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

Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_INTS_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_EVES_MAIN_A

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

3.

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. If applicable, illustrate the relationships in your UML diagram. a)

4.

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)

6.

Speak to your instructor if you have any questions.

See the source code extract from the model solution

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)

See the source code extract from the model solution Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

277


Unit 3: Object-Oriented Concepts and Programming Techniques

7.

BC401

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.

Task 2: 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)

2.

See the source code extract from the model solution

Define the event VEHICLE_CREATED and proceed as you did in the previous exercise. a) b)

Speak to your instructor if you have any questions. See the source code extract from the model solution

Result Source code extract:

SAPBC401_EVES_MAIN_A REPORT

sapbc401_eves_main_a.

TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2. TYPE-POOLS icon.

INCLUDE sapbc401_vehd_h. INCLUDE sapbc401_eves_a.

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

TYPE REF TO lcl_bus,

r_passenger TYPE REF TO lcl_passenger_plane, r_cargo TYPE REF TO lcl_cargo_plane, r_carrier TYPE REF TO lcl_carrier, r_rental TYPE REF TO lcl_rental, r_agency TYPE REF TO lcl_travel_agency.

Continued on next page

278

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Events

START-OF-SELECTION. *######################## ***** Create TRAVEL_AGENCY ************************************** CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’.

***** Create CARRIER ******************************************** CREATE OBJECT r_carrier EXPORTING im_name = ’Smile&Fly Travel’. ***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US Hercules’ im_planetype = ’747-500’ im_cargo = 533. ***** insert business-parnter of agency into partner_list*********** r_agency->add_partner( r_carrier ).

******* create RENTAL ***************************************** CREATE OBJECT r_rental EXPORTING im_name = ’HAPPY CAR RENTAL’. ******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = ’MAN’ im_cargo = 45.

******* 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. ***** insert business-parnter of agency into partner_list*********** r_agency->add_partner( r_rental ). ******* show attributes of all partners of travel_agency ****** r_agency->display_agency_partners( ).

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

279


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

SAPBC401_VEHD_H *&---------------------------------------------------------------------* *&

Include

SAPBC401_VEHD_H

*

*&---------------------------------------------------------------------* *---------------------------------------------------------------------* * define client lcl_travel_agency * it will use the interface lif_partners *---------------------------------------------------------------------* INTERFACE lif_partners. METHODS display_partner. ENDINTERFACE.

"lif_partners

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

CLASS lcl_vehicle DEFINITION

*---------------------------------------------------------------------* CLASS lcl_vehicle DEFINITION.

PUBLIC SECTION. "------------------METHODS: get_average_fuel IMPORTING im_distance TYPE s_distance im_fuel TYPE ty_fuel RETURNING value(re_avgfuel) TYPE ty_fuel. METHODS

constructor IMPORTING im_make TYPE string.

METHODS

display_attributes.

METHODS

set_make IMPORTING im_make TYPE string.

METHODS

get_make EXPORTING ex_make TYPE string.

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

TYPE string.

METHODS

init_make.

CLASS-DATA:

n_o_vehicles TYPE i.

ENDCLASS.

"lcl_vehicle DEFINITION

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

CLASS lcl_vehicle IMPLEMENTATION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_vehicle IMPLEMENTATION. METHOD get_average_fuel.

Continued on next page

280

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Events

re_avgfuel = im_distance / im_fuel. ENDMETHOD.

"get_average_fuel

METHOD constructor. make = im_make. ADD 1 TO n_o_vehicles. RAISE EVENT vehicle_created. ENDMETHOD.

"constructor

METHOD set_make. IF im_make IS INITIAL. init_make( ).

" me->init_make( ). also possible

ELSE. make = im_make. ENDIF. ENDMETHOD.

"set_make

METHOD init_make. make = ’default make’. ENDMETHOD.

"init_make

METHOD get_make. ex_make = make. ENDMETHOD.

"get_make

METHOD display_attributes. WRITE: make. ENDMETHOD.

"display_attributes

METHOD get_count. re_count = n_o_vehicles. ENDMETHOD. ENDCLASS.

"get_count "lcl_vehicle IMPLEMENTATION

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

CLASS lcl_truck DEFINITION

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

CLASS lcl_bus DEFINITION

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

281


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 FOR EVENT vehicle_created OF lcl_vehicle

METHODS

display_attributes.

IMPORTING sender.

INTERFACES: lif_partners. PRIVATE SECTION. "------------------DATA: name TYPE string, vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS.

"lcl_rental DEFINITION

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

CLASS lcl_rental IMPLEMENTATION

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

METHOD

"lif_partners~display_partner

constructor.

name = im_name. SET HANDLER add_vehicle FOR ALL INSTANCES. ENDMETHOD. METHOD

"constructor

add_vehicle.

APPEND sender TO vehicle_list. ENDMETHOD.

METHOD

"add_vehicle

display_attributes.

Continued on next page

282

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Events

DATA: r_vehicle TYPE REF TO lcl_vehicle. WRITE: / WRITE:

icon_transport_proposal AS ICON, name. ’ Here comes the vehicle list: ’. ULINE. ULINE.

LOOP AT vehicle_list INTO r_vehicle. r_vehicle->display_attributes( ). ENDLOOP. ENDMETHOD.

"display_attributes

ENDCLASS.

"lcl_rental IMPLEMENTATION

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

CLASS lcl_travel_agency DEFINITION

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

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

Include

SAPBC401_EVES_A

*

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

CLASS lcl_airplane DEFINITION

*

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

METHODS: constructor IMPORTING im_name

TYPE string

im_planetype TYPE saplane-planetype, display_attributes. CLASS-METHODS: display_n_o_airplanes. EVENTS airplane_created.

PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes IMPORTING im_type

TYPE saplane-planetype

EXPORTING ex_weight

TYPE s_plan_wei

ex_tankcap

TYPE s_capacity.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

283


Unit 3: Object-Oriented Concepts and Programming Techniques

DATA: name

BC401

TYPE string,

planetype TYPE saplane-planetype. CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS.

"lcl_airplane DEFINITION

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

CLASS lcl_airplane IMPLEMENTATION

*

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. METHOD constructor. name

= im_name.

planetype

= im_planetype.

n_o_airplanes = n_o_airplanes + 1. RAISE EVENT airplane_created. ENDMETHOD.

"constructor

METHOD display_attributes. DATA: weight TYPE saplane-weight, cap TYPE saplane-tankcap. WRITE: / icon_ws_plane AS ICON, / ’Name of Airplane:’(001), AT pos_1 name, / ’Type of airplane: ’(002), AT pos_1 planetype. get_technical_attributes( EXPORTING im_type = planetype IMPORTING ex_weight = weight ex_tankcap = cap ). WRITE: / ’Gewicht:’(003), weight, ’Tankkap:’(004), cap. ENDMETHOD.

"display_attributes

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

"display_n_o_airplanes

METHOD get_technical_attributes. SELECT SINGLE weight tankcap FROM saplane INTO (ex_weight, ex_tankcap) WHERE planetype = im_type. IF sy-subrc <> 0. ex_weight = 100000. ex_tankcap = 10000.

Continued on next page

284

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Events

ENDIF.

ENDMETHOD.

"get_technical_attributes

ENDCLASS.

"lcl_airplane IMPLEMENTATION

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

CLASS lcl_cargo_plane DEFINITION

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

CLASS lcl_passenger_plane DEFINITION

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

CLASS lcl_carrier DEFINITION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION. "---------------------------------------INTERFACES lif_partners. METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string, add_airplane FOR EVENT airplane_created OF lcl_airplane IMPORTING sender, display_airplanes, display_attributes. PRIVATE SECTION. "----------------------------------DATA: name

TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS.

"lcl_carrier DEFINITION

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

CLASS lcl_carrier IMPLEMENTATION

*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD lif_partners~display_partner.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

285


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

display_airplanes( ). ENDMETHOD.

"lif_partners~display_partner

METHOD add_airplane. APPEND sender TO airplane_list. ENDMETHOD.

"add_airplane

METHOD display_attributes. WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). ENDMETHOD.

"display_attributes

METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane. LOOP AT airplane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP. ENDMETHOD.

"display_airplanes

METHOD constructor. SET HANDLER add_airplane FOR ALL INSTANCES. name = im_name. ENDMETHOD.

"constructor

METHOD get_name. ex_name = name. ENDMETHOD. ENDCLASS.

286

"get_name "lcl_carrier IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

271

Lesson: Events

Exercise 17: Events in Interfaces (optional) Exercise Duration: 30 Minutes

Exercise Objectives 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

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

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

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. Note: The entry of a business partner reference into the travel agent’s list is to be event-controlled.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

287


Unit 3: Object-Oriented Concepts and Programming Techniques

3.

BC401

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

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

7.

288

Observe the execution of the program in the ABAP Debugger.

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

Complete your ZBC401_##_MAIN program or copy the sample solution from the previous exercise. (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_EVES_MAIN_B

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)

3.

See the source code extract from the model solution

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? If applicable, illustrate the relationships in your UML diagram. a)

4.

Define the event PARTNER_CREATED and trigger it using a suitable method in the class that you selected. a)

5.

Speak to your instructor if you have any questions.

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


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)

7.

See the source code extract from the model solution

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.

Result Source code extract:

SAPBC401_EVES_MAIN_B REPORT

sapbc401_eves_main_b.

TYPES: ty_fuel TYPE p DECIMALS 2, ty_cargo TYPE p DECIMALS 2. TYPE-POOLS icon. INCLUDE sapbc401_vehd_i. INCLUDE sapbc401_eves_b.

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

TYPE REF TO lcl_bus,

r_passenger TYPE REF TO lcl_passenger_plane, r_cargo TYPE REF TO lcl_cargo_plane, r_carrier TYPE REF TO lcl_carrier, r_rental TYPE REF TO lcl_rental, r_agency TYPE REF TO lcl_travel_agency.

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

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

Continued on next page

290

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Events

******* 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. ******* create truck ***************************************** CREATE OBJECT r_bus EXPORTING im_make = ’Mercedes’ im_passengers = 80.

******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = ’VOLVO’ im_cargo = 48. ***** Create CARRIER ******************************************** CREATE OBJECT r_carrier EXPORTING im_name = ’Smile&Fly Travel’. ***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US Hercules’ im_planetype = ’747-500’ im_cargo = 533.

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

SAPBC401_VEHD_I *&---------------------------------------------------------------------* *&

Include

SAPBC401_VEHD_I

*

*&---------------------------------------------------------------------* *---------------------------------------------------------------------* * define client lcl_travel_agency * it will use the interface lif_partners *---------------------------------------------------------------------* INTERFACE lif_partners. METHODS display_partner. EVENTS: partner_created. ENDINTERFACE.

"lif_partners

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

291


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 for event vehicle_created of lcl_vehicle

METHODS

display_attributes.

importing sender. INTERFACES: lif_partners. PRIVATE SECTION. "------------------DATA: name TYPE string, vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS.

"lcl_rental DEFINITION

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

CLASS lcl_rental IMPLEMENTATION

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

METHOD

"lif_partners~display_partner

constructor.

name = im_name. SET HANDLER add_vehicle FOR ALL INSTANCES. RAISE EVENT lif_partners~partner_created. ENDMETHOD.

METHOD

"constructor

add_vehicle.

APPEND sender TO vehicle_list. ENDMETHOD. METHOD

"add_vehicle

display_attributes.

DATA: r_vehicle TYPE REF TO lcl_vehicle. skip 2.

Continued on next page

292

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Events

WRITE: / WRITE:

icon_transport_proposal AS ICON, name. ’ Here comes the vehicle list: ’. ULINE. ULINE.

LOOP AT vehicle_list INTO r_vehicle. r_vehicle->display_attributes( ). ENDLOOP. ENDMETHOD.

"display_attributes

ENDCLASS.

"lcl_rental IMPLEMENTATION

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

CLASS lcl_travel_agency DEFINITION

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

PUBLIC SECTION. "------------------METHODS:

constructor IMPORTING im_name TYPE string.

METHODS

add_partner FOR EVENT partner_created OF lif_partners IMPORTING sender.

METHODS

display_agency_partners.

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

"lcl_travel_agency DEFINITION

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

CLASS lcl_travel_agency IMPLEMENTATION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_travel_agency IMPLEMENTATION. METHOD display_agency_partners. DATA: r_partner TYPE REF TO lif_partners. WRITE: icon_dependents AS ICON, name. WRITE:

’ Here are the partners of the travel agency: ’.ULINE.ULINE.

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

METHOD

"display_agency_partners

constructor.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

293


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

name = im_name. SET HANDLER add_partner FOR ALL INSTANCES. ENDMETHOD. METHOD

"constructor

add_partner.

APPEND sender TO partner_list. ENDMETHOD.

"add_partner

ENDCLASS.

"lcl_travel_agency IMPLEMENTATION

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

Include

SAPBC401_EVES_B

*

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

CLASS lcl_carrier DEFINITION

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

PUBLIC SECTION. "---------------------------------------INTERFACES lif_partners. METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string, add_airplane FOR EVENT airplane_created OF lcl_airplane IMPORTING sender, display_airplanes, display_attributes. PRIVATE SECTION. "----------------------------------DATA: name

TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS.

"lcl_carrier DEFINITION

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

CLASS lcl_carrier IMPLEMENTATION

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

"lif_partners~display_partner

Continued on next page

294

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Events

METHOD add_airplane. APPEND sender TO airplane_list. ENDMETHOD.

"add_airplane

METHOD display_attributes. SKIP 2. WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). ENDMETHOD.

"display_attributes

METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane. LOOP AT airplane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP. ENDMETHOD.

"display_airplanes

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

"constructor

METHOD get_name. ex_name = name. ENDMETHOD. ENDCLASS.

08-03-2004

"get_name "lcl_carrier IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

295


Unit 3: Object-Oriented Concepts and Programming Techniques

BC401

Lesson Summary 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

Related Information ... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.

296

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Unit Summary

Unit Summary 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

08-03-2004

© 2004 SAP AG. All rights reserved.

297


Unit Summary

298

BC401

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

283

Test Your Knowledge 1.

What is the ABAP syntax required to make a local subclass inherit from a superclass?

2.

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? Choose the correct answer(s).

□ □ □ □ 4.

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

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

□ □ □ □ 5.

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

For what purpose do you use inheritance?

© 2004 SAP AG. All rights reserved.

299


Test Your Knowledge

BC401

6.

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? Choose the correct answer(s).

8.

□ □

A B

□ □

C D

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

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

9.

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

What is the statement for defining events?

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

10. What is the statement for triggering events?

11. With which statement would you define a handler method M_H for event E of class C?

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?

14. Can events be triggered in interfaces?

08-03-2004

© 2004 SAP AG. All rights reserved.

301


Test Your Knowledge

286

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 Refer to the relevant section of the lesson.

2.

What is the ABAP syntax required to redefine an inherited method in a local class? Answer: Using the REDEFINITION addition to the METHODS statement Refer to the relevant section of the lesson.

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? Answer: A, C Refer to the relevant section of the lesson.

4.

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 Refer to the relevant section of the lesson.

5.

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.

6.

Does an interface have an implementation part? Answer: No Refer to the relevant section of the lesson.

302

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

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? Answer: A Refer to the relevant section of the lesson.

8.

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 Refer to the relevant section of the lesson.

9.

What is the statement for defining events? Answer: EVENTS Refer to the relevant section of the lesson.

10. What is the statement for triggering events? 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. 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

303


Test Your Knowledge

BC401

13. Can events be defined in interfaces? Answer: Yes Refer to the relevant section of the lesson. 14. Can events be triggered in interfaces? Answer: No Refer to the relevant section of the lesson.

304

© 2004 SAP AG. All rights reserved.

08-03-2004


Unit 4 289

Object-Oriented Repository Objects This unit represents something of a break in the course flow. Use it to your advantage. Participants should be freshly motivated by being familiarized with the new tools and being able to employ their recently acquired knowledge and the resulting change in method. Caution: With regards to content, the second lesson would be better suited to the previous unit. However, we deliberately chose this alternative sequence so that (amongst other things) the singleton demonstration can be carried out directly in the Class Builder. The optional exercises also assume that the participants are able to use the Class Builder. This also allows for a natural transition to the Persistence Services, which are also realized using generated global classes and interfaces. Do not neglect the third lesson. Even if not all useful components of the Transaction Services are available yet, the persistence mapping possibilities are limited, or the participants find it irrelevant, the ABAP Workbench still provides a powerful tool.

Unit Overview 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. 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. The third lesson is about possibilities for generating very specific global classes. In turn, this generation tool uses the Class Builder.

08-03-2004

© 2004 SAP AG. All rights reserved.

305


Unit 4: Object-Oriented Repository Objects

BC401

Unit Objectives After completing this unit, you will 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

Unit Contents Lesson: Global Classes and Interfaces ......................................307 Procedure: Importing Local Classes and Interfaces ...................316 Procedure: Moving the Method Definition of a Global Class to an Implemented Interface .....................................................324 Demonstration: Moving a Method Definition to an Interface..........324 Procedure: Creating an Object-Oriented Transaction .................332 Demonstration: Creating an OO Transaction ...........................332 Exercise 18: Global Classes ..............................................335 Exercise 19: Global Interfaces............................................339 Exercise 20: Refactoring Assistant.......................................349 Lesson: Special Object-Oriented Programming Techniques..............354 Exercise 21: Singleton Classes (Optional) ..............................361 Exercise 22: Friendship Relationships (optional) ......................365 Lesson: Persistent Objects in ABAP Objects for SAP Web Application Server 6.20 ......................................................................371 Procedure: Creating Persistent Classes ................................375 Demonstration: Reading and Writing Objects ..........................375

306

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: 291

Lesson: Global Classes and Interfaces

Global Classes and Interfaces Lesson Duration: 150 Minutes

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. We will demonstrate the use of global standard classes using the powerful example of the SAP Grid Control.

Lesson Objectives After completing this lesson, you will 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)

The participants will not learn any new programming skills in this lesson. This lesson only serves to introduce new types of Repository objects and the associated tools. Once again, you should highlight the strengths of the ABAP Workbench development environment, particularly in comparison to working with other programming languages. For example, a context-sensitive editor does not necessarily offer a performant, cross-platform, upwardly compatible, actively integrated, and business-oriented application language.

Business Example Develop your classes and interfaces as actively integrated Repository objects.

08-03-2004

© 2004 SAP AG. All rights reserved.

307


Unit 4: Object-Oriented Repository Objects

BC401

Creating Global Classes and Interfaces 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. In both cases, whether or not the source text is stored separately in include programs is irrelevant. 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. Be sure to explain the correct use of the Class Builder slowly and in detail. In addition to the presentation, you should show all of the steps in a separate demonstration class.

Figure 134: Creating Global Classes in the Object Navigator

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

308

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

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

Figure 135: Definition of Attributes

Choose the Attributes tab to open the list of all attribute definitions in the class. You can define new attributes here. You can use the input help when you are defining the type attributes. Remember to use meaningful short descriptions.

08-03-2004

© 2004 SAP AG. All rights reserved.

309


Unit 4: Object-Oriented Repository Objects

BC401

Figure 136: Definition of Methods

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. 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. Hint: Methods can be transported separately.

We suggest only including the interface in your demonstration class after the first exercise is complete.

310

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

Figure 137: Including Global Classes

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. We suggest only including the interface in your demonstration class after the first exercise is complete.

08-03-2004

© 2004 SAP AG. All rights reserved.

311


Unit 4: Object-Oriented Repository Objects

BC401

Figure 138: Definition of Method Signatures

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. You can use the input help when defining the attributes. Remember to use meaningful short descriptions. You can scroll between the signatures using the Previous Method and Next Method buttons. Choose the Methods button to return to the method list.

Figure 139: Implementation of Methods

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.

312

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

You can display the method’s signature by choosing the relevant button.

Figure 140: Displaying the Method Definition

Choose Goto → Method definition if you want to change the attributes of your method during the implementation.

Figure 141: Definition of Components Using the Navigation Area

08-03-2004

© 2004 SAP AG. All rights reserved.

313


Unit 4: Object-Oriented Repository Objects

BC401

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. Hint: Print selected portions of the source text using Class → Print or Method → Print.

Remind participants of the importance of documentation. They should document every class individually as well as the class as a whole.

Figure 142: The Class Builder Testing Environment

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. You can test the triggering of events in a class as follows: 1. 2. 3.

314

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.

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

The event that was triggered and all of the exported actual parameters are displayed in a list. At this point, we recommend having the participants do the first exercise.

Demonstrate the following procedure in the system, because the menu path is not easy to find and the correct usage of the next screen is also not self-explanatory. This is a good opportunity to create a global interface for the business partners. You will also need it later when you add global classes to your demonstration program.

08-03-2004

© 2004 SAP AG. All rights reserved.

315


Unit 4: Object-Oriented Repository Objects

298

BC401

Importing Local Classes and Interfaces Use The procedure is an easy way to make global copies of local classes and local interfaces. Caution: This function cannot be used from within the Object Navigator.

Procedure 1.

In the SAP Easy Access Menu, choose Tools → ABAP Workbench → Development → Class Builder or call the transaction SE24.

2.

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.

Figure 143: Importing a Local Program Class

316

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

Other Functions of the Class Builder You set out the inheritance relationships between global classes in the Properties tab.

Figure 144: Defining an Inheritance Relationship

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

317


Unit 4: Object-Oriented Repository Objects

BC401

Figure 145: Redefining an Inherited Method

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.

Figure 146: Defining a Local Type

You can define local types in global classes. This includes local classes in particular. Technically, you are not defining a class within a class, but a class that is local in the Repository object of the global class.

318

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

All components of the global class have access to these local types, but they are encapsulated to the outside. The same applies for local interfaces in global classes. To edit the implementation parts of these local classes, choose the Impl. button. (Local Class Implementations).

Figure 147: Structured Display of Inherited Components

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

319


Unit 4: Object-Oriented Repository Objects

BC401

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.

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. Be sure to demonstrate the following editing possibilities, ideally using the global demonstration class that you just created. Show both possibilities: Drag&Drop and the Pattern button.

320

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

Figure 149: Separating the Navigation and Editing Areas of the Object Navigator.

This way, the previously discussed advantages also apply to working with global classes and interfaces.

Figure 150: Object Instantiation Using Drag&Drop

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

321


Unit 4: Object-Oriented Repository Objects

BC401

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.

Figure 151: Method Calls Using Drag&Drop

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. 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. Optionally, you can prepare the participants for the next exercise by including the global interface in the global class and adapting the demonstration program to use the global interface. This step may not be necessary for more able groups of participants.

At this point, we recommend having the participants do the second exercise. Again, this should show the participants how easy it is to extend object-oriented software applications if they were modeled well. Try to capitalize on this motivational effect.

322

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

The Refactoring Assistant 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. Working with the tool is simple, since it is based on Drag&Drop dialogs.

Figure 152: Working with the Refactoring Assistant

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

08-03-2004

© 2004 SAP AG. All rights reserved.

323


Unit 4: Object-Oriented Repository Objects

306

BC401

Moving the Method Definition of a Global Class to an Implemented Interface 1.

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.

Demonstration: Moving a Method Definition to an Interface Purpose This section demonstrates the correct use of the Refactoring Assistant. This is also a good time to point out the easy connection to the SAP Library.

System Data System: will be assigned Client: will be assigned User ID: will be assigned Password: will be assigned Set up instructions: None significant when using a standard SAP Web AS 6.20 training system 1. Either copy the global class CL_BC401_BOOT_CALL_METHOD and global interface IF_BC401_BOOT_EMPTY or create your own equivalent objects. 2.

Analyze and activate the copy of the interface (which is currently empty). Adapt the copy of the class: Change the interfaces list to include the name of the copy of the interface. Analyze, activate, and test the copy of the class.

324

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

3.

Open the Refactoring Assistant and point out the SAP Library. Move the SEND_MESSAGE method from the class to the interface using Drag&Drop.

4.

Save your work and point out the message texts.

5.

Look at the interface: The method definition has been inserted.

6.

Activate the interface.

7.

Look at the class: The method definition has been adapted. Caution: Adapt the SEND_MESSAGE method in the CALLER method.

8.

Activate and test the class

9.

Sample objects in package BC401: • •

Global class CL_BC401_BOOD_CALL_METHOD Global interface IF_BC401_BOOD_EMPTY

At this point, we recommend having the participants do the third exercise.

Use of SAP Standard Classes – Application Example 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. Be flexible while working on this section: If the participants truly meet all prerequisites of this course, this material is simply revision. If that is the case, consider demonstrating a different application control or adding event handling to the SAP Grid Control. You must emphasize that this is an application example. This is not an introduction to dialog programming with EnjoySAP controls.

08-03-2004

© 2004 SAP AG. All rights reserved.

325


Unit 4: Object-Oriented Repository Objects

BC401

Figure 153: SAP Grid Control

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

326

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

Figure 154: Including an SAP Grid Control Instance in a Dialog Program

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. There are different types of container controls. However, they all encapsulate fundamental control functions, such as scroll bars. 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

327


Unit 4: Object-Oriented Repository Objects

BC401

Figure 155: Displaying Application Data Using an SAP Grid Control Instance

For normal display, the follow programming steps are sufficient: 1. 2. 3. 4.

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

328

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

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. 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. Individual elements of the SAP Control Framework are also covered in other courses. 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.

It may be worth pointing out the relevant SAP course at this point.

OO Transactions as a Transaction Type 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

329


Unit 4: Object-Oriented Repository Objects

BC401

This section is very important for two reasons: 1.

This new transaction type has made it possible to develop purely object-oriented applications, that is, ones that are not associated with procedural framework programs. Caution: Procedural framework programs are still required for screen fields.

2.

Participants need to learn about the object-oriented transaction services before they can understand the flag OO Transaction Model. However, they need to know the OO transaction as a transaction type before they learn this.

Figure 156: Creating an OO Transaction Code

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. Thus, users now have the opportunity to call methods themselves in the usual way (through menu options, command field entries, and so on).

330

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

Caution: Global classes in ABAP Objects cannot contain screen definitions. Thus, when you create a link to a global class, note the following: •

The constructor cannot contain any IMPORTING parameters

ABAP list displays cannot be processed

Caution: Breaking these rules will not cause a syntax error or a message from the Extended Syntax Check. Instead, you will either cause a runtime error, or there will be no display 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.

331


Unit 4: Object-Oriented Repository Objects

311

BC401

Creating an Object-Oriented Transaction 1.

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.

Demonstration: Creating an OO Transaction Purpose Above all, the aim is to clarify the terms transaction, transaction code, program, class, and method. Point out the creation of the instance in particular. The GUID should help you with that.

System Data System: will be assigned Client: will be assigned User ID: will be assigned Password: will be assigned Set up instructions: None significant when using a standard SAP Web AS 6.20 training system 1. Either analyze the class CL_BC401_BOOD_ID in depth or create your own. 2.

Show the class the features of the tool by having them test it.

3.

Create a transaction code. Choose the option Method of a Class (OO Transaction) as an Initial Object.

4.

Leave the OO transaction model flag unchecked. Link either to the DISPLAY_ATTRIBUTES method of the global class CL_BC401_BOOD_ID or to your own method.

5.

332

Save the transaction code.

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

6.

Enter the transaction code in the command field or insert it in a role – for example, in your personal Favorites – and execute the transaction.

7.

Sample objects in package BC401: • •

08-03-2004

Global class CL_BC401_BOOD_ID Transaction code BC401_BOOD

© 2004 SAP AG. All rights reserved.

333


Unit 4: Object-Oriented Repository Objects

334

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

313

Lesson: Global Classes and Interfaces

Exercise 18: Global Classes Exercise Duration: 30 Minutes

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

Business Example Create a global class to represent hotels.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Create a global class for hotels. 1.

Create the global class ZCL_##_HOTEL. (Where ## is your two-digit group number).

2.

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

Maintain the short texts. 3.

Define the following methods in the class:

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

335


Unit 4: Object-Oriented Repository Objects

BC401

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

Maintain the short texts.

Task 2: Check your work.

336

1.

Activate your class.

2.

Test your class in the Class Builder’s testing environment.

© 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). a) b)

Follow the processes as outlined in the relevant section of this lesson. Model solution: CL_HOTEL 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.

2.

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

Maintain the short texts. a) b) 3.

Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.

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.

337


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

Activate your class. a)

2.

Test your class in the Class Builder’s testing environment. a) b)

338

Carry out this step in the usual manner. Additional information is available in the SAP Library.

Follow the processes as outlined in the relevant section of this lesson. Speak to your instructor if you have any questions.

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

317

Lesson: Global Classes and Interfaces

Exercise 19: Global Interfaces Exercise Duration: 30 Minutes

Exercise Objectives 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

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

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.

Create the global interface ZIF_##_PARTNERS. Define the instance method DISPLAY_PARTNER and the instance event PARTNER_CREATED in the interface. Hint: Import the local interface from your program ZBC401_##_MAIN or from the previous lesson’s sample solution SAPBC401_EVES_MAIN_B.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

339


Unit 4: Object-Oriented Repository Objects

BC401

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.

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: Add an instance of your global hotel class to your main program.

340

1.

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.

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

2.

Speak to your instructor if you have any questions.

Create the global interface ZIF_##_PARTNERS. Define the instance method DISPLAY_PARTNER and the instance event PARTNER_CREATED in the interface. Hint: Import the local interface from your program ZBC401_##_MAIN or from the previous lesson’s sample solution SAPBC401_EVES_MAIN_B. a) b) c)

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

341


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

Complete your program ZBC401_##_MAIN program or copy the program SAPBC401_EVES_MAIN_B (where ## is your two-digit group number). a) b)

2.

Remove the definition of the local interface and adapt all places where it was used to suit the new global interface. a)

3.

See the source code extract from the model solution

Define a reference variable, specify your global hotel class as the type, and create an instance. a)

4.

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_CLSS_MAIN_A

See the source code extract from the model solution

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.

Result Source code extract:

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. INCLUDE sapbc401_vehd_j. INCLUDE sapbc401_clss_a.

Continued on next page

342

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

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

TYPE REF TO lcl_bus,

r_passenger TYPE REF TO lcl_passenger_plane, r_cargo TYPE REF TO lcl_cargo_plane, r_carrier TYPE REF TO lcl_carrier, r_rental TYPE REF TO lcl_rental, r_agency TYPE REF TO lcl_travel_agency, r_hotel TYPE REF TO cl_hotel.

START-OF-SELECTION. *######################## ******* create travel_agency ***************************************** CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’.

******* create rental ***************************************** CREATE OBJECT r_rental EXPORTING im_name = ’HAPPY CAR RENTAL’. ******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = ’MAN’ im_cargo = 45. ******* create truck ***************************************** CREATE OBJECT r_bus EXPORTING im_make = ’Mercedes’ im_passengers = 80.

******* create truck ***************************************** CREATE OBJECT r_truck EXPORTING im_make = ’VOLVO’ im_cargo = 48. ***** Create CARRIER ******************************************** CREATE OBJECT r_carrier EXPORTING im_name = ’Smile&Fly Travel’. ***** Passenger Plane ******************************************** CREATE OBJECT r_passenger EXPORTING im_name = ’LH BERLIN’ im_planetype = ’747-400’ im_seats = 345. ***** cargo Plane ************************************************ CREATE OBJECT r_cargo EXPORTING im_name = ’US Hercules’ im_planetype = ’747-500’

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

343


Unit 4: Object-Oriented Repository Objects

BC401

im_cargo = 533.

******* create hotel ***************************************** CREATE OBJECT r_hotel EXPORTING im_name = ’Holiday Inn’ im_beds = 345.

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

SAPBC401_VEHD_J *&---------------------------------------------------------------------* *&

Include

SAPBC401_VEHD_J

*

*&---------------------------------------------------------------------* *---------------------------------------------------------------------* * work with the global interface if_hotel *---------------------------------------------------------------------* *---------------------------------------------------------------------* *

CLASS lcl_vehicle DEFINITION

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

CLASS lcl_truck DEFINITION

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

CLASS lcl_bus DEFINITION

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

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

Continued on next page

344

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

METHODS

display_attributes.

INTERFACES:

if_partners.

PRIVATE SECTION. "------------------DATA: name TYPE string, vehicle_list TYPE TABLE OF REF TO lcl_vehicle. ENDCLASS.

"lcl_rental DEFINITION

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

CLASS lcl_rental IMPLEMENTATION

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

"lif_partners~display_partner

constructor.

name = im_name. SET HANDLER add_vehicle FOR ALL INSTANCES. RAISE EVENT if_partners~partner_created. ENDMETHOD. METHOD

"constructor

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. r_vehicle->display_attributes( ). ENDLOOP. ENDMETHOD.

ENDCLASS.

"display_attributes

"lcl_rental IMPLEMENTATION

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

CLASS lcl_travel_agency DEFINITION

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

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

345


Unit 4: Object-Oriented Repository Objects

BC401

*---------------------------------------------------------------------* CLASS lcl_travel_agency DEFINITION. PUBLIC SECTION. "------------------METHODS:

constructor IMPORTING im_name TYPE string.

METHODS

add_partner FOR EVENT partner_created OF if_partners IMPORTING sender.

METHODS

display_agency_partners.

PRIVATE SECTION. "------------------DATA: name TYPE string, partner_list TYPE TABLE OF REF TO if_partners. ENDCLASS.

"lcl_travel_agency DEFINITION

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

CLASS lcl_travel_agency IMPLEMENTATION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_travel_agency IMPLEMENTATION. METHOD display_agency_partners. DATA: r_partner TYPE REF TO 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.

name = im_name. SET HANDLER add_partner FOR ALL INSTANCES. ENDMETHOD.

METHOD

"constructor

add_partner.

APPEND sender TO partner_list. ENDMETHOD.

"add_partner

ENDCLASS.

"lcl_travel_agency IMPLEMENTATION

SAPBC401_CLSS_A *------------------------------------------------------------------* *

INCLUDE SAPBC401_CLSS_A

Continued on next page

346

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

*------------------------------------------------------------------* * work with interface if_partners * implement and raise events in lcl_carrier *------------------------------------------------------------------* *

CLASS lcl_airplane DEFINITION

*

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

CLASS lcl_cargo_plane DEFINITION

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

CLASS lcl_passenger_plane DEFINITION

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

CLASS lcl_carrier DEFINITION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION. "---------------------------------------INTERFACES if_partners. METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string, add_airplane FOR EVENT airplane_created OF lcl_airplane IMPORTING sender, display_airplanes, display_attributes. PRIVATE SECTION. "----------------------------------DATA: name

TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS.

"lcl_carrier DEFINITION

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

CLASS lcl_carrier IMPLEMENTATION

*---------------------------------------------------------------------* CLASS lcl_carrier IMPLEMENTATION. METHOD if_partners~display_partner. display_attributes( ).

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

347


Unit 4: Object-Oriented Repository Objects

ENDMETHOD.

BC401

"lif_partners~display_partner

METHOD add_airplane. APPEND sender TO airplane_list. ENDMETHOD.

"add_airplane

METHOD display_attributes. SKIP 2. WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). ENDMETHOD.

"display_attributes

METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane. LOOP AT airplane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP. ENDMETHOD.

"display_airplanes

METHOD constructor. name = im_name. SET HANDLER add_airplane FOR ALL INSTANCES. RAISE EVENT if_partners~partner_created. ENDMETHOD.

"constructor

METHOD get_name. ex_name = name. ENDMETHOD. ENDCLASS.

348

"get_name "lcl_carrier IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

327

Lesson: Global Classes and Interfaces

Exercise 20: Refactoring Assistant Exercise Duration: 15 Minutes

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

Business Example Include your global hotel class in a class hierarchy.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

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

2.

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.

Task 2: Move the general components of the ZCL_##_HOTEL class to the superclass. 1.

Use the Refactoring Assistant to move the NAME attribute, the instance constructor, and the DISPLAY_ATTRIBUTES method into the class ZCL_##_HOUSE. Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

349


Unit 4: Object-Oriented Repository Objects

BC401

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.

6.

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.

350

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

2.

Create the global class ZCL_##_HOTEL and leave it empty. a) b) c)

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

Define an inheritance relationship to make ZCL_##_HOUSE the superclass and ZCL_##_HOTEL the subclass. 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: Move the general components of the ZCL_##_HOTEL class to the superclass. 1.

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.

351


Unit 4: Object-Oriented Repository Objects

3.

Adapt the implementation of the DISPLAY_ATTRIBUTES method in the superclass. a) b)

4.

b)

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)

5.

BC401

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

352

Carry out this step in the usual manner. Additional information is available in the SAP Library.

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Global Classes and Interfaces

Lesson Summary 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 ... about this topic is available in the SAP Library.

08-03-2004

© 2004 SAP AG. All rights reserved.

353


Unit 4: Object-Oriented Repository Objects

Lesson: 331

BC401

Special Object-Oriented Programming Techniques Lesson Duration: 90 Minutes

Lesson Overview 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: • • • • • •

Define abstract classes Define abstract methods Define final classes Define final methods Limit the visibility of the constructor Define friend relationships between classes

The first two sections are mostly intended to complete the participants’ understanding of ABAP Objects. Go into more depth towards the end of this lesson.

Business Example You want to add special object-oriented programming techniques to your ABAP Objects implementations.

Abstract Classes and Abstract Methods 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. 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.

354

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Special Object-Oriented Programming Techniques

We do not suggest doing a system demonstration at this point.

Figure 157: Abstract Classes and Abstract Methods

References to such abstract classes can therefore be used for polymorphic access to subclass instances. Static methods cannot be abstract because they cannot be redefined.

Final Classes and Methods You can prevent a class from being inherited by using the FINAL addition with the CLASS statement. You can prevent a method from being redefined by using the FINAL addition with the METHODS statement. Note: You will find the relevant flag in the Class Builder, under the Properties tab for that class or method.

This once, we do not suggest doing a system demonstration at this point.

08-03-2004

© 2004 SAP AG. All rights reserved.

355


Unit 4: Object-Oriented Repository Objects

BC401

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. Classes that are abstract and final should only contain static components.

Visibility of the Instance Constructor You can limit the instantiability of a class by using the CREATE addition with the CLASS statement. Note: The relevant flag is in the Class Builder, in the Properties tab for the relevant class.

Figure 159: Implicit Setting of the Instance Constructor’s Visibility

356

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Special Object-Oriented Programming Techniques

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. Note: Regardless of that, the instance constructor must always be defined syntactically in the public section.

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

Figure 160: Definition of Friendship Relationships

08-03-2004

© 2004 SAP AG. All rights reserved.

357


Unit 4: Object-Oriented Repository Objects

BC401

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. Conversely, granting friendship is not inherited. A friend of a superclass is therefore not automatically a friend of its subclasses.

Figure 161: Areas of Use for Friendship Relationships

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.

Classes Without Multiple Instantiation 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: Be sure to demonstrate this concept in the system, because it is a basic programming pattern for all standard object-oriented programming languages. You could use the first (optional) exercise for this purpose, thereby having the participants take part in the demonstration.

358

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Special Object-Oriented Programming Techniques

Figure 162: Singleton Classes

The class is defined with the additions FINAL and CREATE PRIVATE and is instantiated using its static constructor. A public static component could then make the reference to the class available to an external user.

08-03-2004

© 2004 SAP AG. All rights reserved.

359


Unit 4: Object-Oriented Repository Objects

360

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

337

Lesson: Special Object-Oriented Programming Techniques

Exercise 21: Singleton Classes (Optional) Exercise Duration: 15 Minutes

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 • Define singleton classes • Instantiate singleton classes

Business Example You need a class that can be instantiated no more than once per program context.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Create a singleton class. 1.

Create the global class ZCL_##_SINGLETON. (Where ## is your two-digit group number). When doing so, specify the necessary attributes for the singleton class.

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.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

361


Unit 4: Object-Oriented Repository Objects

BC401

Task 2: Create a singleton instance.

362

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.

08-03-2004


BC401

Lesson: Special Object-Oriented Programming Techniques

Solution 21: Singleton Classes (Optional) Task 1: Create a singleton class. 1.

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)

2.

Define the attribute R_SINGLETON for a reference to the singleton instance, making sure that the attribute has a suitable type. a)

3.

Use the relevant sections of the lesson as a guide.

Define and implement the method GET_SINGLETON. It will provide the reference to the singleton instance. a)

4.

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.

Use the relevant sections of the lesson as a guide.

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

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

08-03-2004

© 2004 SAP AG. All rights reserved.

363


Unit 4: Object-Oriented Repository Objects

3.

BC401

Create the singleton instance. a)

See the source code extract from the model solution

Result Source code extract:

SAPBC401_SPCS_MAIN_A REPORT sapbc401_spcs_main_a.

DATA: r_single TYPE REF TO cl_singleton.

START-OF-SELECTION. *######################## r_single = cl_singleton=>get_singleton( ).

364

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

341

Lesson: Special Object-Oriented Programming Techniques

Exercise 22: Friendship Relationships (optional) Exercise Duration: 45 Minutes

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 • Define friendship relationships • Access private attributes of a friendship-granting class

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.

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Buffer the flight data in a singleton class. 1.

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). Hint: You can use the global table kind TY_CONNECTIONS.

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.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

365


Unit 4: Object-Oriented Repository Objects

BC401

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.

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:

5.

Name

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. Hint: If required, use the statement CLASS ... DEFINITION LOAD to syntactically enable direct access to the static components of the class.

Task 3: Create a travel agency instance and have it provide the data of a flight connection.

366

1.

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


BC401

Lesson: Special Object-Oriented Programming Techniques

Solution 22: Friendship Relationships (optional) Task 1: Buffer the flight data in a singleton class. 1.

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). Hint: You can use the global table kind TY_CONNECTIONS. a) b)

2.

Speak to your instructor if you have any questions. Model solution: CL_SINGLETON

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

Speak to your instructor if you have any questions.

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

Define and implement an instance constructor that sets the private attribute NAME. a)

4.

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 the public instance method GET_CONNECTION with the following signature: Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

367


Unit 4: Object-Oriented Repository Objects

Name

Kind

Reference type

IM_CARRID

Importing

S_CARR_ID

IM_CONNID

Importing

S_CONN_ID

EX_CONNECTION

Exporting

SPFLI

a) 5.

BC401

Carry out this step in the usual manner. Additional information is available in the SAP Library.

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. Hint: If required, use the statement CLASS ... DEFINITION LOAD to syntactically enable direct access to the static components of the class. a)

Use the relevant sections of the lesson as a guide.

Task 3: Create a travel agency instance and have it provide the data of a flight connection. 1.

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

368

© 2004 SAP AG. All rights reserved.

08-03-2004


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 Source code extract:

SAPBC401_SPCS_MAIN_B REPORT

sapbc401_spcs_main_b.

DATA: r_single TYPE REF TO cl_singleton, r_agency TYPE REF TO cl_agency, rec TYPE spfli.

START-OF-SELECTION. *######################## r_single = cl_singleton=>get_singleton( ). CREATE OBJECT r_agency EXPORTING im_name = ’Agency’.

r_agency->get_connection( EXPORTING im_carrid = ’LH’ im_connid = ’0400’ IMPORTING ex_connection = rec ).

WRITE: / rec-carrid, rec-connid, rec-cityfrom, rec-cityto.

08-03-2004

© 2004 SAP AG. All rights reserved.

369


Unit 4: Object-Oriented Repository Objects

BC401

Lesson Summary 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

Related Information ... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.

370

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: 347

Lesson: Persistent Objects in ABAP Objects for SAP Web Application Server 6.20

Persistent Objects in ABAP Objects for SAP Web Application Server 6.20 Lesson Duration: 45 Minutes

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

Lesson Objectives After completing this lesson, you will be able to: • • •

Create persistent objects using the standard technique Load persistent objects using the standard technique Access components of persistent objects

This lesson is largely concerned with future developments. That is, not all the concepts introduced here are fully implemented at present in the SAP standard system. In addition, the Persistence Services are not yet complete. For example, they do not yet support the SAP locking concept or any enhancements to it. Thus this lesson, more than others, presents you with the opportunity to deal with this topic in greater or lesser detail, depending on the time available and the level of interest among participants.

Business Example You need to use the new Object Services of the SAP Web AS 6.20 in your ABAP Objects programs.

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

08-03-2004

© 2004 SAP AG. All rights reserved.

371


Unit 4: Object-Oriented Repository Objects

BC401

Figure 163: Simulation of an Object-Oriented Database Management System

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

Persistent Objects as Instances of Special Global Classes 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.) 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. When you create a persistent class ZCL_<name>, 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_<name>. Programs must call

372

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Persistent Objects in ABAP Objects for SAP Web Application Server 6.20

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

Figure 164: Generating and Writing to Persistent Objects

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

373


Unit 4: Object-Oriented Repository Objects

BC401

Figure 165: Reading Persistent Objects

374

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Persistent Objects in ABAP Objects for SAP Web Application Server 6.20

351

Creating Persistent Classes 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.

Demonstration: Reading and Writing Objects Purpose You should explain how each Persistence Service works with the different Repository objects. You should also clarify what participants must do themselves and what the system does for them. We recommend that you create a new table, to make clear that the attribute values are actually written to and read from normal transparent (application) tables. You will extend the persistent classes to show that all general object-oriented programming techniques are available. Two different programs are created – one for reading, one for writing – to demonstrate unequivocally that the objects can be saved permanently and independently of specific programs.

System Data System: will be assigned Client: will be assigned User ID: will be assigned Password: will be assigned Set up instructions: None significant when using a standard SAP Web AS 6.20 training system 1. Model the class for airlines. Use the type SCARR-CARRID for the key. For the other attributes, use the following types:

08-03-2004

2.

• SCARR-CARRNAME • SCARR-CURRCODE • SCARR-URL Display the transparent table SCARR or create a new table.

3.

Create a persistent class and define a persistence mapping.

© 2004 SAP AG. All rights reserved.

375


Unit 4: Object-Oriented Repository Objects

BC401

4.

Activate all the generated classes.

5.

Show the main methods that have been generated automatically.

6.

Extend the persistent class: The method DISPLAY_ATTRIBUTES displays attribute values in a list.

7.

Write a second executable program with a selection screen so that you can input the attribute values. Check that the key is unique. Create a persistent object according to the entries in the selection screen. Handle the exception. Call the method or methods. Start the asynchronous update.

8.

Display the new table entry in the Data Browser

9.

Write a second executable program with a selection screen so that you can input the key. Read the persistent object according to the entries in the selection screen. Handle the exception. Call the method or methods.

10. Sample objects in package BC401: • • •

376

Persistent class CL_BC401_POJD_CARRIER Executable program SAPBC401_POJD_SET_PERSIST Executable program SAPBC401_POJD_GET_PERSIST

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Persistent Objects in ABAP Objects for SAP Web Application Server 6.20

Facilitated Discussion Here you have an opportunity to discuss any open issues that may have arisen. The discussion could be widened to include other, more in-depth questions, if desired. However, you should not enter into such a discussion unless you have mastered this topic fully. To find out whether you have or not, answer the following questions yourself. If you cannot, avoid this in-depth discussion.

Discussion Questions Use the following questions to engage the participants in the discussion.Feel free to use your own additional questions. • • • • •

08-03-2004

What is the underlying purpose of encapsulating database accesses using an object-oriented approach? Does it require more runtime resources than an non-encapsulated ABAP Open SQL access? Is the SAP locking concept used by the Persistence Services? What do you need to do when using table-type attributes? What do you need to take into account when using object GUIDs?

© 2004 SAP AG. All rights reserved.

377


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

Related Information ... is available in the SAP Library.

378

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Unit Summary

Unit Summary 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

08-03-2004

© 2004 SAP AG. All rights reserved.

379


Unit Summary

380

BC401

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

355

Test Your Knowledge 1.

Which of the following statements are correct? Choose the correct answer(s).

2.

□ □ □ □ □

A B C D E

F

G

H

I

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.

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.

□ □ 3.

True False

Which of the following statements are correct? Choose the correct answer(s).

□ □ □ □ □ □ □ □ □ □

08-03-2004

A B C D E F G H I J

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.

© 2004 SAP AG. All rights reserved.

381


Test Your Knowledge

4.

BC401

For what purpose is the technique of persistent objects used? Choose the correct answer(s).

382

A

B

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

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

357

Answers 1.

Which of the following statements are correct? Answer: B, D, G, H Refer to the relevant section of the lesson.

2.

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. Answer: False 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.

3.

Which of the following statements are correct? Answer: C, D, H, I 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

383


Unit 4: Object-Oriented Repository Objects

384

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


Unit 5 Exception Handling and Dynamic Programming

359

This is the natural position of this part of the course, as the procedural and object-oriented aspects practically overlap here. Caution: More so than the previous units, this unit contains syntax elements that were only introduced with SAP Web AS 6.10. Although the previous version of this course was already designed for SAP Web AS 6.10, some of these elements are described for the first time in this course. Additionally, some syntax elements that were already part of SAP R73 4.6A are being introduced here for the first time.

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

Unit Objectives After completing this unit, you will be able to: • • • • • •

08-03-2004

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

© 2004 SAP AG. All rights reserved.

385


Unit 5: Exception Handling and Dynamic Programming

• • • • • •

BC401

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

Unit Contents Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20 ......................................................................387 Procedure: Define global exception classes ............................394 Demonstration: Defining a Global Exception Class....................395 Demonstration: Raising, Propagating, and Handling an Exception..398 Demonstration: Mapping Other Exceptions to the Original Exception ....................................................................405 Exercise 23: Class-Based Exceptions ................................... 411 Exercise 24: Mapping Exceptions to Each Other ......................421 Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20 ........................................................431 Exercise 25: Type Casting with Data Elements (Optional)............453 Exercise 26: Creating Data Objects at Runtime........................459

386

© 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

361

Application Server 6.20 Lesson Duration: 120 Minutes

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

Lesson Objectives After completing this lesson, you will 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

It is particularly important to point out that this is an extension to the existing features of ABAP Objects. Naturally, the old exceptions concept can still be used, but will not be developed any more. Participants with experience in Java will notice marked similarities in syntax and runtime behavior. The main point again is to present the additional user-friendly options available in ABAP Objects and the ABAP Workbench. In the unlikely event that participants are (still) skeptical about object-oriented programming, it may be helpful to motivate them with a simple example from procedural programming: Until now, subroutines could not raise exceptions that could be handled. Instead you had to implement a “relationship check” using EXIT (or RETURN as of SAP Web AS 6.10) and auxiliary variables that you had to define yourself. Now, any processing block in ABAP Objects can raise a class-based exception.

Business Example You need to use the new exceptions concept of the SAP Web AS 6.20 in your ABAP Objects programs.

08-03-2004

© 2004 SAP AG. All rights reserved.

387


Unit 5: Exception Handling and Dynamic Programming

BC401

The Concept of Class-Based Exception Handling 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.

Figure 166: An Overview of the Class-Based Exception Concept

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

388

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

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

Figure 167: Exception Classes: The Inheritance Hierarchy

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.) In the SAP standard system, the names of all exception classes start with CX_. 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. New exception classes inherit from one of these superclasses, so that other components can be added. These are usually individual exception texts.

08-03-2004

© 2004 SAP AG. All rights reserved.

389


Unit 5: Exception Handling and Dynamic Programming

BC401

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

Figure 168: Structure of a TRY-ENDTRY Block

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

390

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

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. After an exception occurs, the system searches through the listed exception handlers in the order specified. It then executes the first exception handler whose CATCH statement contains the relevant exception class or one of its superclasses. In some cases, the system cannot find a handler for an exception within a specific TRY-ENDTRY 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. 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.

Example: Handling a Predefined Exception 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.

08-03-2004

© 2004 SAP AG. All rights reserved.

391


Unit 5: Exception Handling and Dynamic Programming

BC401

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 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. MESSAGE string TYPE message_type. As well as the string message that will be displayed, you must also specify the message type message_type. 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. 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.

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

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

08-03-2004

© 2004 SAP AG. All rights reserved.

393


Unit 5: Exception Handling and Dynamic Programming

367

BC401

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.

Figure 170: Creating Global Exception Classes

2.

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

Continued on next page

394

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

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

Figure 171: Define Variable Exception Texts

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

Activate your exception class.

Demonstration: Defining a Global Exception Class Purpose You should make clear how much the system supports developers. When using global classes they need only add the missing elements that fit their needs. In other words: “You can’t go wrong.” You should also show clearly how the features of the Class Builder are adapted automatically when you create an exception class.

08-03-2004

© 2004 SAP AG. All rights reserved.

395


Unit 5: Exception Handling and Dynamic Programming

BC401

System Data System: will be assigned Client: will be assigned User ID: will be assigned Password: will be assigned Set up instructions: None significant when using a standard SAP Web AS 6.20 training system 1. Copy the template program SAPBC401_EXCT_HANDLE_EXCEP, including all its include programs. 2.

Activate and execute this copy. Explain the functions and implementation of this program fully. In particular, point out the possible error situations in the GET_ATTRIBUTES of the local class LCL_PLANE and show the resulting unsatisfactory list display.

3.

Create an exception class. Derive it from the superclass CX_STATIC_CHECK.

4.

Create a read-only public instance attribute for the plane type. Name the attribute PLANETYPE.

5.

Enter a text for the predefined ID – such as “The airplane type ... is unknown.” Insert the airplane type generically using the public instance attribute.

6.

Define other public static constants as IDs for another exception text. Suggested name: CX_BC401_EXCD_PLANETYPE_F.

7.

Enter a text for this second ID – such as “This airplane type is for freight only.” Insert the airplane type generically using the public instance attribute.

8.

Activate the exception class

9.

Sample object in the package BC401: global class CX_BC401_EXCD_PLANETYPE

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

396

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

blocks or dialog 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 FORM subr_name ... RAISING cx_... cx_... or 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.

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 used to supply the value. When the exception is raised, the

08-03-2004

© 2004 SAP AG. All rights reserved.

397


Unit 5: Exception Handling and Dynamic Programming

BC401

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.

Demonstration: Raising, Propagating, and Handling an Exception Purpose Here you should demonstrate that an actual instance of the exception class is generated, which the regular object-oriented ABAP Objects syntax elements then access. You also show the extended features of the ABAP Debugger as they relate to the class-based exception concept. By displaying the reference contents, you should be able to emphasize the object-oriented approach of the new exception concept even more.

System Data System: will be assigned Client: will be assigned User ID: will be assigned Password: will be assigned Set up instructions: None significant when using a standard SAP Web AS 6.20 training system 1. Extend the signature of the method GET_ATTRIBUTES of the local class LCL_PLANE copied in the previous demonstration program, so that it propagates an instance of the global exception class. 2.

Raise an exception within the method for both situations. When doing so, •

If the key is wrong (sy-subrc = 4), set the default text ( textid = classname=>classname). If the airplane is a cargo airplane, (seatsmax_b = 0), set the additional text ( textid = classname=>new_text_id).

In both cases, set the airplane type (planetype = me->type).

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

3.

Handle the exception in the method DISPLAY_ATTRIBUTES of the local class LCL_CARRIER: Catch the exception when the method GET_ATTRIBUTES is called and the list is subsequently displayed. To do this, define a local reference with the type of a global exception class. We suggest the name: L_REF_EXC

4.

If an exception occurs, export the dynamically-set text and display it in the list instead of the unsatisfactory entries. To do so, define a text variable with a suitable type locally. We suggest the name: L_EXC_TEXT

5.

Activate and execute the program.

6.

Execute the program in debugging mode, thus demonstrating the features of the ABAP Debugger when an exception is raised.

7.

Sample object in package BC401: Executable program SAPBC401_EXCD_HANDLE_EXCEP

Example: Raising, Passing Along, and Handling an Exception CLASS lcl_plane DEFINITION. PUBLIC SECTION.

... METHODS get_attributes EXPORTING ex_name

TYPE t_name_15

value(ex_wa_plane) TYPE saplane RAISING cx_bc401_excd_planetype.

ENDCLASS.

"lcl_plane DEFINITION

CLASS lcl_plane IMPLEMENTATION. ...

METHOD get_attributes.

08-03-2004

© 2004 SAP AG. All rights reserved.

399


Unit 5: Exception Handling and Dynamic Programming

BC401

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 textid = cx_bc401_excd_planetype=>cx_bc401_excd_planetype_f. ENDIF. ELSE. RAISE EXCEPTION TYPE cx_bc401_excd_planetype EXPORTING planetype = me->type. ENDIF. ENDMETHOD. ENDCLASS.

"lcl_plane "lcl_plane IMPLEMENTATION

CLASS lcl_carrier DEFINITION.

PUBLIC SECTION. ... METHODS display_attributes.

ENDCLASS.

"lcl_carrier DEFINITION

CLASS lcl_carrier IMPLEMENTATION. ...

METHOD display_attributes. DATA: l_ref_plane TYPE REF TO lcl_plane, l_name TYPE t_name_15, l_wa_plane TYPE saplane,

l_ref_exc TYPE REF TO cx_bc401_excd_planetype, l_exc_text TYPE string.

...

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

TRY.

CALL METHOD l_ref_plane->get_attributes IMPORTING 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. ENDTRY.

ENDMETHOD.

ENDCLASS.

"display_attributes

"lcl_carrier IMPLEMENTATION

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

08-03-2004

© 2004 SAP AG. All rights reserved.

401


Unit 5: Exception Handling and Dynamic Programming

BC401

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

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.

Figure 173: Class-Based Exceptions in Debugging Mode

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.

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

We advise you to have the participants do the exercise on defining, raising, propagating, and handling class-based exceptions at this point.

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.

Figure 174: Integration of Standard Exceptions in the Runtime System

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

08-03-2004

© 2004 SAP AG. All rights reserved.

403


Unit 5: Exception Handling and Dynamic Programming

BC401

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

404

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

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

Demonstration: Mapping Other Exceptions to the Original Exception Purpose You should make clear how easy it is to get a reference to the previous exception instance in a chain of exceptions using the public attribute PREVIOUS. Caution: At this point, remind participants that chained exceptions must not be confused with an exception that is passed up several call levels.

08-03-2004

© 2004 SAP AG. All rights reserved.

405


Unit 5: Exception Handling and Dynamic Programming

BC401

System Data System: will be assigned Client: will be assigned User ID: will be assigned Password: will be assigned Set up instructions: None significant when using a standard SAP Web AS 6.20 training system 1. Copy the template program SAPBC401_EXCD_HANDLE_EXCEP, along with the previous demonstration program (including all include programs). 2.

Activate and execute this copy. Before the list is displayed, the user should receive a message informing him or her that at least one error situation could occur. Another information message should then display the text of the original exception. The list should then be displayed for the invalid airplane type, but not for those that follow it.

3.

Create an exception class. Derive it from the superclass CX_STATIC_CHECK.

4.

Enter a text for the predefined ID – such as “The list contains errors.”

5.

Extend the signature of the method DISPLAY_ATTRIBUTES of the local class LCL_CARRIER in the demonstration program, so that it propagates an instance of the global exception class.

6.

Have the method raise an exception if the original exception is caught for the invalid airplane type. In doing so, set the reference to point to the instance of this original exception ( previous = local_ref_to_prev_exc).

7.

Handle the exception in the main program: Catch the exception when the method DISPLAY_ATTRIBUTES of the local class .LCL_CARRIER is called To do this, define a reference in the main program with the type of a global exception class. We suggest the name: REF_EXC

8.

If the exception occurs, export the dynamically specified text and display it as an information message. To do so, define a text variable with a suitable type in the main program. We suggest the name: EXC_TEXT

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

Then export the reference to the original exception instance by accessing the appropriate attribute. Use this reference to export the text from the original exception and display it as an information message. To do so, define a text variable with a suitable type in the main program. We suggest the name: PREVIOUS_TEXT 9.

Activate and execute the program.

10. Execute the program in debugging mode, showing the content of the PREVIOUS attribute and of the references to the different exception instances. 11. Sample objects in package BC401: • •

Global class CX_BC401_EXCD_LIST Executable program SAPBC401_EXCD_GET_PREVIOUS

Example: Creating a Chain of Exceptions 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. CLASS lcl_carrier DEFINITION. PUBLIC SECTION.

... METHODS display_attributes RAISING cx_bc401_excd_list.

ENDCLASS.

"lcl_carrier DEFINITION

CLASS lcl_carrier IMPLEMENTATION.

... METHOD display_attributes. DATA: l_ref_plane TYPE REF TO lcl_plane, l_name TYPE t_name_15, l_wa_plane TYPE saplane,

08-03-2004

© 2004 SAP AG. All rights reserved.

407


Unit 5: Exception Handling and Dynamic Programming

BC401

l_ref_exc TYPE REF TO cx_bc401_excd_planetype, l_exc_text TYPE string. ... TRY. CALL METHOD l_ref_plane->get_attributes IMPORTING 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 EXPORTING previous = l_ref_exc. ENDTRY. ENDMETHOD.

"display_attributes

ENDCLASS.

"lcl_carrier IMPLEMENTATION

... DATA: ref_plane

TYPE REF TO lcl_plane,

ref_carrier TYPE REF TO lcl_carrier, ref_exc

TYPE REF TO cx_bc401_excd_list,

exc_text

TYPE string,

previous_text TYPE string.

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

TRY. CALL METHOD ref_carrier->display_attributes.

CATCH cx_bc401_excd_list INTO ref_exc.

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

exc_text = ref_exc->get_text( ). MESSAGE exc_text TYPE ’I’.

previous_text = ref_exc->previous->get_text( ). MESSAGE previous_text TYPE ’I’. ENDTRY.

...

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

08-03-2004

© 2004 SAP AG. All rights reserved.

409


Unit 5: Exception Handling and Dynamic Programming

410

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

379

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

Exercise 23: Class-Based Exceptions Exercise Duration: 45 Minutes

Exercise Objectives 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

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Create a global exception class for an invalid airplane type. 1.

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.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

411


Unit 5: Exception Handling and Dynamic Programming

BC401

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.

3.

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. To do so, define a local reference variable (suggested name: R_EXCEPTION) and assign it to the CX_ROOT class.

2.

Read the error text in the exception instance and display it in the ABAP list. To that end, define a variable (suggested name: EXC_TEXT) with data type STRING.

412

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

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) b) c)

2.

Add an attribute for the airplane type (suggested name: PLANETYPE) and assign the type S_PLANETYPE to it. a) b)

3.

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

Follow the processes as outlined in the relevant section of this document. Speak to your instructor if you have any questions.

Create a default error message that can be enhanced dynamically to include the airplane type. a) b)

Follow the processes as outlined in the relevant section of this document. Speak to your instructor if you have any questions.

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). 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. Ensure that the invalid airplane type is copied into the attribute of the exception instance. a)

See the source code extract from the model solution Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

413


Unit 5: Exception Handling and Dynamic Programming

3.

BC401

Make sure that the raised exception is explicitly propagated. a)

See the source code extract from the model solution

Task 3: Handle the exception. 1.

Catch your exception in the DISPLAY_ATTRIBUTES method of local class LCL_AIRPLANE. To do so, define a local reference variable (suggested name: R_EXCEPTION) and assign it to the CX_ROOT class. 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. To that end, define a variable (suggested name: EXC_TEXT) with data type STRING. a)

See the source code extract from the model solution

Result Source code extract:

BC401_EXCS_RAISE_TRY_CL2 *&---------------------------------------------------------------------* *&

Include

BC401_EXCS_RAISE_TRY_CL2

*

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

*------------------------------------------------------------------* * events in: lcl_airplane and lcl_carrier ! * *------------------------------------------------------------------* *

CLASS lcl_airplane DEFINITION

*

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

PUBLIC SECTION. "--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30. METHODS: constructor IMPORTING im_name

TYPE string

Continued on next page

414

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

im_planetype TYPE saplane-planetype, display_attributes. CLASS-METHODS: display_n_o_airplanes. EVENTS: airplane_created. PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes IMPORTING im_type

TYPE s_plan_wei

ex_tankcap

TYPE s_capacity

RAISING

DATA: name

TYPE saplane-planetype

EXPORTING ex_weight

cx_bc401_invalid_planetype.

TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS.

"lcl_airplane DEFINITION

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

CLASS lcl_airplane IMPLEMENTATION

*

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

METHOD constructor. name

= im_name.

planetype

= im_planetype.

n_o_airplanes = n_o_airplanes + 1. RAISE EVENT airplane_created. ENDMETHOD.

"constructor

METHOD display_attributes. DATA: weight TYPE saplane-weight, cap TYPE saplane-tankcap, 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. * handle exception in case of invalid planetype: TRY.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

415


Unit 5: Exception Handling and Dynamic Programming

BC401

get_technical_attributes( EXPORTING im_type = planetype IMPORTING ex_weight = weight ex_tankcap = cap ). 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. ENDTRY. ENDMETHOD.

"display_attributes

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

"display_n_o_airplanes

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

"get_technical_attributes "lcl_airplane IMPLEMENTATION

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

CLASS lcl_cargo_plane DEFINITION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane. PUBLIC SECTION. "---------------------METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype im_cargo TYPE scplane-cargomax. METHODS: display_attributes REDEFINITION.

PRIVATE SECTION.

Continued on next page

416

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

"---------------------DATA: max_cargo TYPE scplane-cargomax. ENDCLASS.

"lcl_cargo_plane DEFINITION

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

CLASS lcl_cargo_plane IMPLEMENTATION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_cargo_plane IMPLEMENTATION. METHOD constructor. CALL METHOD super->constructor EXPORTING im_name

= im_name

im_planetype = im_planetype. max_cargo = im_cargo. ENDMETHOD.

"constructor

METHOD display_attributes. super->display_attributes( ). WRITE: / ’Max Cargo = ’, max_cargo. ULINE. ENDMETHOD.

ENDCLASS.

"display_attributes

"lcl_cargo_plane IMPLEMENTATION

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

CLASS lcl_passenger_plane DEFINITION

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

PUBLIC SECTION. METHODS: constructor IMPORTING im_name TYPE string im_planetype TYPE saplane-planetype im_seats TYPE sflight-seatsmax. METHODS: display_attributes REDEFINITION.

PRIVATE SECTION. DATA: max_seats TYPE sflight-seatsmax. ENDCLASS.

"lcl_passenger_plane DEFINITION

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

417


Unit 5: Exception Handling and Dynamic Programming

BC401

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

CLASS lcl_passenger_plane IMPLEMENTATION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_passenger_plane IMPLEMENTATION. METHOD constructor. CALL METHOD super->constructor EXPORTING im_name

= im_name

im_planetype = im_planetype. max_seats = im_seats. ENDMETHOD.

"constructor

METHOD display_attributes. super->display_attributes( ). WRITE: / ’Max Seats = ’, max_seats. ULINE. ENDMETHOD.

"display_attributes

ENDCLASS.

"lcl_passenger_plane IMPLEMENTATION

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

CLASS lcl_carrier DEFINITION

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

PUBLIC SECTION. "---------------------------------------INTERFACES lif_partners. METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string, add_airplane FOR EVENT airplane_created OF lcl_airplane IMPORTING sender, display_airplanes, display_attributes. PRIVATE SECTION. "----------------------------------DATA: name

TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS.

"lcl_carrier DEFINITION

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

"lif_partners~display_partner

METHOD add_airplane. APPEND sender TO airplane_list. ENDMETHOD.

"add_airplane

METHOD display_attributes. SKIP 2. WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). ENDMETHOD.

"display_attributes

METHOD display_airplanes. DATA: r_plane TYPE REF TO lcl_airplane. LOOP AT airplane_list INTO r_plane. r_plane->display_attributes( ). ENDLOOP. ENDMETHOD.

"display_airplanes

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

"constructor

METHOD get_name. ex_name = name. ENDMETHOD.

ENDCLASS.

08-03-2004

"get_name

"lcl_carrier IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

419


Unit 5: Exception Handling and Dynamic Programming

420

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

389

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

Exercise 24: Mapping Exceptions to Each Other Exercise Duration: 30 Minutes

Exercise Objectives 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

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Define a local exception class for the event of an error text being displayed in the list. 1.

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

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

421


Unit 5: Exception Handling and Dynamic Programming

3.

BC401

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.

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

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.

2.

Extend the signature of the DISPLAY_ATTRIBUTES method, so that your new exception is explicitly propagated.

Task 3: Handle your new exception and evaluate the information of both the new and the original exception instance. 1.

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

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). 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. Enter this text in form of an information message, as well.

422

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

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

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

3.

Carry out this step in the usual manner. Additional information is available in the SAP Library. Model solution: SAPBC401_EXCS_RAISE_TRY_OPT

Carry out this step in the usual manner. Additional information is available in the SAP Library.

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

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.

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

08-03-2004

© 2004 SAP AG. All rights reserved.

423


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

Task 3: Handle your new exception and evaluate the information of both the new and the original exception instance. 1.

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)

2.

See the source code extract from the model solution

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)

3.

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

See the source code extract from the model solution

Result 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. INCLUDE bc401_excs_raise_try_opt_exc. INCLUDE bc401_excs_raise_try_opt_cl1.

Continued on next page

424

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

INCLUDE bc401_excs_raise_try_opt_cl2.

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

TYPE REF TO lcl_bus,

r_passenger TYPE REF TO lcl_passenger_plane, r_cargo TYPE REF TO lcl_cargo_plane, r_carrier TYPE REF TO lcl_carrier, r_rental TYPE REF TO lcl_rental, r_agency TYPE REF TO lcl_travel_agency. START-OF-SELECTION.

...

BC401_EXCS_RAISE_TRY_OPT_EXC *&---------------------------------------------------------------------* *&

Include

BC401_EXCS_RAISE_TRY_OPT_EXC

*

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

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

CLASS lcx_list_error DEFINITION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcx_list_error DEFINITION INHERITING FROM cx_static_check.

PUBLIC SECTION. METHODS get_exc_text RETURNING value(result) TYPE string.

"lcx_list_error DEFINITION

ENDCLASS.

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

CLASS lcx_list_error IMPLEMENTATION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcx_list_error IMPLEMENTATION.

METHOD get_exc_text. result = ’The list contains an error.’(err). ENDMETHOD.

"get_text

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

425


Unit 5: Exception Handling and Dynamic Programming

BC401

"lcx_list_error IMPLEMENTATION

ENDCLASS.

BC401_EXCS_RAISE_TRY_CL2 *&---------------------------------------------------------------------* *&

Include

BC401_EXCS_RAISE_TRY_CL2

*

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

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

CLASS lcl_airplane DEFINITION

*

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

METHODS: constructor IMPORTING im_name

TYPE string

im_planetype TYPE saplane-planetype. METHODS: display_attributes RAISING lcx_list_error.

CLASS-METHODS: display_n_o_airplanes. EVENTS: airplane_created. PRIVATE SECTION. "---------------------------------------------METHODS: get_technical_attributes IMPORTING im_type

TYPE s_plan_wei

ex_tankcap

TYPE s_capacity

RAISING

DATA: name

TYPE saplane-planetype

EXPORTING ex_weight

cx_bc401_invalid_planetype.

TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i. ENDCLASS.

"lcl_airplane DEFINITION

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

Continued on next page

426

© 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_airplane IMPLEMENTATION

*

*------------------------------------------------------------------* CLASS lcl_airplane IMPLEMENTATION. METHOD constructor. ... ENDMETHOD.

"constructor

METHOD display_attributes. DATA: weight TYPE saplane-weight, cap TYPE saplane-tankcap, r_exception TYPE REF TO cx_root, exc_text TYPE string.

WRITE: / icon_ws_plane AS ICON, / ’Name of Airplane’(001), AT pos_1 name, / ’Type of airplane: ’(002), AT pos_1 planetype. *

handle exception in case of invalid planetype: TRY. get_technical_attributes( EXPORTING im_type = planetype IMPORTING ex_weight = weight ex_tankcap = cap ). WRITE: / ’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. ENDMETHOD.

"display_attributes

METHOD display_n_o_airplanes. ... ENDMETHOD.

"display_n_o_airplanes

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

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

427


Unit 5: Exception Handling and Dynamic Programming

BC401

EXPORTING planetype = im_type. ENDIF. ENDMETHOD.

"get_technical_attributes

ENDCLASS.

"lcl_airplane IMPLEMENTATION

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

CLASS lcl_carrier DEFINITION

*---------------------------------------------------------------------* * *---------------------------------------------------------------------* CLASS lcl_carrier DEFINITION. PUBLIC SECTION. "---------------------------------------INTERFACES lif_partners.

METHODS: constructor IMPORTING im_name TYPE string, get_name RETURNING value(ex_name) TYPE string, add_airplane FOR EVENT airplane_created OF lcl_airplane IMPORTING sender, display_airplanes, display_attributes. PRIVATE SECTION. "----------------------------------DATA: name

TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane. ENDCLASS.

"lcl_carrier DEFINITION

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

CLASS lcl_carrier IMPLEMENTATION

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

METHOD lif_partners~display_partner. ... ENDMETHOD.

"lif_partners~display_partner

METHOD add_airplane. ... ENDMETHOD.

"add_airplane

METHOD display_attributes. SKIP 2.

Continued on next page

428

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Exception Handling in ABAP Objects for the SAP Web Application Server 6.20

WRITE: icon_flight AS ICON, name . ULINE. ULINE. display_airplanes( ). ENDMETHOD.

"display_attributes

METHOD display_airplanes. DATA: r_plane

TYPE REF TO lcl_airplane,

r_exc

TYPE REF TO lcx_list_error,

exc_text TYPE string.

LOOP AT airplane_list INTO r_plane. TRY. r_plane->display_attributes( ). CATCH lcx_list_error INTO r_exc. exc_text = r_exc->get_exc_text( ). MESSAGE exc_text TYPE ’I’.

exc_text = r_exc->previous->get_text( ). MESSAGE exc_text TYPE ’I’. ENDTRY. ENDLOOP. ENDMETHOD.

"display_airplanes

METHOD constructor. ... ENDMETHOD.

"constructor

METHOD get_name. ... ENDMETHOD. ENDCLASS.

08-03-2004

"get_name "lcl_carrier IMPLEMENTATION

© 2004 SAP AG. All rights reserved.

429


Unit 5: Exception Handling and Dynamic Programming

BC401

Lesson Summary 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

Related Information ... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.

430

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: 399

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20 Lesson Duration: 120 Minutes

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

Lesson Objectives After completing this lesson, you will 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

ABAP Objects is a programming language that contains both procedural and object-oriented features. The procedural parts must always be used in classes – that is, in object-oriented contexts. On the other hand, certain concepts (for example, runtime type identification, Business Add Ins, and the Control Framework) are only implemented as object-oriented concepts. Nevertheless, they can be used in both procedural and object-oriented concepts. Effectively, there is no sense in making an artificial distinction between the object-oriented and the procedural aspects of ABAP Objects. You can use this lesson to illustrate these ideas again.

08-03-2004

© 2004 SAP AG. All rights reserved.

431


Unit 5: Exception Handling and Dynamic Programming

BC401

This lesson is designed to contain the complete spectrum of information, so not all information may be of equal relevance to every participant. Therefore, focus specifically on dynamic instantiation and calls, and most of all on the CREATE DATA statement. The RTTI concept pulls the threads together at the end by solving a number of problems that are initially left open.

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

Figure 176: Field Symbols

You declare field symbols using the FIELD-SYMBOLS statement. Caution: Note that the parentheses (<>) around the field symbol’s name are part of the syntax.

432

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

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. 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: <fs_date> TYPE d, <fs_time> TYPE t. ASSIGN: date TO <fs_date>, time TO <fs_time>. * possible? <fs_time> = <fs_date>.

The last statement is a syntax error! Conversely, using the following construction would cause a runtime error: FIELD-SYMBOLS: <fs_date> TYPE ANY, <fs_time> 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. If the participants do not seem motivated to use this technique, remind them of the enormous runtime advantages for nested internal tables.

Figure 177: Type Casting with Field Symbols

08-03-2004

© 2004 SAP AG. All rights reserved.

433


Unit 5: Exception Handling and Dynamic Programming

BC401

If you use the CASTING addition when you assign a data object to a field symbol that has a different type, you can remove the restrictions of having to use the data object’s original type. The access is then interpreted as though the data object had the data type of the field symbol. If you use the CASTING TYPE 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.

For example: PARAMETERS tabname TYPE dd02l-tabname. DATA: dummy TYPE i, line(65535) TYPE c. FIELD-SYMBOLS <fs_wa> TYPE ANY. ASSIGN line TO <fs_wa> CASTING TYPE (tabname).

You can now access line using <fs_wa> as if this elementary data object had the same type as the row type of the transparent table passed using tabname. Note: You define the dummy data object only to ensure that line has the correct alignment.

Accessing Attributes Using Field Symbols 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.

Attribute Access Using the ASSIGN Statement ASSIGN class=>static_attribute TO <fs>. ASSIGN o_ref->instance_attribute TO <fs>.

If the field symbol <fs> has been typed generically, the missing type attributes are copied from the attributes during assignment. You can also access it dynamically.

434

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

Dynamic Attribute Access Using the ASSIGN Statement DATA: classname

TYPE seoclsname VALUE ’CLASS’,

attributname TYPE seocpdname VALUE ’ATTRIBUTE’. ASSIGN (classname)=>(attributname) TO <fs>. ASSIGN o_ref->(attributname) TO <fs>.

At this point, we recommend having the participants do the first (optional) exercise. It will provide a basic example of field symbols to help any participants who are not familiar with their use. Remind participants that this is only an example situation. This particular problem could also be solved using two MOVE statements.

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.

Figure 178: Data References

08-03-2004

© 2004 SAP AG. All rights reserved.

435


Unit 5: Exception Handling and Dynamic Programming

BC401

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. Note: The data syntax element represents a predefined name, comparable with space or constructor . You define the data reference variable itself using the DATA statement. This reference variable is a data object that can contain any data object (TYPE REF TO data) or a data object of the specified type. You work with data references using references. That is, when you access a data reference variable the data reference itself is accessed, so that changes are made to the addresses. Data references are handled in ABAP 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. 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. 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.) 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.)

436

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

The expression data_reference->* is comparable to the expression <field_symbol> . 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.

For example: DATA ref TYPE REF TO sflight.

CREATE DATA ref. ref->fldate = ref->fldate + 5. WRITE: / ref->seatsmax.

Here, the component selector is similar to the hyphen used with regular component access to structured data objects.

Validity of References – Logical Expression ... ref IS [NOT] BOUND ...

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. 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. In contrast, you can only use the expression ... ref IS [NOT] INITIAL ... to determine if ref contains the null reference or not. Chained lists are an important use for data references in other programming languages. This is not the case in ABAP Objects because it uses internal tables, which are very easy to handle. Remind the participants of the two main uses for data references in ABAP Objects, namely the following dynamic method calls and instantiation data objects at runtime.

08-03-2004

© 2004 SAP AG. All rights reserved.

437


Unit 5: Exception Handling and Dynamic Programming

BC401

Dynamic Instantiation and Calls Syntax elements can be transferred dynamically for many statements. The syntax for doing this differs, depending on the statement you use:

Figure 179: Dynamic Statements

If you pass the attribute as a literal in the static form of the statement, you can replace the literal with a variable. If you pass the attribute as an identifier in the static form of the statement, you can replace the identifier with a variable in parentheses. Make sure there are no spaces between either parenthesis and the variable. For some statements, you can use a single-column internal table instead of one or more literals or identifiers. Caution: Note: you must use upper case when filling data objects with literals. 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.

438

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

This principle also applies to the object-oriented statements in ABAP Objects. Using the following statement, you can instantiate objects dynamically:

Dynamic Instantiation of Objects DATA: classname TYPE seoclsname, o_ref TYPE REF TO object. ... CREATE OBJECT o_ref TYPE (classname) PARAMETER-TABLE it_par EXCEPTION-TABLE it_exc.

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. Note: Compare to TYPE REF TO data. 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:

Calling Instance Methods Dynamically CALL METHOD o_ref->(meth_name) PARAMETER-TABLE it_par EXCEPTION-TABLE it_exc.

or static methods

Calling Static Methods Dynamically CALL METHOD (classname)=>(meth_name) PARAMETER-TABLE it_par EXCEPTION-TABLE it_exc.

08-03-2004

© 2004 SAP AG. All rights reserved.

439


Unit 5: Exception Handling and Dynamic Programming

BC401

Figure 180: Parameter Transfer and Exception Allocation for Dynamic Instantiations and Calls

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. The table kind has three columns: NAME Name of the formal parameter KIND Type of parameter transfer (exporting, importing, changing, or receiving) 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. The exception table must have the attributes of the ABAP_EXCPBIND_TAB table kind. The table has two columns:

440

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

NAME Name of exception VALUE Value for the return variable SY-SUBRC (type: I) 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.

Figure 181: Dynamic Method Calls – Syntax Example

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

08-03-2004

© 2004 SAP AG. All rights reserved.

441


Unit 5: Exception Handling and Dynamic Programming

BC401

After the method call, the actual parameter GD_MAKE contains the passed value.

Dynamic Instantiation and Cast Assignments for Data Objects Using data references and the statement CREATE DATA, you can create data objects at runtime, as you can with class instances.

Instantiation of Data Objects at Runtime DATA ref TYPE REF TO typename. CREATE DATA ref.

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 DATA ref TYPE REF TO data. 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).

Emphasize the following possibilities if you notice that participants seem unmotivated by this topic. If anyone is still unclear about the possibilities of dynamic instantiation, be sure to give a problem-oriented demonstration in the example program.

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

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

Figure 182: Dereferencing Generically Typed Data References

This statement ASSIGN ref_itab->* TO <fs_itab> assigns the relevant data object (the one to which the data reference in the reference variable ref_itab points) to the field symbol <fs_itab>. If the data object is assigned successfully, SY_SUBRC is set to 0. If the field symbol is fully generically typed, it adopts the type of the data object. If the field symbol is partially or completely typed, the system checks the compatibility of the data types. You can also cast to the assigned data object. If the data reference is initial or invalid, it cannot be dereferenced. In that case the field symbol remains unchanged and SY-SUBRC is set to 4. We strongly recommend demonstrating the following program in the system (excerpt from the executable program SAPBC401_DYND_DATADECL_RTTI). Ideally, you should develop it together with the participants.

08-03-2004

© 2004 SAP AG. All rights reserved.

443


Unit 5: Exception Handling and Dynamic Programming

BC401

Generating Data Objects at Runtime – Application Example REPORT ... . DATA: ref_itab TYPE REF TO data, ref_wa

TYPE REF TO data.

FIELD-SYMBOLS: <fs_itab> TYPE ANY TABLE, <fs_wa>

TYPE ANY,

<fs_comp> TYPE ANY. 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. ASSIGN ref_itab->* TO <fs_itab>.

SELECT * FROM (pa_tab) INTO TABLE <fs_itab> UP TO 100 ROWS. CREATE DATA ref_wa LIKE LINE OF <fs_itab>. "or: TYPE (pa_tab). ASSIGN ref_wa->* TO <fs_wa>. LOOP AT <fs_itab> INTO <fs_wa>. DO. ASSIGN COMPONENT sy-index OF STRUCTURE <fs_wa> TO <fs_comp>. IF sy-subrc NE 0. NEW-LINE. EXIT. ENDIF. WRITE <fs_comp>. ENDDO. ENDLOOP.

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

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

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. The statement ASSIGN ref_wa->* TO <fs_wa> assigns the data object to the field symbol. The data type of the table is inherited by the field symbol, so type casting is no longer necessary. You can now write each data record from the SELECT statement into the compatibly-typed data object using the field symbol <fs_wa>. If you knew the component names, you could display the fields directly using WRITE <fs_wa>-.... However, you will not normally know the names of the components, nor how many of them there are. For this reason, you must display the components using the ASSIGN-COMPONENT variant: The components of the structure <fs_wa> are assigned one-by-one to the field symbol <fs_comp> and then displayed. When the loop runs out of components, the program requests the next data record. At this point, we recommend having the participants do the second exercise of this lesson. It would be a good idea to mention to the participants that SAP Grid Control is also a very powerful tool when used with dynamic programming.

Figure 183: Cast Assignment for Data References

08-03-2004

© 2004 SAP AG. All rights reserved.

445


Unit 5: Exception Handling and Dynamic Programming

BC401

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.

If necessary and/or there is enough interest among the participants, demonstrate the program SAPBC401_DYND_DATACAST.

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.

Figure 184: Copying Global Type Information for References – Principle

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:

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

Figure 185: Copying Global Type Information for References – Syntax Example

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 <fs_gen>, 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. 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. Caution: This example has been set up intentionally to display that the type of a statically typed reference variable is actually the decisive factor.

If required and/or there is enough interest among the participants, demonstrate the program SAPBC401_DYND_REF_GLOB_TYPE .

08-03-2004

© 2004 SAP AG. All rights reserved.

447


Unit 5: Exception Handling and Dynamic Programming

BC401

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:

Figure 186: Dynamic Type Analysis for RTTI Classes

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

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

We strongly recommend demonstrating the following source code in the system (excerpt from the executable program SAPBC401_DYND_DATADECL_RTTI). Ideally, you should develop it together with the participants.

Dynamic Data Type Analysis – Application Example ... DATA: ref_descr TYPE REF TO cl_abap_structdescr, wa_comp

TYPE abap_compdescr.

...

START-OF-SELECTION. ... * get reference to type descripion object by widening cast:

ref_descr ?= cl_abap_typedescr=>describe_by_data( <fs_wa> ). ...

TOP-OF-PAGE. LOOP AT ref_descr->components INTO wa_comp. WRITE wa_comp-name. ENDLOOP.

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. 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. The functional method call returns the reference to the description instance of the structure. (The system creates the structure dynamically, which is why it is accessed through a field symbol). Only the abstract class CL_ABAP_TYPEDESCR contains the method DESCRIBE_BY_DATA. Its RETURNING parameter is typed as a reference to this superclass. However, since the actual parameter REF_DESCR has the type of the subclass CL_ABAP_STRUCTDESCR, we need to assign the object using a widening cast.

08-03-2004

© 2004 SAP AG. All rights reserved.

449


Unit 5: Exception Handling and Dynamic Programming

BC401

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. We strongly recommend demonstrating the following source text in the system (excerpt from the executable program SAPBC401_DYND_RTTI_OBJECT). Ideally, you should develop it together with the participants.

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) DATA ref_class_descr TYPE REF TO cl_abap_classdescr.

ref_class_descr ?= cl_abap_typedescr=>describe_by_object_ref( sender ). IF ref_class_descr->get_relative_name( ) = ’LCL_BUS’. APPEND sender TO vehicle_list. ENDIF. ENDMETHOD.

"add_vehicle

...

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). We will now build upon this example: The vehicle rental company is now only interested in buses. 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. The functional method call again returns the reference to the description instance of the vehicle instance.

450

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

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

08-03-2004

© 2004 SAP AG. All rights reserved.

451


Unit 5: Exception Handling and Dynamic Programming

452

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

419

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

Exercise 25: Type Casting with Data Elements (Optional) Exercise Duration: 15 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Use field symbols to cast types • Calculate dates

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

System Data System: Client: User ID: Password: Set up instructions: AS 6.20 system

will be assigned will be assigned will be assigned will be assigned None significant when using a standard SAP Web

Task 1: Copy the template. 1.

Copy template: SAPBC401_TABS_PROCESS_DATA or ZBC401_##_PROCESS_DATA Program name: ZBC401_##_CASTING (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.

453


Unit 5: Exception Handling and Dynamic Programming

BC401

Task 2: 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: <FS_DATE>).

Task 3: Use the field symbol in the event block LOAD-OF-PROGRAM to calculate the default value.

454

1.

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.

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

Copy template: SAPBC401_TABS_PROCESS_DATA or ZBC401_##_PROCESS_DATA Program name: ZBC401_##_CASTING (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_DYNS_CASTING

Activate your copy (or copies). 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.

Task 2: 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. a)

2.

See the source code extract from the model solution

Define a field symbol based on this type (suggested name: <FS_DATE>). a)

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

© 2004 SAP AG. All rights reserved.

455


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

Result Source code extract:

SAPBC401_DYNS_CASTING REPORT sapbc401_dyns_casting.

TYPE-POOLS col. TYPES: BEGIN OF st_flight_c, ... END OF st_flight_c, BEGIN OF st_flight, ... END OF st_flight, BEGIN OF st_date, year(4)

TYPE n,

month(2) TYPE n, day(2)

TYPE n,

END OF st_date.

... FIELD-SYMBOLS <fs_date> TYPE st_date.

PARAMETERS: pa_date LIKE sy-datum, pa_alv

AS CHECKBOX DEFAULT ’X’.

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

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

ASSIGN pa_date TO <fs_date> CASTING.

<fs_date>-day = ’01’. IF <fs_date>-month < 12. <fs_date>-month = <fs_date>-month + 1. ELSE. <fs_date>-month = ’01’. <fs_date>-year

= <fs_date>-year + 1.

ENDIF.

AT SELECTION-SCREEN. IF pa_date < sy-datum. MESSAGE e085(bc401).

" date in the past

ENDIF.

START-OF-SELECTION.

08-03-2004

© 2004 SAP AG. All rights reserved.

457


Unit 5: Exception Handling and Dynamic Programming

458

© 2004 SAP AG. All rights reserved.

BC401

08-03-2004


BC401

425

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

Exercise 26: Creating Data Objects at Runtime Exercise Duration: 30 Minutes

Exercise Objectives After completing this exercise, you will be able to: • Dynamically instantiate data objects • Program dynamic Open SQL statements

Business Example You are to develop a program that can be used as an “ad-hoc data browser”. 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. 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. Optimization of runtime requirements is not the focus of this exercise.

System Data System: will be assigned Client: will be assigned User ID: will be assigned Password: will be assigned Set up instructions: None significant when using a standard SAP Web AS 6.20 training system

Task 1: Copy the template. 1.

Copy template: SAPBC401_DYNT_CREATE_DATA_SQL Program name: ZBC401_##_CREATE_DATA_SQL (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.

459


Unit 5: Exception Handling and Dynamic Programming

BC401

Familiarize yourself with the program and its existing functions.

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

3.

Assign a suitably-typed field symbol to the generated internal table so that its contents can be accessed (suggested name: <FS_ITAB>).

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

Task 3: Display the content of the internal table with an SAP Grid Control instance. 1.

Define a reference for the SAP Grid Control instance to be created (suggested name: REF_ALV). Hint: The relevant class is called CL_GUI_ALV_GRID.

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.

460

© 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 26: Creating Data Objects at Runtime Task 1: Copy the template. 1.

Copy template: SAPBC401_DYNT_CREATE_DATA_SQL Program name: ZBC401_##_CREATE_DATA_SQL (Where ## is your two-digit group number). a)

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

Carry out this step in the usual manner. Additional information is available in the SAP Library.

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

Define a reference for the internal table that is to be generated (suggested name REF_ITAB). a)

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: <FS_ITAB>). a)

See the source code extract from the model solution

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

461


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

See the source code extract from the model solution

Task 3: Display the content of the internal table with an SAP Grid Control instance. 1.

Define a reference for the SAP Grid Control instance to be created (suggested name: REF_ALV). Hint: The relevant class is called CL_GUI_ALV_GRID. a)

2.

Within the PBO module INIT_CONTROLS_0100 already created, create an instance of the SAP Grid Control. a)

3.

See the source code extract from the model solution

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

See the source code extract from the model solution

Result Source code extract:

SAPBC401_DYNS_CREATE_DATA_SQL REPORT

sapbc401_dyns_create_data_sql

.

Continued on next page

462

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

DATA: ok_code LIKE sy-ucomm, popans. DATA: ref_docking TYPE REF TO cl_gui_docking_container, ref_alv TYPE REF TO cl_gui_alv_grid.

DATA ref_itab TYPE REF TO data.

FIELD-SYMBOLS <fs_itab> TYPE ANY TABLE.

PARAMETERS pa_tab TYPE dd02l-tabname DEFAULT ’SPFLI’.

START-OF-SELECTION.

CREATE DATA ref_itab TYPE STANDARD TABLE OF (pa_tab) WITH NON-UNIQUE DEFAULT KEY. ASSIGN ref_itab->* TO <fs_itab>.

SELECT * FROM (pa_tab) INTO TABLE <fs_itab> UP TO 100 ROWS. IF sy-subrc <> 0. MESSAGE a702(bc401). ENDIF.

CALL SCREEN 100.

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

Module

clear_ok_code

OUTPUT

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

text

*----------------------------------------------------------------------* MODULE clear_ok_code OUTPUT. CLEAR ok_code. ENDMODULE.

" clear_ok_code

OUTPUT

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

463


Unit 5: Exception Handling and Dynamic Programming

BC401

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

Module

STATUS_0100

OUTPUT

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

text

*----------------------------------------------------------------------* MODULE status_0100 OUTPUT. SET PF-STATUS ’ST100’. SET TITLEBAR ’T100’. ENDMODULE.

" STATUS_0100

OUTPUT

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

Module

init_controls_0100

OUTPUT

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

text

*----------------------------------------------------------------------* MODULE init_controls_0100 OUTPUT. IF ref_docking IS INITIAL. CREATE OBJECT ref_docking EXPORTING *

SIDE

= DOCK_AT_LEFT

extension

= 2000

EXCEPTIONS OTHERS

= 6

. IF sy-subrc <> 0. MESSAGE a015(rfw). ENDIF.

CREATE OBJECT ref_alv EXPORTING i_parent

= ref_docking

EXCEPTIONS error_cntl_create = 1 error_cntl_init

= 2

error_cntl_link

= 3

error_dp_create

= 4

OTHERS

= 5

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

Continued on next page

464

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

ENDIF.

CALL METHOD ref_alv->set_table_for_first_display EXPORTING i_structure_name

= pa_tab

CHANGING it_outtab

= <fs_itab>

EXCEPTIONS invalid_parameter_combination = 1 program_error

= 2

too_many_lines

= 3

OTHERS

= 4

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

ENDIF. ENDMODULE.

" init_controls_0100

OUTPUT

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

Module

leave_programm

INPUT

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

text

*----------------------------------------------------------------------* MODULE leave_programm INPUT. CLEAR popans. CALL FUNCTION ’POPUP_TO_CONFIRM_STEP’ EXPORTING textline1

= text-dml

textline2

= text-rcn

titel

= text-cnc

cancel_display = ’ ’ IMPORTING answer

= popans.

CASE popans. WHEN ’J’. LEAVE PROGRAM. WHEN ’N’. CLEAR ok_code. ENDCASE.

Continued on next page

08-03-2004

© 2004 SAP AG. All rights reserved.

465


Unit 5: Exception Handling and Dynamic Programming

ENDMODULE.

BC401

" leave_programm

INPUT

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

Module

USER_COMMAND_0100

INPUT

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

text

*----------------------------------------------------------------------* MODULE user_command_0100 INPUT. CASE ok_code. WHEN ’BACK’. CLEAR popans. CALL FUNCTION ’POPUP_TO_CONFIRM_STEP’ EXPORTING textline1

= text-dml

textline2

= text-rbk

titel

= text-bak

cancel_display = ’ ’ IMPORTING answer

= popans.

CASE popans. WHEN ’J’. LEAVE TO SCREEN 0. WHEN ’N’. ENDCASE. WHEN ’EXIT’. CLEAR popans. CALL FUNCTION ’POPUP_TO_CONFIRM_STEP’ EXPORTING textline1

= text-dml

textline2

= text-rex

titel

= text-ext

cancel_display = ’ ’ IMPORTING answer

= popans.

IF popans = ’J’. LEAVE PROGRAM. ENDIF.

WHEN OTHERS. ENDCASE. ENDMODULE.

" USER_COMMAND_0100

INPUT

Continued on next page

466

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Lesson: Dynamic Programming with ABAP Objects for the SAP Web Application Server 6.20

Flow Logic Screen 100 PROCESS BEFORE OUTPUT. MODULE clear_ok_code. MODULE status_0100. MODULE init_controls_0100.

PROCESS AFTER INPUT. MODULE leave_programm AT EXIT-COMMAND. MODULE user_command_0100.

08-03-2004

© 2004 SAP AG. All rights reserved.

467


Unit 5: Exception Handling and Dynamic Programming

BC401

Lesson Summary 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

Related Information ... about this subject is available in the SAP Library and the ABAP keyword documentation for the individual statements.

468

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Unit Summary

Unit Summary 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

08-03-2004

© 2004 SAP AG. All rights reserved.

469


Unit Summary

470

BC401

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

437

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.

□ □ 2.

True False

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. Determine whether this statement is true or false.

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

© 2004 SAP AG. All rights reserved.

471


Test Your Knowledge

5.

BC401

Which of the following statements about dynamic programming are correct? Choose the correct answer(s).

472

□ □

A B

C

D

E

F

G

H

I

J

K

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.

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Test Your Knowledge

439

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. Answer: False Refer to the relevant section of the lesson.

2.

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.

3.

The new exception classes can only be defined globally. This ensures central maintenance and reuse. Answer: False Refer to the relevant section of the lesson.

4.

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

473


Course Summary

BC401

Course Summary You should now be able to: • • • • • • •

474

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

© 2004 SAP AG. All rights reserved.

08-03-2004


Appendix 1 Calling Programs and Passing Data

Calling Programs In ABAP Objects, there are two main ways of starting programs from within other programs: The material in this appendix was taken from the unit with the same name in the previous version of this course.

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. Restart The current program is terminated and the called program is started.

Figure 187: Calling Programs

08-03-2004

© 2004 SAP AG. All rights reserved.

475


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

Figure 188: Calling an Executable Program

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

476

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Appendix 1: Calling Programs and Passing Data

Figure 189: Calling a Transaction

With the 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. The statement CALL TRANSACTION ’T_CODE’ allows you to insert ABAP programs that have a transaction code. 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. Caution: The flow logic is processed.

08-03-2004

© 2004 SAP AG. All rights reserved.

477


Appendix 1: Calling Programs and Passing Data

BC401

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. Note: For further information, refer to the course BC414 (Programming Database Updates) and the SAP Library.

Management of Working Memory The way in which the working memory is organized from the program’s point of view can be represented easily using a model.

Figure 190: Logical Memory Model

There is a distinction between internal and external sessions: •

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.

Data for a program is only visible within an internal session. In general, data visibility is restricted to the relevant program.

478

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Appendix 1: Calling Programs and Passing Data

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.

Figure 191: Inserting a Program -1

Figure 192: Inserting a Program -2

08-03-2004

© 2004 SAP AG. All rights reserved.

479


Appendix 1: Calling Programs and Passing Data

BC401

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.

Figure 193: Terminating the Inserted Program

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.

480

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Appendix 1: Calling Programs and Passing Data

Figure 194: Restarting an Executable Program -1

Figure 195: Restarting an Executable Program -2

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

481


Appendix 1: Calling Programs and Passing Data

BC401

The starting situation for the third case is therefore the execution of the statement LEAVE TO TRANSACTION within a program.

Figure 196: Restarting a Transaction -1

Figure 197: Restarting a Transaction -2

482

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Appendix 1: Calling Programs and Passing Data

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

Figure 198: Passing Data Between Programs – Overview

You can use the following techniques to pass data: • • • • •

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.

08-03-2004

© 2004 SAP AG. All rights reserved.

483


Appendix 1: Calling Programs and Passing Data

BC401

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.

Figure 199: Passing Data Using the Program Interface

When you call ABAP programs that have a standard selection screen, you can pass data for the input fields in the call. There are two ways to do this: • •

By specifying a variant for the selection screen when you call the program When the program is called, you predefine specific values for the input fields

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.

484

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Appendix 1: Calling Programs and Passing Data

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

Figure 201: ABAP Memory and SAP Memory

08-03-2004

© 2004 SAP AG. All rights reserved.

485


Appendix 1: Calling Programs and Passing Data

BC401

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. You can use the contents of SAP Memory as default values for screen fields.

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.

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.

486

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Appendix 1: Calling Programs and Passing Data

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. 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. To release a data cluster, use the FREE MEMORY ID ... statement. 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).

Figure 203: Passing Parameters Using the SAP Memory

08-03-2004

© 2004 SAP AG. All rights reserved.

487


Appendix 1: Calling Programs and Passing Data

BC401

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. Here, you can also choose whether the entries from the field should be transferred to the parameter (SET), or whether the input field should be filled with the value from the parameter (GET). To find out about the names of the parameters assigned to input fields, display the input help (F4) for the field, and choose Technical info.

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.

Figure 204: Passing Data Using an Internal Table – Preview

488

© 2004 SAP AG. All rights reserved.

08-03-2004


BC401

Appendix 1: Calling Programs and Passing Data

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. 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). 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. You can find out if the transaction was executed successfully from the return value SY-SUBRC. This technique is useful if, for example: • •

You are processing in the foreground, but the input fields have not been filled using GET parameters You want to process the transaction in the background. In this case, you normally have to pass function codes as well.

Figure 205: Fields of the Global Type BDCDATA

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

08-03-2004

Input/output fields (with data) The command field BDC_OKCODE (with a function code) The cursor positioning field, BDC_CURSOR (with a field name)

© 2004 SAP AG. All rights reserved.

489


Appendix 1: Calling Programs and Passing Data

BC401

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. For further information, refer to the course BC420 (Data Transfer) and the SAP Library.

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

490

© 2004 SAP AG. All rights reserved.

08-03-2004


Index Numerics/Symbols ~, 230–231 ?=, 199, 236, 446 [], 39 ->*, 436, 443

BYTE-CO, 6 BYTE-CS, 6 BYTE-NA, 6 BYTE-NS, 6 byte-type, 5

A

C

abstraction, 106 ACTIVATION, 271 aggregation, 110, 133 alias name, 230–231, 240 ALIASES, 230 alignment, 7 alignment gap, 7 alignment requirement, 7 APPEND, 31–32, 40 SORTED BY, 33 ASCII character set, 3 ASSIGN, 433, 443 CASTING, 434 CASTING TYPE, 434 association, 110 binary, 110 recursive, 110 AT NEW, 38, 43 attribute, 120 AGENT, 373 KERNEL_ERRID, 390 PREVIOUS, 404 private, 122 public, 122 static, 123

CA, 6 CALL METHOD, 135–136 EXCEPTION-TABLE, 439 EXCEPTIONS, 125 EXPORTING, 125 IMPORTING, 125 PARAMETER-TABLE, 439 calling methods dynamically, 439 cardinality, 110 cast assignment operator, 446 CATCH, 390 CHANGING, 125 character length, 3, 5 character representation internal, 3 character set table, 3 character-type, 5 class, 104, 119 abstract, 354 CL_ABAP_CHAR_UTILITIES, 5 CL_ABAP_CLASSDESCR, 451 CL_ABAP_STRUCTDESCR, 449 CL_ABAP_TYPEDESCR, 448–449, 451 CL_GUI_ALV_GRID, 327

B basis class, 373 BINARY SEARCH, 48 byte sequence processing, 4–5 BYTE-CA, 6 BYTE-CN, 6

08-03-2004

© 2004 SAP AG. All rights reserved.

491


Index

BC401

CL_GUI_CUSTOM_CONTAINER, 327 definition part, 119 final, 355 friendship, 357 instantiation, 356 persistent, 372 CLASS, 119, 308 ABSTRACT, 354 CREATE, 356 DEFINITION, 119 FINAL, 355 FRIENDS, 357 INHERITING FROM, 185 PRIVATE SECTION, 122 PUBLIC SECTION, 122 class actor, 372 class agent, 372 class attribute, 124 Class Builder display settings, 319–320 editing class components, 314 class diagram, 109 CLASS EVENTS, 268 class method, 128 CLASS_CONSTRUCTOR, 142 CLASS-METHODS, 127 classes without multiple instantiation, 358 CLEANUP, 391, 398 CLEAR, 34 CN, 6 CO, 6 COLLECT, 31 ASSIGNING, 44 REFERENCE INTO, 44 COMMIT WORK, 373 component interface, 239 composition, 110

492

© 2004 SAP AG. All rights reserved.

compound interface, 239 constructor, 140, 188 static, 142 CONSTRUCTOR, 140 container control, 327 control level processing, 38, 43 CP, 6 CREATE DATA, 442 TYPE, 442 CREATE OBJECT, 130 TYPE, 439 CS, 6

D DATA TYPE REF TO, 130, 436, 446 TYPE REF TO data, 436 data reference variables, 436 data references, 436 data type table-type, 23 database management system object-oriented, 372 DEFAULT, 125 DEFAULT KEY, 26 DEFINITION, 119 definition part, 119 delegation, 113 delegation principle, 99 DELETE, 33, 35 ADJACENT DUPLICATES FROM, 34 TRANSPORTING, 33 WHERE, 34 dereferencing, 436, 443, 446–447 dereferencing operator, 436, 443, 446 DESCRIBE FIELD, 448 LENGTH, 6 DESCRIBE TABLE, 448 destructor, 140

08-03-2004


BC401

Index

downcast, 200, 237

E encapsulation, 93, 122 ENDAT, 38, 43 ENDTRY, 390 Enjoy Demo Center, 329 event static, 265 event handler method, 266 event-controlling, 100 EVENTS, 268 exception, 388 class-based, 388 mapping, 404–405 propagate, 390, 396 exception chain, 388, 404 exception class CX_DYNAMIC_CHECK, 389, 403 CX_NO_CHECK, 389, 404, 441 CX_OS_OBJECT_EXISTING, 373 CX_OS_OBJECT_NOT_FOUND, 373 CX_ROOT, 389, 404 CX_STATIC_CHECK, 389, 403 CX_SY_ARITHMETIC_ERROR, 392 CX_SY_ARITHMETIC_OVERFLOW, 392 CX_SY_MOVE_CAST_ERROR, 201, 237 CX_SY_ZERODIVIDE, 390 global, 388 inheritance hierarchy, 403 local, 388 superclass, 403 Exception class, 388

08-03-2004

exception handling, 388, 390 static check, 403 syntax check, 403 exception instance, 388 exception texts multiple, 390 EXPORT TO DATA BUFFER, 5

F field symbol, 432 FIELD-SYMBOLS, 432 fragment view, 7 FREE, 34 friend concept, 357 friendship relationship, 357 inheritance, 358 function CHARLEN, 5 STRLEN, 6 XSTRLEN, 6 function group data management, 93

G Garbage Collector, 132 generalization, 111, 183 global class print, 314 test, 314

H handler table, 272 hash algorithm, 46 hash function, 46 hashed table, 24, 46, 53 HASHED TABLE, 26 header line, 39

I IMPORT FROM DATA BUFFER, 5 IN BYTE MODE, 6 IN CHARACTER MODE, 5 indicator

© 2004 SAP AG. All rights reserved.

493


Index

BC401

OO transaction model, 330 information hiding, 122 inheritance, 100 INITIAL SIZE, 29, 33 INSERT, 31–32 ASSIGNING, 44 REFERENCE INTO, 44 instance, 105 instance attribute, 123 instance constructor, 140, 188 visibility section, 356 instance event, 265 instance method, 127 instantiating objects dynamically, 439 instantiation class, 129 data type, 442 interface class, 122 compound, 239 method, 125 INTERFACE, 230 interface resolution operator, 230–231 INTERFACES, 230 internal table attributes, 23 column, 23 control level processing, 38, 43 data type, 23 entry, 23 hash, 24 hash management, 46 header line, 39 index access, 24 initial size, 29 key, 23 key access, 24 row type, 23 sorted, 24 standard, 24 standard key, 26

494

© 2004 SAP AG. All rights reserved.

standard type, 27 table kind, 24 table scan, 48 unstructured row type, 26, 45 IS ASSIGNED, 433 IS BOUND, 437 IS INITIAL, 437

K KEY, 26

L LOOP AT, 38 ASSIGNING, 43, 49 REFERENCE INTO, 44, 49 TRANSPORTING NO FIELDS, 38 WHERE, 48

M ME, 143 MESSAGE, 392 method, 125 abstract, 354 call, 135–136 CREATE_PERSISTENT, 373 DESCRIBE_BY_DATA, 449 DESCRIBE_BY_OBJECT_REF, 451 final, 355 functional, 137 GET_PERSISTENT, 373 GET_RELATIVE_NAME, 451 GET_SOURCE_POSITION, 389 GET_TEXT, 389, 392, 395, 398 private, 126 public, 126 redefinition, 186 REFRESH_TABLE_DISPLAY, 329

08-03-2004


BC401

Index

SET_TABLE_FOR_FIRST_DISPLAY, 328 signature, 125 static, 127, 355 METHODS, 127 ABSTRACT, 354 FINAL, 355 FOR EVENT, 269 MODIFY, 33, 35 ASSIGNING, 44 REFERENCE INTO, 44 TRANSPORTING, 33 WHERE, 34 MOVE, 131 ?TO, 199, 236, 446 multiple inheritance, 185 multiple instantiation, 97 multiplicity, 110

P

N

R

NA, 6 namespace class, 127 narrowing cast, 193, 233 NON-UNIQUE, 26 NP, 6 NS, 6 null reference, 130, 437

RAISE EVENT, 268 RAISING, 397 READ TABLE, 36–37 ASSIGNING, 43, 49 BINARY SEARCH, 48 COMPARING, 37 REFERENCE INTO, 44, 49 TRANSPORTING, 37 TRANSPORTING NO FIELDS, 37 READ-ONLY, 121, 123 redefinition, 186 Refactoring Assistant, 323 reference independent, 132 validity, 437 reference semantics, 436 reference types, 446 reference variable, 130, 436 data type, 446 REFRESH, 34 registration, 270, 272 RETURNING, 125 role, 110

O object, 104 behavior, 108 identity, 105 persistent, 372 status, 105, 108 Object GUID, 372 object link, 110 Object Management Group (OMG), 107 offset access, 9–10 OO transaction, 329 Open SQL statement dynamic, 438 OPTIONAL, 125

08-03-2004

package, 108 Persistence Service, 372 persistent, 371 pointer dereferenced, 432 polymorphism, 100, 197, 234 prefix BYTE-, 6 PRIVATE SECTION, 122 processing character strings, 4–5 programming model object-oriented, 97 procedural, 91 PROTECTED SECTION, 189 PUBLIC SECTION, 122

© 2004 SAP AG. All rights reserved.

495


Index

BC401

role design pattern, 203 RTTI, 448 runtime error BCD_ZERODIVIDE, 390 catchable, 389 Runtime Type Identification (RTTI), 448

S SAP Control Framework, 325 SAP Grid Control, 326 Self-Reference, 143 SENDER, 269 sequence diagram, 112 SET HANDLER, 271 ACTIVATION, 271 FOR ALL INSTANCES, 271 signature, 125 singleton, 358 singleton class, 358 SORT, 35 SORTED BY, 33 sorted table, 24, 52 SORTED TABLE, 26 specialization, 111, 183 standard key, 26 standard table, 24, 51 STANDARD TABLE, 26 static attribute, 123 static constructor, 142 static method, 127 subclass, 183 SUPER, 186 superclass, 183 syntax check Unicode check, 4 system field SY-TABIX, 37–38 SY-TFILL, 36 SY-TLENG, 36

496

© 2004 SAP AG. All rights reserved.

T table scan, 48 TABLE_LINE, 26, 45, 132 text ID, 397 transaction code, 329 transaction service, 329 transient, 371 TRY, 390 type ABAP_EXCPBIND_TAB, 440 ABAP_PARMBIND_TAB, 440 dynamic, 193 static, 193 TYPE REF TO, 130 TYPE REF TO data, 436 TYPE REF TO object, 439 TYPES TYPE REF TO, 436, 446 TYPE REF TO data, 436

U UML, 107 UNASSIGN, 433 Unicode, 4 fragment view, 7 Unified Modeling Language, 107 UNIQUE, 26 upcast, 193, 233

V value semantics, 432 visibility section protected, 189

W widening cast, 200, 237 widening cast assignment operator, 199, 236 WITH, 26 DEFAULT KEY, 26 WITH HEADER LINE, 39

08-03-2004


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

08-03-2004

© 2004 SAP AG. All rights reserved.

497


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.