parte 3 - notas y trucos sap (bitacora) | trucos y anotaciones · 2013-01-27parte 3 - notas y...

557
TAW10_3 ABAP Workbench Fundamentals SAP NetWeaver Date Training Center Instructors Education Website Instructor Handbook Course Version: 2005 Q4 Course Duration: 15 Day(s) Material Number: 50077030 Owner: Mario Gohlke (D023031) An SAP Compass course - use it to learn, reference it for work

Upload: lecong

Post on 25-Mar-2018

245 views

Category:

Documents


9 download

TRANSCRIPT

Page 1: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3ABAP Workbench Fundamentals

SAP NetWeaver

Date

Training Center

Instructors

Education Website

Instructor HandbookCourse Version: 2005 Q4Course Duration: 15 Day(s)Material Number: 50077030Owner: Mario Gohlke (D023031)

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

Page 2: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Copyright

Copyright © 2005 SAP AG. All rights reserved.

No part of this publication may be reproduced or transmitted in any form or for any purpose without theexpress 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 softwarecomponents of other software vendors.

Trademarks

� Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint® and SQL Server® areregistered 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 ofCitrix Systems, Inc.

� HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C®, World WideWeb 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 aretrademarks or registered trademarks of SAP AG in Germany and in several other countries allover the world. All other products mentioned are trademarks or registered trademarks of theirrespective companies.

Disclaimer

THESE MATERIALS ARE PROVIDED BY SAP ON AN "AS IS" BASIS, AND SAP EXPRESSLYDISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR APPLIED, INCLUDING WITHOUTLIMITATION WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULARPURPOSE, WITH RESPECT TO THESE MATERIALS AND THE SERVICE, INFORMATION, TEXT,GRAPHICS, LINKS, OR ANY OTHER MATERIALS AND PRODUCTS CONTAINED HEREIN. INNO EVENT SHALL SAP BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL,CONSEQUENTIAL, OR PUNITIVE DAMAGES OF ANY KIND WHATSOEVER, INCLUDINGWITHOUT LIMITATION LOST REVENUES OR LOST PROFITS, WHICH MAY RESULT FROMTHE USE OF THESE MATERIALS OR INCLUDED SOFTWARE COMPONENTS.

Page 3: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

About This HandbookThis handbook is intended to complement the instructor-led presentation of thiscourse, and serve as a source of reference. It is not suitable for self-study.

Typographic ConventionsAmerican English is the standard used in this handbook. The following typographicconventions are also used.

Type Style Description

Example text Words or characters that appear on the screen. Theseinclude field names, screen titles, pushbuttons as well asmenu names, paths, and options.

Also used for cross-references to other documentationboth internal (in this documentation) and external (inother locations, such as SAPNet).

Example text Emphasized words or phrases in body text, titles ofgraphics, and tables

EXAMPLE TEXT Names of elements in the system. These include reportnames, program names, transaction codes, table names,and individual key words of a programming language,when surrounded by body text, for example SELECTand INCLUDE.

Example text Screen output. This includes file and directory namesand their paths, messages, names of variables andparameters, and passages of the source text of a program.

Example text Exact user entry. These are words and characters thatyou enter in the system exactly as they appear in thedocumentation.

<Example text> Variable user entry. Pointed brackets indicate that youreplace these words and characters with appropriateentries.

2005/Q4 © 2005 SAP AG. All rights reserved. iii

Page 4: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

About This Handbook TAW10_3

Icons in Body TextThe 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�spresentation.

iv © 2005 SAP AG. All rights reserved. 2005/Q4

Page 5: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

ContentsCourse Overview ...... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

Course Goals.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .viiCourse Objectives .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

Unit 1: Introduction to Object-Oriented Programming ..... . . . . . . . . . . . . . . . . . . . . . . . . . . .1The Object-Oriented Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3Analysis and Design with UML... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Fundamental Object-Oriented Syntax Elements .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

Unit 2: Object-Oriented Concepts and Programming Techniques..... . . . . . . . . . .107Inheritance and Casting... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109Interfaces and Casting .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .153Events .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193

Unit 3: Object-Oriented Repository Objects ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .235Global Classes and Interfaces ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .237

Unit 4: ALV Grid Control .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .321ALV Grid Control - Simple Lists .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .323ALV Grid Control - Field Catalog ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .337ALV Grid Control - Layout . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .349ALV Grid Control - Events ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .368

Unit 5: Exception Handling and RTTS ...... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .383Exception Handling in ABAP Objects ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .385RTTS (Run Time Type Service) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .428

Unit 6: Shared Objects ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .457Shared Objects .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .458

Unit 7: Case Study ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .495Case Study and Preview .... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .496

2005/Q4 © 2005 SAP AG. All rights reserved. v

Page 6: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Contents TAW10_3

Unit 8: ABAP Certification..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .533Description of Certification.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .534

Index ..... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .543

vi © 2005 SAP AG. All rights reserved. 2005/Q4

Page 7: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Course OverviewThis training course, lasting three weeks, provides a comprehensive and detailedintroduction to the basics of ABAP/ABAP object-oriented programming and theABAP Workbench tools. This course also prepares you for certification as aDevelopment Consultant SAP NetWeaver - ABAP Workbench 2004.

Target AudienceThis course is intended for the following audiences:

� Development consultants and developers who are responsible for adapting anddeveloping ABAP/ABAP Objects programs

Course PrerequisitesRequired Knowledge

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

Course Duration DetailsUnit 1:Introduction to Object-Oriented ProgrammingThe Object-Oriented Programming Model 30 MinutesAnalysis and Design with UML 30 MinutesExercise 1: UML Class Diagrams 30 MinutesFundamental Object-Oriented Syntax Elements 200 MinutesExercise 2: Local Classes 45 MinutesExercise 3: Objects 20 MinutesExercise 4: Method Calls 45 MinutesExercise 5: Constructors 45 MinutesExercise 6: Private Methods 45 Minutes

Unit 2: Object-Oriented Concepts and Programming TechniquesInheritance and Casting 160 MinutesExercise 7: Class Hierarchies 60 MinutesExercise 8: Polymorphism 20 MinutesExercise 9: Aggregation and Generic Calls 45 MinutesInterfaces and Casting 120 MinutesExercise 10: Interface Implementation 45 Minutes

2005/Q4 © 2005 SAP AG. All rights reserved. vii

Page 8: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Course Overview TAW10_3

Exercise 11: Aggregation, Generic Calls, andPolymorphism 45 Minutes

Events 75 MinutesExercise 12: Events in Superclasses 40 MinutesExercise 13: (Optional): Events in Interfaces 30 Minutes

Unit 3: Object-Oriented Repository ObjectsGlobal Classes and Interfaces 180 MinutesExercise 14: Global Classes 40 MinutesExercise 15: Global Interfaces 30 MinutesExercise 16: (Optional): Refactoring Assistant 15 MinutesExercise 17: ALV Grid Control 45 Minutes

Unit 4: ALV Grid ControlALV Grid Control - Simple Lists 1 MinutesExercise 18: ALV Grid Control - Simple Lists MinutesALV Grid Control - Field Catalog 50 MinutesALV Grid Control - Layout 80 MinutesExercise 19: ALV Grid Control - Field Catalogand Layout Minutes

ALV Grid Control - Events 1 MinutesExercise 20: ALV Grid Control - Events Minutes

Unit 5: Exception Handling and RTTSException Handling in ABAP Objects 90 MinutesExercise 21: Class-Based Exceptions 45 MinutesExercise 22: (Optional): Mapping Exceptions toEach Other 45 Minutes

RTTS (Run Time Type Service) 120 MinutesExercise 23: RTTI: Querying Object Attributes 30 MinutesExercise 24: (Optional): RTTC: Creating Typesat Runtime 30 Minutes

Unit 6: Shared ObjectsShared Objects 60 MinutesExercise 25: Using Shared Objects 50 Minutes

Unit 7: Case StudyCase Study and Preview 30 HoursExercise 26: Create a UML Class Diagram 20 MinutesExercise 27: Develop a Solution for a Test Case 300 Minutes

Unit 8: ABAP CertificationDescription of Certification 1 Minutes

viii © 2005 SAP AG. All rights reserved. 2005/Q4

Page 9: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Course Overview

Course GoalsThis course will prepare you to:

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

Course ObjectivesAfter completing this course, you will be able to:

� Describe the data structure of SAP systems� Use the ABAP Workbench tools� Create lists using classic reports� Create and call function groups and function modules� Work with the ABAP Dictionary� Program in a performance-sensitive manner� Describe the concepts behind object-oriented programming� Create lists using ALV Grid Control

SAP Software Component InformationThe information in this course pertains to the following SAP Software Componentsand releases:

� SAP Web AS 6.20� SAP Web AS 6.40

Work in progress

2005/Q4 © 2005 SAP AG. All rights reserved. ix

Page 10: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Course Overview TAW10_3

x © 2005 SAP AG. All rights reserved. 2005/Q4

Page 11: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 11 Introduction to Object-Oriented

Programming

For more information, see the introductory instructor notes in the lesson.

Unit OverviewThis unit covers the basics of object-oriented programing with ABAP Objects andprovides an insight into data modeling using Unified Modeling Language.

Unit ObjectivesAfter completing this unit, you will be able to:

� Explain the differences between procedural and object-oriented programmingmodels

� List the advantages of the object-oriented programming model� Name the most important diagram types in UML� Create simple class diagrams� Create simple object diagrams� Describe sequence diagrams� Define classes� Generate and delete objects� Access attributes� Call methods

Unit ContentsLesson: The Object-Oriented Programming Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3

2005/Q4 © 2005 SAP AG. All rights reserved. 1

Page 12: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Lesson: Analysis and Design with UML ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Exercise 1: UML Class Diagrams ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

Lesson: Fundamental Object-Oriented Syntax Elements .. . . . . . . . . . . . . . . . . . . . . 41Exercise 2: Local Classes.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Exercise 3: Objects .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77Exercise 4: Method Calls .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Exercise 5: Constructors .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Exercise 6: Private Methods ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

2 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 13: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: The Object-Oriented Programming Model

Lesson:3

The Object-Oriented Programming ModelLesson Duration: 30 Minutes

Lesson OverviewBased on your existing knowledge of procedural programming with ABAP, we willexplain the object-oriented approach and encourage you to use it. The main emphasiswill be on explanation. At this stage, it is important that you understand the subjectand its concepts so that we can build on this knowledge later.

For now, it would not make sense to try to argue a conclusive point for or against theobject-oriented approach. Before you can make a qualified decision, you need toknow object-oriented concepts and their advantages and disadvantages.

Even if this sort of decision is made within your team or by your developmentmanager, you should be able to contribute to the discussion.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Explain the differences between procedural and object-oriented programmingmodels

� List the advantages of the object-oriented programming model

Finding the best way to handle this lesson depends on the individual groupof participants. Experience shows that participants often have some previousknowledge of procedural programming, particularly the contents of the previouscourse BC400. Sometimes, for no apparent reason, these participants hesitate to useobject-orientation. Try to overcome this hesitation.

Therefore, it would be counterproductive to put too much emphasis on the last section.The attributes that are described there need to be dealt with gradually in the specificlessons. The final section is more suitable for participants with object-orientedexperience in other programming languages. You can assure these participants thatthey will soon be re-introduced to some familiar concepts.

It is important to clarify that the object-oriented programming model does not extendthe range of problems that can be solved algorithmically. Object orientation is justanother programming approach. It can solve exactly the same number of problems asother approaches.

2005/Q4 © 2005 SAP AG. All rights reserved. 3

Page 14: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Business ExampleYou need to explain the basics of the object-oriented programming model and itsadvantages to your development project manager.

Moving from the Procedural to the Object-OrientedProgramming ModelObject-oriented programming was developed at approximately the same time aslogical and procedural programming models, for example, the programming languageSimula 67. In the past, COBOL and the procedural programming model as expressedin languages like C or Pascal were dominant in enterprise application development.Before ABAP, SAP originally used a macro assembler.

Even today, many developers still have more experience with procedural programmingthan object-oriented programming. Therefore, this introduction to object-orientedprogramming also uses references to the procedural model in its explanations.

Figure 1: History of Selected Programming Languages

ABAP was created with the intention of improving reporting. It was developedrelatively independently as an in-house programming language, although it wasinfluenced by other programming languages like COBOL and Pascal. ABAP/4was then extended to form ABAP Objects. Therefore, ABAP Objects unitesobject-oriented and procedural elements in one programming language.

4 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 15: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: The Object-Oriented Programming Model

For the object-oriented part, only those object-oriented concepts that had provedtheir worth for enterprise application development in other languages, such as Java,C++, and Smalltalk, were adopted. ABAP Objects, like ABAP/4, also contains someunique, very advantageous concepts.

You should repeat these points whenever they are relevant throughout the entirecourse and illustrate them with specific syntax examples to ensure that they are notmerely seen as empty phrases.

Figure 2: Characteristics of the Procedural Programming Model

Data and functions are usually kept separate in the procedural programming model.Global variables for a program contain data, while subroutines contain functions.

Essentially, every subprogram can access every variable. This means that theprogramming model itself does not support consistent access to some related parts ofthe data.

2005/Q4 © 2005 SAP AG. All rights reserved. 5

Page 16: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 3: Typical Procedural ABAP Program

A typical procedural ABAP program consists of type definitions and data declarations,which describe the structure of the data used by the program when it is executed.Modularization units (for example, subroutines or function modules) can beencapsulated. On the main program level, however, there is no special protection forthe data objects: any variables can be accessed by any means.

Figure 4: Encapsulating Data Using Function Groups

6 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 17: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: The Object-Oriented Programming Model

Every time a function module is called in a main program, its function group is loadedinto the internal session. The function group remains active until the main programis finished. The main program and the function groups that were called in it are allstored 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 theglobal data � of the function groups. In other words, it is not possible to access thefunction group�s global data directly from the main program.

Encapsulation also incorporates the idea that the implementation of a service can behidden from the system�s other components, so that these cannot and do not makeassumptions about the internal status of the modularization unit. This way, the designof these other components is not dependent on a specific implementation of the othermodularization units.

Therefore, a function group is a unit of data and functions that manages thisdata. Encapsulated access to data and services � a concept of the object-orientedprogramming model � can therefore be supported in the procedural part of ABAPObjects. This meant that BAPIs could be implemented as function modules andBusiness Objects could be implemented as function groups.

It may be helpful to mention some other characteristics of function modules here, suchas remote capability or optional parallelization. In doing so, you risk being drawnaway from the core subject matter, but you will be able to emphasize the power andversatility of even the procedural part of ABAP Objects.

It can also help participants to understand that object-orientation is just anotherprogramming method and does not necessarily lead to more technical possibilities.

2005/Q4 © 2005 SAP AG. All rights reserved. 7

Page 18: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 5: Example of a Function Group

In the above example, the fictional function group S_VEHICLE provides a useror client with the services INC_SPEED, DEC_SPEED, and GET_SPEED. Theseservices are the function group�s interface and access the global data object SPEED,which belongs to the whole function group.

Figure 6: Example of Using the Function Group

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

8 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 19: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: The Object-Oriented Programming Model

We feel that the best way to learn about the new aspects is to highlight the differencesfrom the old characteristics. Multiple instantiation is a new characteristic that could besuitable for this purpose. Some other object-oriented concepts also exist in procedurallanguages or they are easy to imagine.

However, this is not the case for inheritance. It is more difficult, and therefore lesssuitable for defining the limits of the object-oriented approach.

Figure 7: Several Instances of One Function Group

It is not possible for the main program to work with several vehicles without extraprogramming and administrative effort. Most importantly, one specific vehicle couldno longer be represented by a whole function group.

Figure 8: Multiple Instantiation in Object-Oriented Programming

2005/Q4 © 2005 SAP AG. All rights reserved. 9

Page 20: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

The possibility of creating several runtime instances in a capsule for each programcontext is one of the key characteristics of object-oriented programming.

In this example, four vehicles were created, all of which have different characteristicinstances. However, they all share the same data structure, the same range offunctions, and the ability to protect their data against access from the outside.

Figure 9: ABAP Main Memory and Encapsulation

Like the function groups, the objects are also stored in the same internal session asthe program that is being used. Also, all data areas are separated from each other andare therefore protected.

10 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 21: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: The Object-Oriented Programming Model

Figure 10: Data Management in Procedural and Object-Oriented Models

Unlike in procedural programming, the use of multiple instantiation in object-orientedprogramming allows you to create a direct abstraction of a real object. For thispurpose, the established concept of encapsulation was systematically extended.

The ABAP Objects Object-Oriented Programming ModelThe object-oriented concepts of ABAP Objects are essentially the same as those ofother modern object-oriented languages such as C++ or Java. A small number ofconcepts that did not prove to be successful in these other languages were not includedin ABAP Objects. On the other hand, ABAP Objects also has helpful languageelements that C++ and Java do not offer.

Some specific features of ABAP Objects only exist because of the guaranteed upwardcompatibility of older ABAP language elements.

Major differences in comparison to other object-oriented languages are in thedevelopment environment. You can use the ABAP Workbench�s entire range offunctions with ABAP Objects.

2005/Q4 © 2005 SAP AG. All rights reserved. 11

Page 22: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 11: ABAP Objects as a Compatible Extension of ABAP

ABAP Objects is not a new language, but has been designed as a systematic extensionof ABAP. All of the extensions, including the old procedural parts, are upwardlycompatible.

Type checks in the object-oriented contexts of ABAP Objects are stricter than those inthe procedural contexts.

In developing ABAP Objects, the ABAP language was cleaned up, in particular in theobject-oriented contexts. This means that obsolete statements lead to syntax errors.

However, it is also advisable to avoid obsolete statements in the purely proceduralenvironment, as this creates source texts that are safer and more flexible. Nevertheless,as the language is upwardly compatible, it is not possible to entirely prevent the useof such statements.

For a list of obsolete language elements, refer to the ABAP keyword documentation.Every obsolete statement is also specifically noted as forbidden in the object-orientedcontext.

It may be useful to mention the great advantages of SAP�s approach: The upwardcompatibility saves developers from having to carry out a migration when a newrelease is implemented. With a small number of exceptions, the Repository objectsfrom the first SAP R/3 Basis release can still be used without restrictions in SAP WebAS 6.20. No competitor can match this.

12 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 23: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: The Object-Oriented Programming Model

Figure 12: Client/Server Relationships Between Objects

Objects behave like client/server systems. When one object sends a message toanother object, telling it to behave in a certain way, the first object can be seen as aclient and the other as a server.

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

In principle, objects can perform both roles simultaneously; they can offer services toother objects while requesting services at the same time.

In object-oriented programming, the services are distributed among the objects insuch a way as to avoid redundancies and so that each object offers exactly thoseservices that are within its area of responsibility. If an object needs any other services,it requests these from other objects. This is known as the principle of delegation.

For example:

For example, the common task �data retrieval and output� should be distributed overat least two objects: one is responsible for data retrieval and one for output. As longas the data retrieval object does not change its protocol, its internal implementationcan be altered without any necessary changes to the output object. Alternately, thedata retrieval object could be replaced by a different object, providing that the newobject uses the same protocol. These exchanges can also take place at runtime.

2005/Q4 © 2005 SAP AG. All rights reserved. 13

Page 24: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

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

inheritanceInheritance defines the implementation relationships between classes. One class(the subclass) adopts the structure and behavior of another class (superclass),possibly also adapting or extending it.

PolymorphismPolymorphism is when instances of different classes respond differently to thesame messages.

Event controlInstead of sending messages directly to specific objects, objects can also triggerevents. Events can be triggered if it is not yet known at the time of developmentif and how objects will react.

To summarize, the object-oriented programming model of ABAP Objects has thefollowing key characteristics:

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

The model has the following advantages:

14 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 25: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: The Object-Oriented Programming Model

� Improved software structure and consistency in the development process� Reduced maintenance effort and less susceptibility to errors� Better integration of the customer/user into the analysis, design, and maintenance

processes� Options for extending the software are simpler and more secure

A standardized language is used in the various phases of software development(analysis, specification, design, and implementation). Communication is much easierwhen changing between phases.

The features will only become apparent to the participants after they have completedthe relevant lessons. Make sure they understand that the claims made in this coursewill be verified by their own experience.

In object-oriented programming, analysis and design decisions have an even greatereffect on implementation than they do in procedural programming. Therefore, youshould already structure and formally standardize the analysis and design phase. Youcan use modeling languages to do this.

Figure 14: The Software Development Process

2005/Q4 © 2005 SAP AG. All rights reserved. 15

Page 26: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Facilitated DiscussionHere you have an opportunity to discuss any open issues that may have arisen. Inmost cases, however, we suggest moving swiftly forwards to the more practice-basedlessons.

Discussion QuestionsUse the following questions to engage the participants in the discussion. Feel free touse your own additional questions.

Use the questions as appropriate to find out what participants know.

16 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 27: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 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

2005/Q4 © 2005 SAP AG. All rights reserved. 17

Page 28: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Lesson:15

Analysis and Design with UMLLesson Duration: 30 Minutes

Lesson OverviewThis lesson will help you to develop an object-oriented solution to a businessapplication problem, from classifying your objects through to defining therelationships between them.

We will be using parts of the Unified Modeling Language (UML) modeling standardas a visual aid.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Name the most important diagram types in UML� Create simple class diagrams� Create simple object diagrams� Describe sequence diagrams

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

Business ExampleYou need to model a business application requirement before it is implemented.

ClassificationWith object-oriented programming, the real world is viewed as a collection of objects� for example, different airplanes, cars, and people. Some of these objects are verysimilar. In other words, they can be described using the same characteristics andthey exhibit the same behaviors.

18 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 29: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

All characteristics and behaviors of these similar objects are now grouped into onecentral class. This class is used to describe every object that derives from it. Aclass, therefore, is a description of a quantity of objects that are typified by the samecharacteristics and the same behaviors.

Figure 15: Classification of Objects

For example, the vehicle �make x, ... series n� is an object of class �car.� This objectis 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 anattribute that distinguishes each object from all other objects of its class. Two differentobjects can have identical attribute values and still not be identical.

For example,two coffee cups have the same height and diameter, have the samehandle, and are both white. Although their statuses are therefore completely identical,they are clearly two different coffee cups.

Literature on the subject of object orientation often speaks of instances. An instancesimply means an object.

Note: In the literal sense of the word instance, the meaning is slightly morespecific. It means a concrete � that is, uniquely identifiable � instance ofa class.

In the following pages, we will make a distinction between instance and object.

2005/Q4 © 2005 SAP AG. All rights reserved. 19

Page 30: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 16: Classes as Abstraction Forms

In a software context, abstractions are simplified representations of complexrelationships in the real world. A real, existing object is abstracted to dimensions thatare relevant for simulating the required section of the real world.

This example concerns vehicles. Software for a vehicle enthusiast and software for ascrap merchant contain different abstractions (classes) for these objects. Dependingon the type of abstraction, a class can contain very different aspects of the objects.

In reality, classification is the decisive step. Therefore, it requires extensiveconsiderations that would go far beyond the framework of this course. This must beemphasized to the participants. At this point, you will need to keep questions to aminimum and ask participants to be patient to keep up the necessary pace. As this is atraining situation, a certain starting situation has to be accepted as given.

20 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 31: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

Figure 17: Comparison of Classes and Objects

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

Modeling in UMLUnified Modeling Language (UML) is a globally standardized modeling language. Itis used for the specification, construction, visualization, and documentation of modelsfor software systems and enables uniform communication between users.

UML is an industry standard and was initally developed by the Object ManagementGroup (OMG) since September 1997. SAP uses UML as a company-wide standardfor 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 differentviews of a system. The following three diagram types are of particular significancein this context:

Class diagramsShow the classes and the relationships between them, that is, a static view of amodel.

Behavior diagramsPay particular attention to the sequence in which the objects relate to each other.

2005/Q4 © 2005 SAP AG. All rights reserved. 21

Page 32: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Component diagramsShow the organization and dependencies of components.

Later, we will need to find concrete methods for realizing the first two aspects in thelist in the programming language.

The third aspect, component diagrams, is realized in the Repository object package. Inother words, packages can be used to realize the structure of software componentswithin SAP Web Application Server (SAP Web AS) according to the structure'sspecification in a component diagram.

Figure 18: 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 ofomitting the attribute and/or the method parts.

Attributes describe the data that can be stored in the objects of a class. They alsodetermine the status of an object.

Methods describe the functions that an object can perform. They therefore determinethe object's behavior.

22 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 33: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

Figure 19: Example of a Class Diagram

For the modeler of this example, a vehicle is a car with 4 wheels. Of course, theexample with car rental companies and cars could also have been described andmodeled differently. Don't forget to point this out to the participants!

A class diagram describes all static relationships between the classes. There aretwo basic forms of static relationships:

AssociationIn this example, a customer books a car at a rental car company.

Generalization/specializationIn this example, a car, a bus, and a truck are all vehicles.

Note: As mentioned previously, classes can also be shown in class diagramswith their attributes and methods. Here, these have been left out to improveclarity.

2005/Q4 © 2005 SAP AG. All rights reserved. 23

Page 34: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 20: Association

An association describes a semantic relationship between classes. The specificrelationship between objects in these classes is known as an object link. Object linksare 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 arelationship with itself. In most cases, recursive associations are used to link twodifferent objects in one class. The discussion below assumes that the associationsare binary.

Each association has two roles: one for each direction of the association. Each rolecan be described with an association name. Each role has a cardinality that shows howmany instances can participate in this relationship. The multiplicity is the number ofparticipating objects in one class that have a relationship to an object in the otherclass. Like all other elements of the model, cardinalities are dependent on the concretesituation that is being modeled.

24 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 35: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

In this example, you could also require a cardinality of �at least one� to indicatethat only a person who actually makes a booking becomes a customer of the rentalcar company. On the other hand, the cardinality �any number� would allow for amore general definition of a customer.

� An association is represented by a line between the class symbols.� The cardinality (also referred to as multiplicity) of the relationship can be

specified at each end of the line.� Arrows can also be used to indicate the navigation options, that is, the

accessibility of the association partner.� This association name is written in italics above the line and may contain an

arrow to show the read direction.� If roles are defined for both partners, role names can be entered at the end of

the lines.

Inform the participants that you will now be providing some additional detailedexamples of associations to demonstrate the options for modeling with classdiagrams. However, recursive and multiple associations and association classes willnot be mentioned again for the rest of the course and are not used in the exercises.Nevertheless, one objective of this course is to learn how to distinguish betweenassociation, aggregation/composition and generalization/specialization. It is importantthat the participants have understood this!

Figure 21: Association with Roles: Examples

2005/Q4 © 2005 SAP AG. All rights reserved. 25

Page 36: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

In the example ofmultiple associations shown here, role names are used at the end ofthe association lines to describe in greater detail the relationships between the classesinvolved. A person could appear in the role of employee or of company directorfor example.

In the recursive association shown here, the two roles of �child� and �parent� aresimilarly defined using role names. Two instances of the LCL_PERSON class thushave a relationship with each other and represent two roles.

Figure 22: Association Classes

If association is used to link two classes, this relationship can be better representedby a special class. The various characteristics of the relationship are described usingthe attributes of the association class. A dotted line connects this additional classto the association line.

26 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 37: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

Figure 23: Aggregation and Composition

Aggregation and composition are specializations of association. They show that anobject consists of other objects or contains other objects (composition part). Therelationship can be described with the words �consists of� or �is a part of�. Forexample, a car consists of wheels, among other things.

Aggregation and composition are displayed as a line between two classes that islabeled with a small rhombus. The rhombus indicates the aggregate, that is, thecomposition. Otherwise the notation conventions are the same as for associations.

Composition is a specialization of aggregation. Composition means that thecontained object cannot exist without the aggregate (for example, a car reservationcannot exist without the car rental). Therefore, the cardinality of the aggregate canonly be exactly one. The lifetime of the individual parts is linked to the lifetime of theaggregate; parts are created either with or after the aggregate, and they are destroyedeither with or before the aggregate.

In UML notation, composition is denoted by a filled-in rhombus.

2005/Q4 © 2005 SAP AG. All rights reserved. 27

Page 38: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 24: 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. Thisarrow always points to the more general class. The level of generalization increases inthe direction of the arrow. Trees can be built up using several of these relationships.

28 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 39: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

Figure 25: Object Diagram

An object diagram is a �snapshot� taken during program execution, which describesthe instances of the classes and the relationships between them.

It is not a new type of diagram. Rather, it is a variant of the class diagram and is onlyuseful for representing a complex class diagram.

Here you can use the optional exercise relating to object diagrams to underline thedifference between classes and objects.

The following sequence diagrams complete the unit on modeling. They will not bementioned again for the rest of the course!

2005/Q4 © 2005 SAP AG. All rights reserved. 29

Page 40: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 26: Sequence Diagram

Sequence diagrams are used to display certain processes or situations. Sequencediagrams 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 boxcontaining 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 controlfocus 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 iswritten above the arrow in the form nachricht (parameter). There are various ways to represent the reply; in this example, it is shown as adotted returning arrow.

You can also include a description of the process and add comments to the objectlifeline as required.

30 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 41: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

Figure 27: Delegation Principle in a Sequence Diagram

In delegation, two objects are involved in handling a request. The recipient of therequest passes on the execution of the request to a delegate.

In this example, the driver (object DRIVER) sends the message GET_FUEL_LEVELto the vehicle (object CAR). The receipt of this message causes the car to send amessage to the tank (object TANK) to find out what the tank contains. In other words,the car delegates this task to the tank. If necessary, the car formats the informationcontaining the current value of the tank contents before it passes it back to the driver.

2005/Q4 © 2005 SAP AG. All rights reserved. 31

Page 42: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

32 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 43: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

29 Exercise 1: UML Class DiagramsExercise Duration: 30 Minutes

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

Business ExampleModeling simple airplane management.

Task 1: Model a UML Class DiagramYou want to model some key classes for simple airplane management.

1. Your UML class diagram should contain the following classes:

LCL_CARRIER for the airline companiesLCL_AIRPLANE for airplanes (general)LCL_PASSENGER_PLANE for passenger planesLCL_CARGO_PLANE for cargo planes

2. Include some appropriate attributes and methods for each class.

3. Define relationships between your classes.

Choose suitable association types.

4. Choose suitable cardinalities.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 33

Page 44: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Task 2: Optional: Object Diagrams

The advantage of this exercise is that it gives the participants another opportunity topractice (with your help) distinguishing between classes and objects. You shouldtherefore include this exercise if you have enough time.

Decide whether the following object diagrams are correct.

1. A class diagram is shown (see the following figures).

Eight object diagrams are drawn for this class diagram.

Decide whether each object diagram is correct and check the provided box ifit is correct.

Figure 28: Possible Object Diagrams? (1)

Continued on next page

34 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 45: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

Figure 29: Possible Object Diagrams? (2)

2005/Q4 © 2005 SAP AG. All rights reserved. 35

Page 46: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Solution 1: UML Class DiagramsTask 1: Model a UML Class DiagramYou want to model some key classes for simple airplane management.

1. Your UML class diagram should contain the following classes:

LCL_CARRIER for the airline companiesLCL_AIRPLANE for airplanes (general)LCL_PASSENGER_PLANE for passenger planesLCL_CARGO_PLANE for cargo planes

a) Use the model solution as a guide.

2. Include some appropriate attributes and methods for each class.

a) The general attributes and methods for the airplanes should be contained inLCL_AIRPLANE. Continue using model solution as a guide.

3. Define relationships between your classes.

Choose suitable association types.

a) A generalization/specialization relationship between LCL_AIRPLANEand LCL_PASSENGER_PLANE or LCL_CARGO_PLANE seems tobe appropriate. An aggregation should exist between LCL_AIRPLANEand LCL_CARRIER.

Use the model solution as a guide.

Continued on next page

36 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 47: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

4. Choose suitable cardinalities.

a) Various cardinalities can be used in this case. Use the relevant sections ofthe lesson and the model solution as a guide.

Figure 30: Class Diagram for Exercise: CARRIER/AIRPLANE

Task 2: Optional: Object Diagrams

The advantage of this exercise is that it gives the participants another opportunity topractice (with your help) distinguishing between classes and objects. You shouldtherefore include this exercise if you have enough time.

Decide whether the following object diagrams are correct.

1. A class diagram is shown (see the following figures).

Eight object diagrams are drawn for this class diagram.

Decide whether each object diagram is correct and check the provided box ifit is correct.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 37

Page 48: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 31: Possible Object Diagrams? (1)

Continued on next page

38 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 49: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Analysis and Design with UML

Figure 32: Possible Object Diagrams? (2)

a) The object diagrams numbered 2, 4, 5, 6 and 8 are correct.

2005/Q4 © 2005 SAP AG. All rights reserved. 39

Page 50: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Lesson Summary

You should now be able to:� Name the most important diagram types in UML� Create simple class diagrams� Create simple object diagrams� Describe sequence diagrams

40 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 51: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Lesson:36

Fundamental Object-Oriented Syntax ElementsLesson Duration: 200 Minutes

Lesson OverviewIn this lesson, you will put your models into practice. First, you need to learn thefundamental object-oriented syntax elements.

You will receive a step-by-step introduction to the definition of local classes and theirbasic uses, accompanied by several exercises.

Lesson ObjectivesAfter 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 conceptsand syntax elements in quick succession. It is very important that you proceed onesmall step at a time.

We highly recommend running all demonstrations in the system. Otherwise, theparticipants will not be able to complete the exercises.

The best approach is for you to create an empty program. First, define an empty localclass in the program and then build on it with each step.

However, remember to emphasize that the example you are implementing relates tothe graphics and the presentation in the lesson and that it differs from the programthe participants will use in the accompanying exercises.

This lesson is the key to understanding all further lessons about object-orientedprogramming in ABAP Objects. Make sure there are no unanswered questions.

Business ExampleYou want to the implement classes, objects, and associations of your model in ABAPObjects.

2005/Q4 © 2005 SAP AG. All rights reserved. 41

Page 52: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

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

Figure 33: Example of a Class

This above figure shows a vehicle as an example of a class. Using this example, wewill examine the individual concepts. The node on the left shows that the publiccomponents of the class can be accessed �from outside�. On the other hand, privateattributes of the class should not be accessible ��.

Figure 34: Defining Classes

42 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 53: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

A class is a set of objects that have the same structure and the same behavior. A classis therefore like a blueprint based on which all objects in that class are created.

All components of the class are defined in the definition part. The components areattributes, methods, events, constants, types, and implemented interfaces. Onlymethods are implemented in the implementation part.

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

Note: However, you can define local auxiliary classes for global classes.

Figure 35: Example of Attributes

Attributes contain the data that can be stored in the objects of a class. Class attributescan be one of three types: elementary, structured, or table-type. They can consist oflocal or global data types or reference types.

Examples of attributes for the class LCL_VEHICLE are:

MAKE Vehicle makeMODEL Type or modelSER_NO Serial numberCOLOR ColorMAX_SEATS Number of seatsR_MOTOR Reference to class LCL_MOTOR

2005/Q4 © 2005 SAP AG. All rights reserved. 43

Page 54: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 36: Definition of Attributes, Types, and Constants

In classes, you can only use the TYPE addition to refer to data types. You can onlyuse the LIKE reference for local data objects.

The READ-ONLY addition means that a public attribute that was declared with DATAcan 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.

With TYPE REF TO, an attribute can be typed as any reference. This will bediscussed in more detail later.

44 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 55: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Figure 37: Visibility Sections of Attributes

You can protect attributes against access from outside by characterizing them asprivate attributes. The private components of the class cannot be addressed directlyfrom 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 publiccomponents of a class are sometimes collectively known as the class's interface.

Using the private visibility section is also known as information hiding orencapsulation. In part, this is to protect the user of a class: Assume that the privatecomponents of a class are changed at some point, but its interface remains the same.All external users can only access their components through the interface of the class,and so can continue to work with the class as usual after the change is made. The userdoes not notice the change. Only the internal implementation was changed.

Conversely, if the public components of a class were incompatibly changed, everyoutside user would have to take these changes into account. You should therefore usepublic attributes very sparingly, or avoid making subsequent incompatible changes tothe public components of your classes altogether.

2005/Q4 © 2005 SAP AG. All rights reserved. 45

Page 56: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 38: Accessing Private Attributes

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

It is syntactically impossible to access private methods directly from outside.However, this is possible using public methods that output or change the attributes.The marginally higher runtime requirement (method calls in comparison with directvalue assignment) is taken into account to satisfy the encapsulation concept:

The signature of the public method clearly establishes which values must or can betransferred, and what types are to be assigned to them. This relieves the outsideuser of all responsibility. The method itself is only responsible for ensuring that allprivate attributes are dealt with consistently.

For this example, imagine that the MAKE and MODEL attributes are public. The riskwould be too large, since a user might forget to supply one of the two attributes orspecify two inconsistent attributes. Instead, you could use a public method SET_TYPEto ensure that values are specified for both attributes. A strict syntax check governsmethod calls to check that all obligatory parameters are transferred. It would evenbe possible for the method itself to perform a consistency check (to see if a certainvehicle 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 visibilitysection, but they must then be given the addition READ-ONLY.

46 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 57: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Figure 39: Comparison of Instance Attributes with Static Attributes

There are two kinds of attributes:

Instance attributesInstance attributes are attributes that exist once per object, that is, once perruntime instance of the class. They are defined with the syntax element DATA.

Static attributesStatic attributes exist once for each class and are visible for all runtime instancesin that class. They are defined with the syntax element CLASS-DATA.Static attributes usually contain information that applies to all instances, such as:

� Types and constants� Central application data buffers� Administrative information, such as the instance counter

Technical literature often refers to static attributes as class attributes (compare to theCLASS-DATA syntax element). In ABAP Objects, as in C++ and Java, the officialterm is static attribute.

2005/Q4 © 2005 SAP AG. All rights reserved. 47

Page 58: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

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

The graphic shows an example of how the static attribute N_O_VEHICLES is relatedto 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 thatinstances share their common attributes.

Caution: Here, an integer data object is defined in order to count theinstances. It is not possible to find out the number of created instances fromthe system.

48 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 59: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Figure 41: Syntax for Methods

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

Methods have a signature (interface parameters and exceptions) that enables themto receive values when they are called and pass values back to the calling program.Methods can have any number of IMPORTING, EXPORTING, and CHANGINGparameters. All parameters can be passed by value or reference.

One method return value can be defined using the RETURN parameter. It mustalways be transferred as a value. In this case, you cannot then define the EXPORTINGand CHANGING parameters. You can also use the RETURNING parameter to definefunctional methods. This will be discussed in more detail later.

All input parameters (IMPORTING and CHANGING parameters) can be defined asoptional parameters in the declaration using the OPTIONAL or DEFAULT additions.These parameters then do not necessarily have to be transferred when the objectis called. If you use the OPTIONAL addition, the parameter remains initializedaccording to type, whereas the DEFAULT addition allows you to enter a start value.

Like function modules, methods also support the return value SY-SUBRC, but onlyif the signature exceptions were defined using EXCEPTIONS. As of SAP WebAS 6.10, the RAISING addition can be used in its place to propagate class-basedexceptions. The caller then handles these class-based exceptions without evaluatingthe SY-SUBRC return value.

2005/Q4 © 2005 SAP AG. All rights reserved. 49

Page 60: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 42: Visibility Sections of Methods

Methods also have to be assigned to a visibility section. This determines whether themethods are called from outside the class or only from within the class. Thus, privatemethods only serve the purpose of internal modularization.

Figure 43: Accessing Private Methods

50 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 61: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

You define private methods in the PRIVATE SECTION of a class. You define publicattributes in the PUBLIC SECTION.

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

In this example, INIT_TYPE is a private method that is called by the public methodSET_TYPE. The instruction to initialize the attributes could exist in other contexts aswell, so the definition of this private �auxiliary method� is useful.

Note: This is an introductory example. Later, you will learn moreprogramming techniques for evaluating formal parameters.

Namespace: Within a class, attribute names, method names, event names, constantnames, type names, and alias names all share the same namespace. As withsubroutines and function modules, there is an additional local namespace withinmethods. This means that local declarations override those for the whole class.

Figure 44: Comparison of Instance Methods and Static Methods

Instance methods are defined using the syntax keyword METHODS.

Static methods are defined at class level. The restriction that only static componentscan be accessed applies in the implementation part. This means that static methodsdo not need instances, that is, they can be accessed directly through the class. Thiswill be discussed in more detail later. The methods are defined using the syntaxkeyword CLASS-METHODS.

In this example, only the static attribute N_O_VEHICLES can be accessed within thestatic method GET_N_O_VEHICLES. All other attributes of the class are instanceattributes and can only appear within instance methods.

2005/Q4 © 2005 SAP AG. All rights reserved. 51

Page 62: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Technical literature often refers to static methods as �class methods� (compare withthe CLASS-METHODS syntax element). In ABAP Objects, as in C++ and Java, theofficial term is static method.

Figure 45: Visibility Sections and UML Notation

A UML class diagram lists the class name first and class attributes and methods belowit. The visibility of components in a class is shown in UML using the characters + and-: Alternatively, public and private can prefix the method.

UML also allows manufacturers of modeling tools to create their own symbols forvisibility. Representation of visibility characteristics is optional and is normally onlyused 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 inparentheses after the method name. The types are always specified after a colon.

� For a function method, the method name and the parentheses are followed by theevent parameter, separated by a colon.

52 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 63: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Your demonstration program should now resemble the executable programSAPBC401_VEHICLE_MAIN_A.

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

Objects: Instances of ClassesYou could use classes to write complete applications by only using static components.However, the reasoning behind object-oriented programming is to create and workwith runtime instances of classes.

Figure 46: Overview of Class Instances

A class contains the generic description of an object and describes all characteristicsthat all objects of the class have in common. During the program runtime, the classis used to create discrete objects (instances) in the memory. This process is calledinstantiation. If this is the first time the class is accessed, the class is also loadedinto the memory.

2005/Q4 © 2005 SAP AG. All rights reserved. 53

Page 64: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Which values may be written into which attributes is irrelevant. Technically, theobject has an ID (in this case, 5) which is not accessible, however.

Example: Instantiation of class LCL_VEHICLE creates a vehicle object. The privateattributes still contain the technical initial values.

Figure 47: Definition of Reference Variables

DATA r_vehicle1 TYPE REF TO lcl_vehicle is used to definea reference variable, which is thereby typed as a pointer to objects of typelcl_vehicle. The null reference is the technical initial value of a referencevariable. (The pointer is pointing to nothing.)

54 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 65: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Figure 48: Creating Objects

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

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

2005/Q4 © 2005 SAP AG. All rights reserved. 55

Page 66: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Sometimes, experienced participants suggest using field symbols for this. If thishappens, it is a good opportunity to clarify the principal differences again.

It is important that you complete and discuss the exercises at the relevant stagesof this lesson. These are arranged so that each one prepares the way for the next.It can be especially motivating if you demonstrate the exercises for the participants,or have them demonstrate their exercises themselves. The topics covered here, andthe successful completion of the exercises, are very important for the remainder ofthe course!

Figure 50: Garbage Collector

Independent references are references that have not been defined within a class. TheGarbage Collector is a system routine that is automatically started whenever theruntime 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 isdeleted as well.

You can use the logical query IF r_obj IS INITIAL to determine whetherr_obj contains the null reference, in other words whether it does not point to anyobject.

56 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 67: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Do not spend more than 60 seconds discussing the Garbage Collector. Applicationdevelopers cannot influence it. Developers also do not have to work any differentlydepending on whether the Garbage Collector is running.

Some experienced participants refuse to accept that they can no longer have access toobjects if those objects' addresses have been lost.

Caution: The query for IS BOUND would also be possible here, but only makes adifference for data references. If you encounter a question on this, the answer is that inthe case of object references, you can work with both.

Figure 51: Reference Administration with Multiple Instantiation

The component selector -> displayed on the slide will be discussed later: Refer tothis preview!

2005/Q4 © 2005 SAP AG. All rights reserved. 57

Page 68: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

If you want to keep several objects from the same class in your program, you candefine an internal table that contains one column with the object references for thisclass. These objects can be administered in the internal table with the usual statementsfor internal tables such as APPEND, READ or LOOP.

To use logical conditions, the pseudo-component TABLE_LINE must be used whenyou use single-column internal tables. To do this, however, the relevant attributesneed to be public.

Figure 52: Example of Aggregation

During an aggregation, the WHEEL objects must be able to exist on their own, inother words independently of the vehicle. Independent references must therefore stillexist to them. This is indicated by the green arrows pointing to the WHEEL objects.

The objects in the class LCL_WHEEL have their own identity. They can be created inthis 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 desiredassociation.

58 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 69: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Your demonstration program should now resemble the executable programSAPBC401_VEHICLE_MAIN_B.

Here, the next exercise would be suitable for the airplane objects referenced in theinternal table.

Accessing Attributes and MethodsIn this section you learn how you can use classes and their instances. That is, you willlearn about the entire process, starting with the static connections of various instances,through to their practical effects.

Figure 53: Calling Methods

An object that requires the services of another object sends a message to the objectproviding the services. This message names the operation to be executed. Theimplementation 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 beused to exchange values.

2005/Q4 © 2005 SAP AG. All rights reserved. 59

Page 70: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

The example shows the shorter syntax for method calls (supported as of SAP WebAS 6.10) in which the CALL-METHOD prefix is omitted.

Figure 54: Calling Instance Methods: Syntax

Instance methods are called withCALL METHOD ref->method_name .... When calling an instance methodfrom within another instance method, you can omit the instance name ref. Themethod is automatically executed for the current object.

A shorter syntax is also supported as of SAP Web AS 6.10. In this case, CALLMETHOD is omitted and the parameters are listed in parentheses. There must be nospace before the parentheses, but there must be at least one after the parentheses.When you call a method that has only one import parameter, you can specify theactual parameter in the parentheses without any other additions. When you call amethod that only has import parameters, you can omit the EXPORTING addition.

The RECEIVING, IMPORTING, and CHANGING parameters are mutuallyexclusive. Please see the section about functional methods for more details.Otherwise, the same rules apply here as they do for calling a function module.

60 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 71: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

It is not worth making a big deal of the shorter syntax. It was introduced tomake 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 theexplicit syntax as well.

Figure 55: Calling Static Methods - Syntax

Static methods (also referred to as class methods) are called usingCALL METHOD classname=>method_name ....

Like static attributes, static methods are addressed with their class name, since theydo 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 aninstance method.

It is time to do the exercise for the method calls. It is better to do the sub-exerciseon the functional methods separately, in other words afterwards. Otherwise, theparticipants are bound to become confused and mix up all of the techniques.

2005/Q4 © 2005 SAP AG. All rights reserved. 61

Page 72: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 56: 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, passed by value.

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 methodcalls. The former are possible from the beginning (that is, as of SAP R/3 4.6A). Thelatter are only possible as of SAP Web AS 6.10.

62 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 73: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

The exercise step that handles functional methods should be performed on its own, inother words, as a separate step.

Figure 57: Functional Methods: Examples

In the first of these examples, two calls of functional instance methods representthe 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 RETURNINGparameter. The detailed syntax is as follows:

DATA number TYPE i.

...

CALL METHOD lcl_vehicle=>get_n_o_vehiclesRECEIVING re_count = number.

2005/Q4 © 2005 SAP AG. All rights reserved. 63

Page 74: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Figure 58: 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. Instanceattributes are accessed with ref->instance_attribute.

Your demonstration program should now resemble the executable programSAPBC401_VEHICLE_MAIN_C.

ConstructorsThere are two types of methods in ABAP Objects. They are generally not calledexplicitly with CALL METHOD (or the relevant short form), rather they are calledimplicitly. Constructors are the first type of method.

Some participants who have experiences with other object-oriented languages maystruggle at this point. In some of these languages, the constructor concept is useddifferently than in ABAP Objects. This may cause confusion.

Try to avoid this confusion because the concept is actually very simple.

64 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 75: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Figure 59: (Instance) Constructor

The constructor is a special instance method in a class and is always namedCONSTRUCTOR. This abbreviated term actually means the instance constructor.

The constructor is automatically called at runtime with the CREATE OBJECTstatement. 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 instancemethod that is automatically called from the memory immediately beforethe object is deleted.

(The corresponding comments in the SAP Library and the menu paths outsideof the ABAP Workbench are only contained in internal system calls.)

2005/Q4 © 2005 SAP AG. All rights reserved. 65

Page 76: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Unfortunately, they are not dynamically hidden. If they were, we would not need todeal with the participants' questions. Avoid any discussion about this topic.

Figure 60: Constructor: Example

For example, a constructor is necessary if, 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 resemble the executable programSAPBC401_VEHICLE_MAIN_D.

66 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 77: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Now you can perform the appropriate exercise for the constructors in this lesson. Theexercise for the static constructor should be done later.

Figure 61: Example of a Static Constructor

The static constructor is a special static method in a class and is always namedCLASS_CONSTRUCTOR. It is executed no more than once per program (and class).The static constructor is called automatically before the class is first accessed, butbefore 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:

� 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

2005/Q4 © 2005 SAP AG. All rights reserved. 67

Page 78: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

The exercise for the static constructor should be done here! It also has the advantagethat the participants finally get to grips with SQL accesses and learn that nothingchanges in terms of their SQL knowledge: How comforting!

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

Self-ReferenceIn 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 andonly there are they syntactically available.

Figure 62: Self-Reference

You can address an object itself by using the predefined reference variable ME withinits instance methods . Generally, you do not need to use the prefixme-> in such cases, but you may use it to improve readability.

68 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 79: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

However, it is required when you want to show a distinction between local dataobjects 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 actualparameter with EXPORTING or CHANGING.

Your demonstration program should now resemble the executable programSAPBC401_VEHICLE_MAIN_E.

This is a good time to include the fifth exercise of this lesson. You MUST completethis exercise, because a later lesson calls upon the private method to be developed here.Any participants who are particularly experienced can tackle the optional last exercisein this lesson!

2005/Q4 © 2005 SAP AG. All rights reserved. 69

Page 80: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

70 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 81: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

63 Exercise 2: Local ClassesExercise Duration: 45 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Declare local classes� Define attributes� Define and implement methods

Business ExampleYou are a developer for an airline corporation that owns several airline carriers. Startto develop an object-oriented program that can manage the airline carriers and theirairlines.

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

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.

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

2005/Q4 © 2005 SAP AG. All rights reserved. 71

Page 82: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

N_O_AIRPLANES (instance counter), data type I.

3. Define the public instance method SET_ATTRIBUTES for setting the privateinstance attributes.

Your signature should consist of two suitable import parameters that are definedas compatible with 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 displayingthe private instance attributes.

Implement the method in such a way that the values of the two instance attributesare output as an ABAP list. You can also output icons if the ICON type group isloaded.

Hint: To do this, use the statementTYPE-POOLS icon..

Note: Strictly speaking, to adhere to the delegation principle, the readingof the attribute values and their output should not be implemented in thesame method. However, do it here anyway because of time constraints.

5. Define the public static method DISPLAY_N_O_AIRPLANES to display theprivate static attribute.

Implement the method in such a way that the value of the static attributes isoutput in the ABAP list.

Note: So far, your class does not have a mechanism that ensures that theinstance counter is increased each time an object is created. It is up toyou to decide if you want to leave this out for now, or if you want totemporarily control the incrementation using the SET_ATTRIBUTESmethod.

72 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 83: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Solution 2: Local ClassesTask 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 availablein the SAP Library.

Model solution: SAPBC401_AIRS_MAIN_A

2. Create an include program and include it in your ZBC401_##_MAIN mainprogram.

Program name: ZBC401_##_AIRPLANE

(where ## is your two-digit group number). )

a) Carry out this step in the usual manner. Additional information is availablein 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) See the source code extract from the model solution.

2. 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) See the source code extract from the model solution.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 73

Page 84: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

3. Define the public instance method SET_ATTRIBUTES for setting the privateinstance attributes.

Your signature should consist of two suitable import parameters that are definedas compatible with the two attributes.

Implement the method in such a way that the two instance attributes are set.

a) See the source code extract from the model solution.

4. Define the public instance method DISPLAY_ATTRIBUTES for displayingthe private instance attributes.

Implement the method in such a way that the values of the two instance attributesare output as an ABAP list. You can also output icons if the ICON type group isloaded.

Hint: To do this, use the statementTYPE-POOLS icon..

Note: Strictly speaking, to adhere to the delegation principle, the readingof the attribute values and their output should not be implemented in thesame method. However, do it here anyway because of time constraints.

a) See the source code extract from the model solution.

5. Define the public static method DISPLAY_N_O_AIRPLANES to display theprivate static attribute.

Implement the method in such a way that the value of the static attributes isoutput in the ABAP list.

Note: So far, your class does not have a mechanism that ensures that theinstance counter is increased each time an object is created. It is up toyou to decide if you want to leave this out for now, or if you want totemporarily control the incrementation using the SET_ATTRIBUTESmethod.

a) See the source code extract from the model solution.

ResultSource code extract:

Continued on next page

74 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 85: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

SAPBC401_AIRS_MAIN_A

REPORT sapbc401_airs_main_a.

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.

ENDCLASS. "lcl_airplane DEFINITION

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 75

Page 86: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

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

* CLASS lcl_airplane IMPLEMENTATION *

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

CLASS lcl_airplane IMPLEMENTATION.

METHOD set_attributes.

name = im_name.

planetype = im_planetype.

* doesn’t make sense so much -

* only in order to get an effect

* after calling display_n_o_airplanes:

n_o_airplanes = n_o_airplanes + 1.

ENDMETHOD. "set_attributes

METHOD display_attributes.

WRITE: / icon_ws_plane AS ICON,

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

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

ENDMETHOD. "display_attributes

METHOD display_n_o_airplanes.

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

AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.

ENDMETHOD. "display_n_o_airplanes

ENDCLASS. "lcl_airplane IMPLEMENTATION

76 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 87: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

69 Exercise 3: ObjectsExercise Duration: 20 Minutes

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

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

Task 1:Define reference variables.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe 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 classLCL_AIRPLANE.

Task 2:Create airplane objects.

1. Create several instances of the local class LCL_AIRPLANE and buffer theirreferences into the internal table.

2. Follow the execution of the program in the ABAP Debugger.

2005/Q4 © 2005 SAP AG. All rights reserved. 77

Page 88: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Solution 3: ObjectsTask 1:Define reference variables.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise.

Define a reference variable for the instances of your class LCL_AIRPLANE.

a) Model solution: SAPBC401_AIRS_MAIN_B

b) See the source code extract from the model solution.

2. Define an internal table for buffering references to instances of the classLCL_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 theirreferences into the internal table.

a) See the source code extract from the model solution.

Continued on next page

78 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 89: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 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. For more information, refer tothe SAP Library.

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

2005/Q4 © 2005 SAP AG. All rights reserved. 79

Page 90: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

80 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 91: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

73 Exercise 4: Method CallsExercise Duration: 45 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Call non-functional methods� Define functional methods� Call functional methods

Business ExampleYou need to fill the attributes of the �empty� airplane objects with suitable values.

Task 1:Call the methods of your class.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise.

Call the static method DISPLAY_N_O_AIRPLANES twice: Once before andonce after the instantiations.

Caution: For reasons explained in the first exercise, you may not noticeany effects at the moment.

2. Use the SET_ATTRIBUTES method to set the attributes for all objects alreadycreated. Choose a unique name for the airplanes. When you are assigningairplane types, use the information in the SAPLANE table as a guide (forexample, '747-400'). Also use at least one invalid airplane type.

3. Display the attribute values in the ABAP list using the DISPLAY_ATTRIBUTESmethod.

Task 2:Add a functional method to your class.

1. In your class, define the public static functional method GET_N_O_AIR-PLANES. The signature must only consist of the result parameter RE_COUNT,which must be a whole number.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 81

Page 92: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

2. Call this method instead of DISPLAY_N_O_AIRPLANES and output the valuein the ABAP list.

82 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 93: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Solution 4: Method CallsTask 1:Call the methods of your class.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise.

Call the static method DISPLAY_N_O_AIRPLANES twice: Once before andonce after the instantiations.

Caution: For reasons explained in the first exercise, you may not noticeany effects at the moment.

a) Model solution: SAPBC401_AIRS_MAIN_C

b) See the source code extract from the model solution.

2. Use the SET_ATTRIBUTES method to set the attributes for all objects alreadycreated. Choose a unique name for the airplanes. When you are assigningairplane types, use the information in the SAPLANE table as a guide (forexample, '747-400'). Also use at least one invalid airplane type.

a) See the source code extract from the model solution.

3. Display the attribute values in the ABAP list using the DISPLAY_ATTRIBUTESmethod.

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_AIR-PLANES. The signature must only consist of the result parameter RE_COUNT,which must be a whole number.

a) See the source code extract from the model solution

2. Call this method instead of DISPLAY_N_O_AIRPLANES and output the valuein the ABAP list.

a) See the source code extract from the model solution.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 83

Page 94: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

ResultSource code:

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

Continued on next page

84 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 95: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

ENDLOOP.

* long syntax for functional call:

* CALL METHOD lcl_airplane=>get_n_o_airplanes

* RECEIVING

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 85

Page 96: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

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

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

ENDCLASS. "lcl_airplane IMPLEMENTATION

86 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 97: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

79 Exercise 5: ConstructorsExercise Duration: 45 Minutes

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

Business ExampleMake your program more realistic: The airplane objects receive their attributes assoon as they are created.

Task 1:Define an instance constructor.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise. (where ## is your two-digit group number). )

Define a reference variable with a suitable signature for the instances of yourclass LCL_AIRPLANE.

Implement it so that the two instance attributes are set and the instance counterN_O_AIRPLANES is increased by one.

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

Task 2:Create airplane objects.

1. Your CREATE OBJECT statements from the previous exercise should now besyntactically incorrect. Adapt and correct them.

2. If necessary, remove the calls of the SET_ATTRIBUTES method.

3. Follow the execution of the program in the ABAP Debugger.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 87

Page 98: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Task 3:Define and implement the static constructor

1. Define the LIST_OF_PLANETYPES internal table as a private class attribute.

To specify the type for this internal table, define the internal table (table types)Z_##_PLANETYPE in the ABAP Dictionary.

Use the PLANETYPE field as a key for the internal table.

2. Define the static constructor in the LCL_AIRPLANE class.

Implement the constructor in such a way that the LIST_OF_PLANETYPESinternal table is filled with all rows from the SAPLANE database table. You canuse the ARRAY FETCH technique for this purpose.

3. Check that the static constructor is called correctly and that the internal tableis filled in the main program. Where is the static constructor called in themain program?

88 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 99: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

Solution 5: ConstructorsTask 1:Define an instance constructor.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise. (where ## is your two-digit group number). )

Define a reference variable with a suitable signature for the instances of yourclass LCL_AIRPLANE.

Implement it so that the two instance attributes are set and the instance counterN_O_AIRPLANES is increased by one.

a) Model solution: SAPBC401_AIRS_MAIN_D

b) See the source code extract from the model solution.

2. If you previously used the SET_ATTRIBUTES method to increase the instancecounter, 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 besyntactically incorrect. Adapt and correct them.

a) See the source code extract from the model solution.

2. If necessary, remove the calls of the SET_ATTRIBUTES method.

a) See the source code extract from the model solution.

3. Follow the execution of the program in the ABAP Debugger.

a) Carry out this step in the usual manner. Additional information on theABAP Debugger is available in the SAP Library.

Task 3:Define and implement the static constructor

1. Define the LIST_OF_PLANETYPES internal table as a private class attribute.

To specify the type for this internal table, define the internal table (table types)Z_##_PLANETYPE in the ABAP Dictionary.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 89

Page 100: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Use the PLANETYPE field as a key for the internal table.

a) See the source code extract from the model solution.

2. Define the static constructor in the LCL_AIRPLANE class.

Implement the constructor in such a way that the LIST_OF_PLANETYPESinternal table is filled with all rows from the SAPLANE database table. You canuse the ARRAY FETCH technique for this purpose.

a) See the source code extract from the model solution.

3. Check that the static constructor is called correctly and that the internal table isfilled in the main program. Where is the static constructor called in the mainprogram?

a) Before the class is first accessed (before DISPLAY_N_O_AIRPLANES inthis case).

ResultSource code extract:

SAPBC401_AIRS_MAIN_D

REPORT sapbc401_airs_main_b.

TYPE-POOLS icon.

INCLUDE sapbc401_airs_d.

DATA: r_plane TYPE REF TO lcl_airplane.

plane_list TYPE TABLE OF REF TO lcl_airplane.

START-OF-SELECTION.

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

lcl_airplane=>display_n_o_airplanes( ).

CREATE OBJECT r_plane EXPORTING im_name = ’LH Berlin’

im_planetype = ’A321’.

APPEND r_plane TO plane_list.

Continued on next page

90 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 101: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

r_plane->display_attributes( ).

CREATE OBJECT r_plane EXPORTING im_name = ’LH Berlin’

im_planetype = ’747-400’.

APPEND r_plane TO plane_list.

r_plane->display_attributes( ).

CREATE OBJECT r_plane EXPORTING im_name = ’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.

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

CLASS-METHODS: display_n_o_airplanes.

PRIVATE SECTION.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 91

Page 102: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

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

DATA: name TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i.

CLASS-DATA: list_of_planetypes TYPE ty_planetypes. "itab type in Dic.

ENDCLASS.

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

* CLASS lcl_airplane IMPLEMENTATION *

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

CLASS lcl_airplane IMPLEMENTATION.

METHOD constructor.

name = im_name.

planetype = im_planetype.

n_o_airplanes = n_o_airplanes + 1.

ENDMETHOD. "constructor

METHOD class_constructor.

SELECT * FROM saplane INTO TABLE list_of_planetypes.

ENDMETHOD.

METHOD display_attributes.

WRITE: / icon_ws_plane AS ICON,

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

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

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

ENDCLASS. "lcl_airplane IMPLEMENTATION

92 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 103: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

85 Exercise 6: Private MethodsExercise Duration: 45 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Use the delegation principle� Structure and call private methods� Use the keyword ME

Business ExampleYou want to display the technical status data for an airplane.

Task 1:Declare another method.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise.

Within your LCL_AIRPLANE class, define the private static methodGET_TECHNICAL_ATTRIBUTES.

The signature must consist of the import parameter for the airplane type and thetwo export parameters for weight and tank capacity. Use the transparent tableSAPLANE as a guide for specifying the types of these formal parameters.

2. Implement the method in such a way that the values for the exportparameters can be determined by single-record access to the internal tableLIST_OF_PLANETYPES. Program a single-record access that worksefficiently!

Note: If the table does not contain any values for the airplane type, itshould be ignored for the time being.

Strictly speaking, the correct unit of measure should also be selectedand exported. However, time constraints mean that you do not needto do it in this exercise.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 93

Page 104: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Task 2:Call the method.

1. If possible, call the method GET_TECHNICAL_ATTRIBUTES from the mainprogram.

2. Call the method GET_TECHNICAL_ATTRIBUTES from the methodDISPLAY_ATTRIBUTES to obtain additional technical data. Enter thisadditional data in the calling method.

3. Follow the execution of the program in the ABAP Debugger.

4. Which alternative solutions could be used to solve the tasks?

Task 3: (optional)Create and handle an exception.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise.

If reading the airplane type in the method GET_TECHNICAL_ATTRIBUTESis not successful (SY-SUBRC <> 0), the exception WRONG_PLANETYPEshould be created.

To do this, use the EXCEPTION addition in the method interface.

The exception should be created or triggered using the RAISE command.

Note: This procedure has already been used in earlier SAP Releasesfor function modules and should be familiar.

At a later stage in this course, we will replace this older technique with amodern technique of exception handling using exception classes.

2. When you call the private method GET_TECHNICAL_ATTRIBUTES in thecalling method DISPLAY_ATTRIBUTES, this exception must now be declaredusing the EXCEPTIONS addition.

Continued on next page

94 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 105: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

If an exception occurs in GET_TECHNICAL_ATTRIBUTES, you can checkthis using the SY-SUBRC in the calling method. (Refer to the normal procedurefor function modules.)

In this exercise, the use of an incorrect airplane type when SY-SUBRC <> 0should simply be documented with a WRITE statement.

2005/Q4 © 2005 SAP AG. All rights reserved. 95

Page 106: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

Solution 6: Private MethodsTask 1:Declare another method.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise.

Within your LCL_AIRPLANE class, define the private static methodGET_TECHNICAL_ATTRIBUTES.

The signature must consist of the import parameter for the airplane type and thetwo export parameters for weight and tank capacity. Use the transparent tableSAPLANE as a guide for specifying the types of these formal parameters.

a) Model solution: SAPBC401_AIRS_MAIN_E

b) See the source code extract from the model solution.

2. Implement the method in such a way that the values for the exportparameters can be determined by single-record access to the internal tableLIST_OF_PLANETYPES. Program a single-record access that worksefficiently!

Note: If the table does not contain any values for the airplane type, itshould be ignored for the time being.

Strictly speaking, the correct unit of measure should also be selectedand exported. However, time constraints mean that you do not needto do it in this exercise.

a) See the source code extract from the model solution.

Task 2:Call the method.

1. If possible, call the method GET_TECHNICAL_ATTRIBUTES from the mainprogram.

a) If it is a private method, you cannot call it from the main program. This isonly possible for public methods.

Continued on next page

96 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 107: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

2. Call the method GET_TECHNICAL_ATTRIBUTES from the methodDISPLAY_ATTRIBUTES to obtain additional technical data. Enter thisadditional data in the calling method.

a) See the source code extract from the model solution.

3. Follow the execution of the program in the ABAP Debugger.

a) Carry out this step in the usual manner. Additional information on theABAP Debugger is available in the SAP Library.

4. Which alternative solutions could be used to solve the tasks?

Answer:

� Do not use the PLANETYPE import parameter.

The method can be defined as an instance method without animport parameter. This method then accesses the class attributeLIST_OF_PLANETYPES with ME->PLANETYPE.

� Do not use the method at all

In the method display_attributes, you can access the class attributeLIST_OF_PLANETYPES directly with ME->PLANETYPE.

Task 3: (optional)Create and handle an exception.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise.

If reading the airplane type in the method GET_TECHNICAL_ATTRIBUTESis not successful (SY-SUBRC <> 0), the exception WRONG_PLANETYPEshould be created.

To do this, use the EXCEPTION addition in the method interface.

The exception should be created or triggered using the RAISE command.

Note: This procedure has already been used in earlier SAP Releasesfor function modules and should be familiar.

At a later stage in this course, we will replace this older technique with amodern technique of exception handling using exception classes.

a) Model solution: SAPBC401_AIRS_MAIN_F

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 97

Page 108: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

2. When you call the private method GET_TECHNICAL_ATTRIBUTES in thecalling method DISPLAY_ATTRIBUTES, this exception must now be declaredusing the EXCEPTIONS addition.

If an exception occurs in GET_TECHNICAL_ATTRIBUTES, you can checkthis using the SY-SUBRC in the calling method. (Refer to the normal procedurefor function modules.)

In this exercise, the use of an incorrect airplane type when SY-SUBRC <> 0should simply be documented with a WRITE statement.

a) Refer to the model solution.

ResultSource code:

SAPBC401_AIRS_F

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

*& Include SAPBC401_AIRS_F *

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

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

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

CLASS-METHODS: class_constructor.

PRIVATE SECTION.

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

CLASS-METHODS: get_technical_attributes

Continued on next page

98 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 109: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Fundamental Object-Oriented Syntax Elements

IMPORTING im_type TYPE saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacity

EXCEPTIONS wrong_planetype.

DATA: name TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: list_of_planetypes TYPE ty_planetypes.

CLASS-DATA: n_o_airplanes TYPE i.

ENDCLASS. "lcl_airplane DEFINITION

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

* CLASS lcl_airplane IMPLEMENTATION *

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

CLASS lcl_airplane IMPLEMENTATION.

METHOD class_constructor.

SELECT * FROM saplane INTO TABLE list_of_planetypes.

ENDMETHOD. "class_constructor

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.

get_technical_attributes(

EXPORTING im_type = planetype

IMPORTING ex_weight = weight

ex_tankcap = cap

EXCEPTIONS wrong_planetype = 4 ).

WRITE: / icon_ws_plane AS ICON,

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 99

Page 110: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 1: Introduction to Object-Oriented Programming TAW10_3

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

IF sy-subrc <> 0.

WRITE: / icon_failure AS ICON, ’WRONG_PLANETYPE’.

ELSE.

WRITE: / ’weight of airplane’(003),

AT pos_1 weight LEFT-JUSTIFIED,

/ ’tankcapacity of airplane ’(004),

AT pos_1 cap LEFT-JUSTIFIED.

ENDIF.

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.

DATA: wa TYPE saplane.

READ TABLE list_of_planetypes INTO wa

WITH TABLE KEY planetype = im_type

TRANSPORTING weight tank capacity.

IF sy-subrc = 0.

ex_weight = wa-weight.

ex_tankcap = wa-tankcap.

ELSE.

RAISE wrong_planetype.

ENDIF.

ENDMETHOD. "get_technical_attributes

ENDCLASS. "lcl_airplane IMPLEMENTATION

100 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 111: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 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 InformationFurther information about this subject is available in the SAP Library and the ABAPkeyword documentation for the individual statements.

2005/Q4 © 2005 SAP AG. All rights reserved. 101

Page 112: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit Summary TAW10_3

Unit SummaryYou 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 simple class diagrams� Create simple object diagrams� Describe sequence diagrams� Define classes� Generate and delete objects� Access attributes� Call methods

102 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 113: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Test Your Knowledge

95Test Your Knowledge

1. The object-oriented programming model was developed considerably later thanthe procedural one. It offers more options for solving problems that previouslycould not be solved with purely procedural programming languages.Determine whether this statement is true or false.□ 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 instancecomponents?

2005/Q4 © 2005 SAP AG. All rights reserved. 103

Page 114: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Test Your Knowledge TAW10_3

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

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

104 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 115: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Test Your Knowledge

97Answers

1. The object-oriented programming model was developed considerably later thanthe procedural one. It offers more options for solving problems that previouslycould 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 foreach 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 canonly 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. It cancontain attribute and method definitions and can generally also contain theimplementations of methods.

Refer to the relevant section of the lesson

5. What is the difference between a class's static components and its instancecomponents?

Answer: You must access static components through the class. There are staticcomponents for each program and class no more than once in the memory. Anobject must be instantiated to access them.You must access instance components via the objects of this class. Any numberof instance components per program and class may be contained in the memory.

Refer to the relevant section of the lesson.

2005/Q4 © 2005 SAP AG. All rights reserved. 105

Page 116: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Test Your Knowledge TAW10_3

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

Answer: A class's constructor is a special method and is always namedCONSTRUCTOR. It is normally only called by the runtime system, wheneveran object of this class is created using CREATE OBJECT. Therefore, it isreferred 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.

106 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 117: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 299 Object-Oriented Concepts and

Programming Techniques

For more information, see the introductory instructor notes in the lesson.

Unit OverviewIn this unit you will learn about the fundamental concepts and programmingtechniques of ABAP Objects and other object-oriented languages such as Java or C++.

Unit ObjectivesAfter 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 inheritance� 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� Define polymorphism with reference to interfaces� Use cast assignments with interfaces to make generic calls� Define and trigger events� Handle events

2005/Q4 © 2005 SAP AG. All rights reserved. 107

Page 118: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

� Register and deregister event handling� Explain the key differences between explicit method calls and event-controlled

method calls

Unit ContentsLesson: Inheritance and Casting .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109

Exercise 7: Class Hierarchies .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .131Exercise 8: Polymorphism ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .141Exercise 9: Aggregation and Generic Calls. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .145

Lesson: Interfaces and Casting .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .153Exercise 10: Interface Implementation .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .171Exercise 11: Aggregation, Generic Calls, and Polymorphism .... . . . . . . . .185

Lesson: Events.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .193Exercise 12: Events in Superclasses .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .203Exercise 13: (Optional): Events in Interfaces .. . . . . . . . . . . . . . . . . . . . . . . . . . . . .217

108 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 119: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

Lesson:101

Inheritance and CastingLesson Duration: 160 Minutes

Lesson OverviewIn 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 devisedin the modeling process. Then you will learn to identify a number of interestingprogramming possibilities provided by inheritance.

Lesson ObjectivesAfter 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 inheritance� Use cast assignments with inheritance to make generic calls

The last part of this lesson is definitely the most important: Inheritance mustalways be used correctly. Inheritance relationships should not be defined betweensemantically unrelated classes simply to achieve technical advantages (such ascentralized maintenance, polymorphism, extensibility). Instead, inheritance mustalways derive from a generalization/specialization relationship that was recognizedas early as the modeling phase. This will allow you to benefit from the enhancedprogramming options.

As in the last lesson, the theory presented should be also be applied in a demo program.We also recommend that you start using the term signature at this point or earlier inthe course to refer to the parameters of a method. The term interface is used to meanseveral different things. Avoid using it as of the following lesson to avoid confusion.

Business ExampleYou want to implement generalization/specialization relationships from your modelin ABAP Objects.

2005/Q4 © 2005 SAP AG. All rights reserved. 109

Page 120: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Creating Generalization/Specialization RelationshipsUsing InheritanceSpecialization (UML) is a relationship in which one class (the subclass) inherits all themain characteristics of another class (the superclass). The subclass can also add newcomponents (attributes, methods, and so on) and replace the implementations withinherited methods. When the implantation is replaced, the method name in the UMLdiagram is renamed within the subclass.

Figure 63: Example of Generalization/Specialization

Specialization is an implementation relationship that emphasizes similaritiesbetween 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 inthe superclass. They also exist in all subclasses.

Specialization is often described as an �is a� relationship. In this example, you wouldsay �A truck is a (specific) vehicle.�

Reversing the point of view is referred to as generalization.

110 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 121: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

Figure 64: Characteristics of Generalization/Specialization

Generalization/specialization, if used properly, provides a significantly better structurefor your software because commonly used elements only need to be stored oncein a central location (in the superclass) and are then automatically available to allsubclasses. Changes made at a later stage have an immediate effect on the 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 whetherthe inherited components from the superclass are sufficient for the subclass or ifthey need to be extended. Generalization/specialization provides very strong linksbetween the superclass and the subclass.

When you develop additional subclasses, you often have to adapt the superclass aswell. Therefore, the creation of a subclass sometimes leads to additional requirementsfor the superclass, for example, when a subclass requires certain protected componentsor when the details of a superclass�s implementation are required to change the methodimplementations in subclasses. The developer of a (super)class cannot normallypredict everything that the subclasses will later require from the superclass.

2005/Q4 © 2005 SAP AG. All rights reserved. 111

Page 122: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Figure 65: Inheritance � Syntax

In ABAP Objects, an inheritance relationship is defined for a subclass using theINHERITING FROM addition, followed by the superclass that is directly above thesubclass. Inheritance hierarchies of varying complexity arise when this superclassinherits from another superclass above it. In contrast, there is no multiple inheritancein 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 specializationrelationships. A superclass is a generalization of its subclasses. The subclasses arein turn different specializations of their superclass. Thus, only additions or changesare permitted in ABAP Objects, which means that you can never remove anythingfrom a superclass in a subclass.

Inheritance is a one-sided relationship. In other words, subclasses recognize theirdirect superclasses but (super)classes do not recognize their subclasses. In the aboveexample, the subclass also contains the ESTIMATE_FUEL method. The subclassalso defines the GET_CARGO method.

112 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 123: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

Figure 66: Redefining Methods

Redefinition is when the implementation of an inherited instance method is changedfor the subclass without changing the signature. At the same time, the visibilitysection for the superclass must remain the same. Redefinition is not possible withoutthe PRIVATE SECTION.

When you use the REDEFINITION addition, you must specify a new implementationpart for the inherited method. As the signature may not be changed, you do not needto define the method parameters and exceptions again.

Within the redefined method�s implementation part, you can use the predefined prefixsuper->... to access components in the superclass directly above where youare working.You often need to do this when redefining a method to call the originalmethod of the superclass.

2005/Q4 © 2005 SAP AG. All rights reserved. 113

Page 124: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Figure 67: 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 68: The Constructor of a Subclass

In most cases, a redefinition as described for the methods above would not be usefulin the case of the constructor. Either the superclass�s constructor can be used withoutany need to change it, or the subclass can be expanded and other parameters will be

114 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 125: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

required in the constructor�s signature. In ABAP Objects, the constructor can only beoverwritten�� as part of inheritance. It can be overwritten in the sense that both thesignature and the implementation part can be adjusted in the subclass.

Hint: In this context, the concept of overloading is of relevance. Withoverloading, a method has several definitions with different signatures anddifferent implementations. Overloading is not supported in ABAP Objects.

The constructor of the direct superclass must be called within the constructor ofthe subclass. This is because of the specialization relationship: If a constructor wasdefined in the superclass, it contains implementations that will always be executedwhen an object is created in this superclass or its subclasses. However, this can onlybe automatically ensured by the runtime system if the subclass�s constructor was notchanged. In most cases, supplying consistent private attributes from the superclass isanother prerequisite to calling the superclass constructor.

In contrast to instance constructors, the static constructor in the superclass is calledautomatically. This means that the runtime system automatically ensures that thestatic constructors of all its superclasses have already been executed before the staticconstructor in a particular class is executed.

Figure 69: Rules for Calling the Constructor

2005/Q4 © 2005 SAP AG. All rights reserved. 115

Page 126: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

If a subclass has not changed its instance constructor, the constructor is left unchangedand is adopted from the superclass. The implementation is then executed from thesuperclass.

Figure 70: Inheritance and Visibility

Inheritance provides an extension of the visibility concept: There are protectedcomponents (PROTECTED SECTION). The visibility of these components liesbetween public and private. Protected components are visible to all subclasses andthe class itself.

When defining local classes in ABAP Objects, you must follow the syntacticalsequence of PUBLIC SECTION, PROTECTED SECTION, PRIVATE SECTION.

116 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 127: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

Figure 71: Protected Versus Private Section

The fact that all components of a superclass are available to the subclass is not relatedto the component�s visibility. A subclass also receives the private components of itssuperclass, however, these cannot be addressed in the syntax of the subclass. Privatecomponents of superclasses can only be addressed indirectly using public or protectedmethods from the superclass, which, in turn, can access the private attributes. Theserestrictions are necessary to ensure that centralized maintenance is possible.

In the above example, it is possible to access the protected attribute TANK insuperclass 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 ofLCL_VEHICLE is to use public methods.

Using the private visibility section, you can change superclasses without the need toknow the subclasses. As long as the changes you make do not affect the semantics,you do not need to adapt the subclasses. This is because they only indirectly accessthe private components from the superclass.

There is only one static component per program context.

Static components and inheritance

� A class that defines a public or protected static attribute shares this attributewith all its subclasses.

� Static methods cannot be redefined

2005/Q4 © 2005 SAP AG. All rights reserved. 117

Page 128: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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

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

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

Narrowing Cast (Upcast)Variables of the type �reference to superclass� can also refer to subclass instances atruntime.

118 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 129: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

Some relationships cannot be portrayed well in static diagrams. At this point, werecommend that you draw the following diagram by hand and hide the slides:

1. Draw the reference variable R_TRUCK (as an example) on the left.2. Write CREATE OBJECT r_truck ... above the reference variable.3. Draw the object display of a truck on the right and connect it to the reference

variable.4. Within this object, draw an area with a few inherited components.5. Draw another reference variable R_VEHICLE some distance below the first one.6. Write R_VEHICLE = R_TRUCK above the second reference variable and ask

the participants to tell you the contents of the second reference variable.7. 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 fromR_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 syntacticrestriction of the second reference variable. (The only reason why the inheritedcomponents can be accessed using the second variable is because the statictype is critical for the syntax check.)

Figure 72: Narrowing Cast With Object References

2005/Q4 © 2005 SAP AG. All rights reserved. 119

Page 130: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

If you assign a subclass reference to a superclass reference, this ensures that allcomponents that can be accessed syntactically after the cast assignment are actuallyavailable in the instance. The subclass always contains at least the same components asthe 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 superclassinstance. However, he 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 theinstance LCL_TRUCK can only be accessed using the reference R_VEHICLE.

If there are any restrictions regarding visibility, they are left unchanged. It is notpossible 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 isthus usually narrowed (or at least unchanged). That is why we describe this type ofassignment of reference variables as narrowing cast. There is a switch from a view ofseveral components to a view of a few components. The term upcast is also common.

Figure 73: 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 orLCL_TRUCK. In the ABAP Debugger, the dynamic type is specified in the formof the following object display.

120 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 131: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

object_id<\PROGRAM=program_name\CLASS=dynamic_type>

Note: Assignments between reference variables are possible whenever thestatic target variables are more general or equal to the dynamic sourcevariables.

Your demonstration program should now contain something that looks like theexecutable program SAPBC401_VEHICLE_MAIN_G. You should run your programin debugging mode.

Note: 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 easyto extend the vehicle management with new specific vehicles.

At this point, we recommend having the participants do the second exercise of thislesson. Strictly speaking, the exercise assumes some knowledge that will not betaught until the next paragraph, however this is unlikely to cause problems as manyparticipants have probably already programmed in the manner that is required here.For these participants, this exercise is obsolete in any case.

2005/Q4 © 2005 SAP AG. All rights reserved. 121

Page 132: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Figure 74: Generic Access After Narrowing Cast Assignments

A typical use for narrowing cast assignments is to prepare for generic access. A userwho is not at all interested in the finer points of the instances of the subclasses butwho simply wants to address the shared components could use a superclass referencefor this access.

In the example shown here, a travel agency (LCL_RENTAL) needs to manage allimaginable kinds of vehicles in one list. This leads to the question of what typesshould be assigned to the internal table for the references to airplane instances. Youshould also assume that the car rental company needs to be able to calculate only therequired amount of fuel for all its vehicles. Correspondingly, the ESTIMATE_FUELmethod is defined in the superclass LCL_VEHICLE and is redefined in all subclasses.

122 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 133: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

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

Objects of different classes can be stored in an internal table when these objects(LCL_BUS, LCL_TRUCK, and LCL_CAR in the above example) are specified astype superclass references (LCL_VEHICLE in the above example). The sharedcomponents of the subclass objects can then be uniformly accessed. For this example,the method ADD_VEHICLE is therefore needed. This copies the references to thevehicle types in this internal table. Its import parameter is already typed as thereference to the superclass.

Figure 76: Narrowing Cast and Generic Access in the Application Example

2005/Q4 © 2005 SAP AG. All rights reserved. 123

Page 134: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

In the above example, the narrowing cast assignment occurs when the vehiclereference is transferred to the formal parameter of the ADD_VEHICLE method. Theshared component is generically accessed within the loop around the internal tablecontaining all of the vehicle references. The ESTIMATE_FUEL method was inheritedfrom the LCL_VEHICLE superclass and may have been redefined.

Figure 77: Polymorphism: Generic Access Using the Superclass Reference

Which implementation is executed when ESTIMATE_FUEL is called now dependson which object the superclass reference R_VEHICLE currently refers to. Thedynamic type, not the static type, of the reference variable is used to search for theimplementation of a method. Therefore, when r_vehicle->estimate_fuelis called, the implementation is not executed from LCL_VEHICLE (static type ofR_VEHICLE) because the method was redefined in all vehicle classes.

When an instance receives a message to execute a particular method, the method thatimplemented the class of this instance is executed. If the class has not been redefinedin the method, the implementation from the superclass is executed.

When objects from different classes react differently to the same method calls, thisis known as polymorphism. The possibility of polymorphism is one of the mainstrengths of inheritance; a client can handle different classes uniformly, irrespective oftheir implementation. The runtime system searches for the correct implementation ofa method on behalf of the client.

124 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 135: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

Polymorphism can be used to write programs that are highly generic, that is, they donot need to be changed significantly if use cases are added. For instance, this wouldmake it very easy to add motorbikes to this example: You would simply define a newsubclass of LCL_VEHICLE which you could call LCL_MOTORBIKE. You wouldalso have to redefine the inherited method ESTIMATE_FUEL. Without needing anymore changes, your vehicle management system could then work with motorbikes andcalculate the required fuel levels for them.

Figure 78: 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 polymorphismthrough inheritance, this means that the source code is less self-explanatory and ismore susceptible to errors. For example, the syntax check can check that the functionmodel is called correctly, but not whether the internal table contains a valid functionmodule name for each vehicle.

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

2005/Q4 © 2005 SAP AG. All rights reserved. 125

Page 136: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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

Widening Cast (Downcast)Variables of the type �reference to superclass� can also refer to subclass instances atruntime. You may want to copy such a reference back to a suitable variable of the type�reference to subclass�.

At this point, we recommend that you add to your narrowing cast diagram and hidethe slides:

1. Draw another reference variable called R_TRUCK2 under R_VEHICLE.2. Write R_TRUCK2 ?= R_VEHICLE above the third reference variable and

discuss with the participants the need to use �?�. Then ask the participants whatthe content of the third reference variable is.

3. Draw an arrow from R_TRUCK2 to the object.

You must ask which components can be addressed with R_TRUCK2.

Figure 79: Widening Cast With Object References

126 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 137: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

If you want to assign a superclass reference to a subclass reference, you must usethe widening cast assignment operatorMOVE ... ?TO ... or its short form?=. Otherwise, you will get a message stating that it is not certain that all componentsthat can be accessed syntactically after the cast assignment are actually available in theinstance. As a rule, the subclass class contains more components than the superclass.

After assigning this type of reference back to a subclass reference to the implementingclass, clients are no longer limited to inherited components. In the example givenhere, all components of the LCL_TRUCK instance can be accessed again after theassignment using the reference R_TRUCK2.

The view is thus usually widened, or at least unchanged. That is why we describe thistype of assignment of reference variables as widening cast; there is a switch from aview of a few components to a view of more components. The term downcast isalso common.

Figure 80: Specific Access After Widening Cast Assignments

A typical use for widening cast assignments is when specific components of instancesneed to be addressed and their references are kept in variables that are typed on thesuperclass. A user who is interested in the finer points of the instances of a subclasscannot use the superclass reference for this access because it only allows access tothe shared components.

2005/Q4 © 2005 SAP AG. All rights reserved. 127

Page 138: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

In this example, a car rental company (LCL_RENTAL) wants to determine themaximum capacity of its trucks, but it stores all types of vehicle references in aninternal table that is typed as LCL_VEHICLE. Therefore, what happens if there is notruck reference in the superclass reference R_VEHICLE at runtime but the wideningcast assignment operator tries to copy the reference to the now invalid referenceR_TRUCK?

Figure 81: Widening Cast Assignment and Exception Handling in theApplication Example

In contrast to the narrowing cast assignment, it is possible that the static target variable(R_TRUCK) is neither more general than nor the same as the dynamic type of thesource variable (R_VEHICLE), namely when R_VEHICLE contains bus or sports carreferences. That is why with this kind of cast, the runtime system checks, before theassignment, whether the current content of the source variable corresponds to the typerequirements of the target variable. Otherwise, an exception that can be handled istriggered, and the original value of the target variable remains the same.

The exception of the error class CX_SY_MOVE_CAST_ERROR can be identifiedusing TRY-ENDTRY and the CATCH statement. Another way to prevent this runtimeerror would be to use runtime type identification (RTTI) classes. They can be used todetermine the dynamic type at runtime and to set a condition for the cast.

128 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 139: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

We recommend you do a separate demonstration to show the necessity of identifyingthe exception. You can use the program SAPBC401_VEHICLE_MAIN_I as thecopy template for this.

Note: You must refer to the specific lesson about the exception concept. Youdo not have enough time to discuss this topic now!

You can insert the optional exercise on the widening cast at this point. However, youmust provide a precise description of the tasks involved.

Using InheritanceThis final section does not examine whether or not inheritance should be used as aprogramming technique over a number of alternatives. As early as the modelingphase, you should be able to see whether there is a generalization/specializationrelationship between certain classes. If there is, you can use inheritance to representthis in ABAP Objects.

Figure 82: Using Inheritance

If this is the case, you need to adhere to the relevant concepts of inheritance. Forexample, the semantics must be preserved when you redefine methods. Furthermore,inherited components must be used as intended in the superclass.

2005/Q4 © 2005 SAP AG. All rights reserved. 129

Page 140: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Figure 83: Examples: Misuse of Inheritance

If you do not correctly understand the formulation �is a (specific),� you run the riskof identifying the wrong places in which to use inheritance. Sometimes the need foranother 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 most, there are some cars that have not beenpainted. Therefore, every car needs the attribute color, assuming that it is relevantto the application. Therefore, the attribute should already have been defined in thesuperclass, or there is no longer an authorization for subclasses of this type. Therewould also be contradictions with reality when you try to implement a method forpainting the cars.

Note: Such attributes are often also defined as reference variables to asuperclass of role classes. There is one description class for each role. Tochange the role of an instance, exchange the references to the correspondingrole description instances. Specialist literature also refers to this as a �roledesign pattern�.

In some cases, specialization relationships are identified that do not allow for thesemantics to be preserved.

For example, the class Square inherits from the class Rectangle. If you try to definemethods for the rectangle that change the width and height separately, these methodswould not make sense when applied to the square. Even if the methods were redefinedto make the lengths of the sides uniform, the semantics would be different.

For the same reasons, simple inheritance of the source text � that is, using inheritanceonly because some required functions were found in a (super)class � is also impossible.

130 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 141: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

121 Exercise 7: Class HierarchiesExercise Duration: 60 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Define subclasses� Redefine superclass methods in subclasses� Effectively use visibility sections

Business ExampleYour airplane management program is to be further refined. Put specific airplanes inrelation to their general airplane class.

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

1. Complete your program ZBC401_##_MAIN (where ## is your two-digit groupnumber) or copy the program SAPBC401_CASS_MAIN_E. )

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 sametype as the table field SFLIGHT-SEATSMAX.

3. Define and implement an instance constructor that assigns values to all instanceattributes in the class.

4. Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayedusing the WRITE statement.

Task 2:In the class LCL_AIRPLANE, define the local subclass LCL_CARGO_PLANE forcargo planes.

1. The class must have a private instance attribute, MAX_CARGO, with the sametype as the table field SCPLANE-CARGOMAX.

2. Define and implement an instance constructor that assigns values to all instanceattributes in the class.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 131

Page 142: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

3. Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayedusing the WRITE statement.

4. Define the functional method GET_CARGO to return the cargo value to thecalling program. Use the formula parameter RE_CARGO.

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

2. Call the static method DISPLAY_N_O_AIRPLANES (before instantiating anyobjects).

3. Use the two references to create an instance of each of the subclassesLCL_PASSENGER_PLANE and LCL_CARGO_PLANE. Decide for yourselfhow 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.

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

2. Could the method GET_TECHNICAL_ATTRIBUTES be called directly fromthe redefined method DISPLAY_ATTRIBUTES of the subclasses?

132 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 143: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

Solution 7: Class HierarchiesTask 1:In the class LCL_AIRPLANE, define the local subclass LCL_PASSENGER_PLANEfor passenger planes.

1. Complete your program ZBC401_##_MAIN (where ## is your two-digit groupnumber) or copy the program SAPBC401_CASS_MAIN_E. )

If applicable, enter the source code for your new class in the include program.

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

b) Model solution: SAPBC401_INHS_MAIN_A

2. The class must have a private instance attribute, MAX_SEATS, with the sametype as the table field SFLIGHT-SEATSMAX.

a) Refer to the model solution.

3. Define and implement an instance constructor that assigns values to all instanceattributes in the class.

a) Refer to the model solution.

4. Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayedusing the WRITE statement.

a) Refer to the model solution.

Task 2:In the class LCL_AIRPLANE, define the local subclass LCL_CARGO_PLANE forcargo planes.

1. The class must have a private instance attribute, MAX_CARGO, with the sametype as the table field SCPLANE-CARGOMAX.

a) Refer to the model solution.

2. Define and implement an instance constructor that assigns values to all instanceattributes in the class.

a) Refer to the model solution.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 133

Page 144: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

3. Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayedusing the WRITE statement.

a) Refer to the model solution.

4. Define the functional method GET_CARGO to return the cargo value to thecalling program. Use the formula parameter RE_CARGO.

a) Refer to the model solution.

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

a) Refer to the model solution.

2. Call the static method DISPLAY_N_O_AIRPLANES (before instantiating anyobjects).

a) Refer to the model solution.

3. Use the two references to create an instance of each of the subclassesLCL_PASSENGER_PLANE and LCL_CARGO_PLANE. Decide for yourselfhow to fill the attributes.

a) Refer to the model solution.

4. Call the DISPLAY_ATTRIBUTES method for both instances.

a) Refer to the model solution.

5. Call the static method DISPLAY_ATTRIBUTES a second time.

a) Refer to the model solution.

Task 4:Analyze your program.

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

a) Carry out this step in the usual manner.

2. Could the method GET_TECHNICAL_ATTRIBUTES be called directly fromthe redefined method DISPLAY_ATTRIBUTES of the subclasses?

Answer: No, because the component of the superclass is private.Continued on next page

134 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 145: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

ResultModel solution:

SAPBC401_INHS_MAIN_A

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

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 135

Page 146: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

SAPBC401_INHS_A

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

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

PRIVATE SECTION.

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

METHODS: get_technical_attributes

IMPORTING im_type TYPE saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacity

DATA: name TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i.

ENDCLASS. "lcl_airplane DEFINITION

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

* CLASS lcl_airplane IMPLEMENTATION *

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

CLASS lcl_airplane IMPLEMENTATION.

Continued on next page

136 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 147: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

METHOD constructor.

name = im_name.

planetype = im_planetype.

n_o_airplanes = n_o_airplanes + 1.

ENDMETHOD. "constructor

METHOD display_attributes.

DATA: weight TYPE saplane-weight,

cap TYPE saplane-tankcap.

WRITE: / icon_ws_plane AS ICON,

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

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

get_technical_attributes( EXPORTING im_type = planetype

IMPORTING ex_weight = weight

ex_tankcap = cap ).

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

’Tank capacity:’(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

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 137

Page 148: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

*

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

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.

METHODS: get_cargo RETURNING VALUE(re_cargo) TYPE scplane-cargomax.

PRIVATE SECTION.

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

DATA: max_cargo TYPE scplane-cargomax.

ENDCLASS. "lcl_cargo_plane DEFINITION

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

* CLASS lcl_cargo_plane IMPLEMENTATION

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

*

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

CLASS lcl_cargo_plane IMPLEMENTATION.

METHOD constructor.

CALL METHOD super->constructor( im_name = im_name

im_planetype = im_planetype ).

max_cargo = im_cargo.

ENDMETHOD. "constructor

METHOD display_attributes.

super->display_attributes( ).

WRITE: / ’Max Cargo = ’, max_cargo.

ULINE.

ENDMETHOD. "display_attributes

METHOD get_cargo.

re_cargo = max_cargo.

ENDMETHOD. "get_cargo

Continued on next page

138 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 149: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

ENDCLASS. "lcl_cargo_plane IMPLEMENTATION

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

* CLASS lcl_passenger_plane DEFINITION

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

*

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

CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..

PUBLIC SECTION.

METHODS: constructor IMPORTING im_name TYPE string

im_planetype TYPE saplane-planetype

im_seats TYPE sflight-seatsmax.

METHODS: display_attributes REDEFINITION.

PRIVATE SECTION.

DATA: max_seats TYPE sflight-seatsmax.

ENDCLASS. "lcl_passenger_plane DEFINITION

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

* CLASS lcl_passenger_plane IMPLEMENTATION

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

*

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

CLASS lcl_passenger_plane IMPLEMENTATION.

METHOD constructor.

CALL METHOD super->constructor( EXPORTING im_name = im_name

im_planetype = im_planetype ).

max_seats = im_seats.

ENDMETHOD. "constructor

METHOD display_attributes.

super->display_attributes( ).

WRITE: / ’Max Seats = ’, max_seats.

ULINE.

ENDMETHOD. "display_attributes

ENDCLASS. "lcl_passenger_plane IMPLEMENTATION

2005/Q4 © 2005 SAP AG. All rights reserved. 139

Page 150: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

140 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 151: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

131 Exercise 8: PolymorphismExercise Duration: 20 Minutes

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

Business ExampleYour airplane management program should display the attributes of the airplaneobjects generically: that is, it should be open to future extensions with additionalairplane classes.

Task 1:Buffer the airplane references in a suitable type of internal table.

1. Complete your ZBC401_##_MAIN program or copy the sample solution fromthe previous exercise. (## is your two-digit group number).

2. In your main program, define an internal table for buffering airplane referencesif you do not already have one. The row type of the internal table should beREF TO LCL_AIRPLANE.

Task 2:Display the attributes of all airplane types that have been 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 theDISPLAY_ATTRIBUTES method every time the loop runs.

Task 3:Analyze your program.

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 141

Page 152: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

2. What would happen if the method DISPLAY_ATTRIBUTES had not beenredefined in the subclasses?

142 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 153: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

Solution 8: PolymorphismTask 1:Buffer the airplane references in a suitable type of internal table.

1. Complete your ZBC401_##_MAIN program or copy the sample solution fromthe previous exercise. (## is your two-digit group number).

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

b) Model solution: SAPBC401_CASS_MAIN_A

2. In your main program, define an internal table for buffering airplane referencesif you do not already have one. The row type of the internal table should beREF TO LCL_AIRPLANE.

a) See the source code extract from the model solution.

Task 2:Display the attributes of all airplane types that have been created so far.

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

a) See the source code extract from the model solution.

2. Program a loop through the contents of the internal table. Call theDISPLAY_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 thecall of the DISPLAY_ATTRIBUTES method.

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

2. What would happen if the method DISPLAY_ATTRIBUTES had not beenredefined in the subclasses?

Answer: The implementation from the superclass would be executed. Yourprogram would not contain polymorphism.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 143

Page 154: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

ResultSource code:

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

144 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 155: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

135 Exercise 9: Aggregation and Generic CallsExercise Duration: 45 Minutes

Exercise ObjectivesAfter 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 ExampleThe management of airplane instances should no longer take place in the mainprogram. Instead, it should be encapsulated in a new class for airlines.

System DataSystem: will be assignedClient: will be assignedUser ID: will be assignedPassword: will be assignedSet up instructions: No special settings if you are using a standard SAP WebAS 6.20 system

Task 1:Define a local class for airlines.

1. From the include program SAPBC401_CAST_B, copy the portions of thesource text for the local class LCL_CARRIER into your include programZBC401_##_AIRPLANE so that you can add to them there (## is your two-digitgroup number).

2. Extend the signature and implementation of the ADD_AIRPLANE methodso that the airplane references can be added to the previously defined listAIRPLANE_LIST.

3. Extend the implementation of the DISPLAY_AIRPLANES method so that theattributes of all airplanes of the airline can be added to the list. Each time anairplane is added, its DISPLAY_ATTRIBUTES method should be called.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 145

Page 156: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

4. Extend the implementation of the DISPLAY_ATTRIBUTES method so that allof the attributes of the airline can be displayed and, consequently, the contents ofthe airplane list can also be displayed.

Task 2:In the main program, create an airline instance. Transfer some airplane referencesto it and display the attributes.

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

2. In the main program, define a suitably typed reference variable for your newairline class.

3. Using the reference, generate an instance of your class LCL_CARRIER. Decidefor yourself how to fill the attributes.

4. Call the ADD_AIRPLANE method to transfer the airplane instances that havebeen created so far to the airline. You may also create and transfer additionalairplanes.

5. Display the attributes of the airline by calling its methodDISPLAY_ATTRIBUTES.

Task 3:Optional exercise: Determining the highest cargo value.

1. Define and implement the functional method GET_HIGHEST_CARGO inclass LCL_CARRIER to calculate the highest cargo value (load capacity) of allcargo planes. Use the Widening Cast technique to identify all relevant airplanesfor this task.

2. For testing purposes, this new method can be called withinDISPLAY_ATTRIBUTES of class LCL_CARRIER.

146 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 157: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

Solution 9: Aggregation and Generic CallsTask 1:Define a local class for airlines.

1. From the include program SAPBC401_CAST_B, copy the portions of thesource text for the local class LCL_CARRIER into your include programZBC401_##_AIRPLANE so that you can add to them there (## is your two-digitgroup number).

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

b) Model solution: SAPBC401_CASS_MAIN_B

2. Extend the signature and implementation of the ADD_AIRPLANE methodso that the airplane references can be added to the previously defined listAIRPLANE_LIST.

a) See the source code extract from the model solution.

3. Extend the implementation of the DISPLAY_AIRPLANES method so that theattributes of all airplanes of the airline can be added to the list. Each time anairplane is added, its DISPLAY_ATTRIBUTES method should be called.

a) See the source code extract from the model solution.

4. Extend the implementation of the DISPLAY_ATTRIBUTES method so that allof the attributes of the airline can be displayed and, consequently, the contents ofthe 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 referencesto it and display the attributes.

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

a) See the source code extract from the model solution.

2. In the main program, define a suitably typed reference variable for your newairline class.

a) See the source code extract from the model solution.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 147

Page 158: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

3. Using the reference, generate an instance of your class LCL_CARRIER. Decidefor yourself how to fill the attributes.

a) See the source code extract from the model solution.

4. Call the ADD_AIRPLANE method to transfer the airplane instances that havebeen created so far to the airline. You may also create and transfer additionalairplanes.

a) See the source code extract from the model solution.

5. Display the attributes of the airline by calling its methodDISPLAY_ATTRIBUTES.

a) See the source code extract from the model solution.

Task 3:Optional exercise: Determining the highest cargo value.

1. Define and implement the functional method GET_HIGHEST_CARGO inclass LCL_CARRIER to calculate the highest cargo value (load capacity) of allcargo planes. Use the Widening Cast technique to identify all relevant airplanesfor this task.

a) Refer to the model solution.

2. For testing purposes, this new method can be called withinDISPLAY_ATTRIBUTES of class LCL_CARRIER.

a) Refer to the model solution.

ResultSource code extract:

SAPBC401_CASS_MAIN_C

REPORT sapbc401_cass_main_c.

TYPE-POOLS icon.

INCLUDE sapbc401_cass_c.

DATA: r_plane TYPE REF TO lcl_airplane,

Continued on next page

148 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 159: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

r_cargo TYPE REF TO lcl_cargo_plane,

r_passenger TYPE REF TO lcl_passenger_plane,

r_carrier TYPE REF TO lcl_carrier.

START-OF-SELECTION.

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

***** Create Carrier ********************************************

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

***** Passenger Plane ********************************************

CREATE OBJECT r_passenger EXPORTING

im_name = ’LH BERLIN’

im_planetype = ’747-400’

im_seats = 345.

***** cargo Plane ************************************************

CREATE OBJECT r_cargo EXPORTING

im_name = ’US HErcules’

im_planetype = ’747-500’

im_cargo = 533.

***** insert planes into itab if client ***************************

r_carrier->add_airplane( r_passenger ).

r_carrier->add_airplane( r_cargo ).

***** show all airplanes inside carrier ***************************

r_carrier->display_attributes( ).

SAPBC401_CASS_C

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

*& Include SAPBC401_CASS_C *

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

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

* CLASS lcl_airplane DEFINITION *

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 149

Page 160: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

...

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

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

get_highest_cargo RETURNING value(re_cargo)

TYPE s_plan_car.

PRIVATE SECTION.

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

DATA: name TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane.

ENDCLASS. "lcl_carrier DEFINITION

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

* CLASS lcl_carrier IMPLEMENTATION

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

CLASS lcl_carrier IMPLEMENTATION.

METHOD add_airplane.

APPEND im_plane TO airplane_list.

ENDMETHOD. "add_airplane

METHOD display_attributes.

DATA: highest_cargo TYPE s_plan_car.

WRITE: icon_flight AS ICON, name . ULINE. ULINE.

display_airplanes( ).

highest_cargo = ME->get_highest_cargo( ).

WRITE: / ’ Highest Cargo = ’, highest_cargo.

ENDMETHOD. "display_attributes

Continued on next page

150 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 161: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Inheritance and Casting

METHOD display_airplanes.

DATA: r_plane TYPE REF TO lcl_airplane.

LOOP AT airplane_list INTO r_plane.

r_plane->display_attributes( ).

ENDLOOP.

ENDMETHOD. "display_airplanes

METHOD constructor.

name = im_name.

ENDMETHOD. "constructor

METHOD get_name.

ex_name = name.

ENDMETHOD. "get_name

METHOD get_highest_cargo.

DATA: r_cargo TYPE REF TO lcl_cargo_plane.

DATA: r_plane TYPE REF TO lcl_airplane.

DATA: cargo TYPE s_plan_car.

DATA: r_exc TYPE REF TO cx_root.

LOOP AT airplane_list INTO r_plane.

TRY.

"**** her comes the optimistical coding *******

r_cargo ?= r_plane.

cargo = r_cargo->get_cargo( ).

IF re_cargo < cargo.

re_cargo = cargo.

ENDIF.

CATCH cx_sy_move_cast_error INTO r_exc. "*** no cargoplaine

ENDTRY.

ENDLOOP.

ENDMETHOD.

ENDCLASS. "lcl_carrier IMPLEMENTATION

2005/Q4 © 2005 SAP AG. All rights reserved. 151

Page 162: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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 inheritance� Use cast assignments with inheritance to make generic calls

Related InformationFor more information about this subject, refer to the SAP Library and the ABAPkeyword documentation for the individual statements.

152 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 163: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

Lesson:143

Interfaces and CastingLesson Duration: 120 Minutes

Lesson OverviewThe only real difference between interfaces and inheritance is the role they play. Theprogramming advantages are thus the same as for inheritance.

Lesson ObjectivesAfter 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� Define polymorphism with reference to interfaces� Use cast assignments with interfaces to make generic calls

Although there are no significant technical differences between regular inheritanceand the implementation of interfaces, this topic is still covered in this separate lesson.That means you can use this lesson without having previously explained inheritance.

The first section is the most important because it deals precisely with these differences.

We have created the last section for the sake of completeness. In other words, it servesto build on the analogy with regular inheritance rather than presenting significantnew programming techniques.

In this lesson, you must make a clear distinction between the terms signature andinterface. Otherwise, you will confuse the participants.

Business ExampleYou want to implement client/server relationships in combination with generic accessfrom your model in ABAP Objects.

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

2005/Q4 © 2005 SAP AG. All rights reserved. 153

Page 164: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

From a technical point of view, interfaces are simply superclasses that cannot beinstantiated, 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 offer � that is, implement � these services in differentways, but keep the same semantics. Interfaces contain no implementations.

In ABAP Objects, the same components can generally be defined in interfaces and inclasses. To recognize the semantic differences from regular inheritance, concentrateon the following, typical use cases.

Figure 84: Central Definition of Shared Components

For example, you want to allow for the option of having multiple classes implementinga service in different ways, but using the same method names and with a uniformsignature. With regular inheritance, you would define such a method in the sharedsuperclass. However, if you cannot siutably model a superclass for inheritance, youneed to define an interface and then define this method there. Therefore, you cancompare this case with a generalization relationship with a superclass.

154 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 165: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

Figure 85: The Client Defines the Protocol

Compared to regular inheritance, the distribution of roles is sometimes different:The user generally defines the interfaces. In the interfaces, the user describes (bothtechnically and semantically) the services that he wants the providers to offer. Eachclass can now decide for itself whether it serves the interface, that is, actuallyoffers the services defined there. Therefore, this case is similar to a specializationrelationship with a subclass.

As with regular inheritance, access to these services is usually generic, that is, it usesa reference that is typed on the interface. As with regular inheritance, you can thusperform polymorphism with interfaces.

2005/Q4 © 2005 SAP AG. All rights reserved. 155

Page 166: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Figure 86: Interfaces in UML Notation

In UML, interfaces are represented in the same way as classes. However, in addition totheir name, they have the stereotype «interface». The use of an interface is representedby 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 adotted arrow from the class to the interface.

The similarity with representing a generalization/specialization relationship isjustified, as we have just described.

Creating Generalization/Specialization RelationshipsUsing InterfacesIn 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, allcomponents of an interface are public.

Note: Note: The areas of use for interfaces as the uniform interface foroffering services.

156 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 167: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

Figure 87: Defining and Implementing an Interface

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

The slide above was included because the participants are likely to have problemswith interfaces. This slide shows the perfect recipe for defining and implementinginterfaces. Explain to the participants that the interface is defined in the first step,made known in the classes in the second step, and, in the third step, the interfacemethods are implemented in the classes. Following this procedure (in the exercisesalso) makes things much easier. You should discuss the procedure several times.

Point out that the interface will only be used at a later stage.

Do the first exercise and explain that the relatively large scope of the preparatoryprogramming (which brings together the two submodels) is required in order to have aclear starting point. In the second part of the exercise, the participants implement theprocedure shown on the slide discussed above.

2005/Q4 © 2005 SAP AG. All rights reserved. 157

Page 168: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

The merging of the two submodels can also be put to a positive use: It is likely thatmost participants will not have previously experienced how easy it can be to jointotally independent applications using object-oriented programming.

The background here is the semantic context in terms of the interface to be defined.

Classes implement interfaces as follows:

� The interface name is listed in the definition part of the class with theINTERFACES statement. This must be in the PUBLIC SECTION, that is,interfaces can only be implemented publicly.

� 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 theimplementing class by prefixing the interface name followed by a tilde (~) (theinterface resolution operator).

interface_name~component_name

To simplify access to interface components, you can use alias names. These canonly appear in the definition part of a class or in the interface definition. Their use issubject 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 be addressed with the shorter formref->a_1.

158 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 169: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

Figure 88: Addressing Interface Components Using Object References

Interface components can only be accessed by using an object reference whose classimplements the interface. Syntactically, this takes place with the interface resolutionoperator ~, just as with access to the interface components in the implementationpart of the class.

Alternately, you can use the alias names defined in the implementing class for theinterface components. Even if shared components of the implementing classes aresubsequently transferred to the interface, access to these components does not need tobe adapted. However, the source code would then be less self-explanatory becauseyou 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 hereis rarely used. At this point, the completeness of the explanation is what matters. Thenext section shows you actually work with interfaces.

Polymorphism with InterfacesBecause interfaces cannot be instantiated, an interface reference can only refer toinstances of classes that have implemented the interface. Therefore, if you wantto perform polymorphism with interfaces, you must use narrowing cast to copy areference to the reference variable that was typed with the interface, just as withregular inheritance.

2005/Q4 © 2005 SAP AG. All rights reserved. 159

Page 170: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Some relationships cannot be portrayed well in static diagrams. At this point, werecommend that you draw the following diagram by hand and hide the slides:

1. Draw the reference variable R_RENTAL (as an example) on the left side.2. Write CREATE OBJECT r_rental ... above the reference variable.3. Draw the object display of a car rental company on the right side and connect

it to the reference variable.4. Within this object, draw an area with a few implemented interface components.5. Draw another reference variable R_PARTNER at some distance below the first

one.6. Write R_PARTNER = R_RENTAL above the second reference variable and ask

the participants to specify the content of the second reference variable.7. 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_PARTNERto the object.

You must ask which components are addressed with R_PARTNER.

In contrast, in the following graphic we want to indicate the syntactic restrictionof the second reference variable. (Using the second variable, you can thereforeonly access the implementing interface components can because the static typeis critical for the syntax check.)

Figure 89: Narrowing Cast with Interface References

160 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 171: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

If the class has implemented the interface, it is certain that all components that can beaccessed 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. Theprefixing 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 andCHECK_AVAILABILITY of the interface LIF_PARTNER can only be accessed afterassigning the reference variable R_PARTNER. It is not possible to access the specificcomponents of the instance from class LCL_RENTAL (GET_NAME in the aboveexample) using the reference variable R_PARTNER.

The view is thus usually narrowed, or at least unchanged, which is why we describethis type of assignment of reference variables as narrowing cast. There is a switchfrom a view of several components to a view of a few components. The term upcastis also common.

Figure 90: 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 thatimplement the interface but who simply wants to address the components defined inthe interface, could use an interface reference for this access.

In the example shown above, a travel agency (LCL_TRAVEL_AGENCY) needs tomanage all the various kinds of business partner in one list. The row type of theinternal table must therefore be typed as the reference to the interface LIF_PARTNER.

2005/Q4 © 2005 SAP AG. All rights reserved. 161

Page 172: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

The travel agency only wants to request the services in order to display theirattributes and to check availability. The relevant methods DISPLAY_PARTNERand CHECK_AVAILABILITY are defined in the interface LIF_PARTNER andimplemented in all business partner classes.

Objects of different classes (LCL_HOTEL, LCL_RENTAL, and LCL_CARRIER)can be kept in an internal table, typed with interface references (LIF_PARTNER). Thecomponents defined in the interface can then be accessed uniformly.

For this example, method ADD_PARTNER is therefore needed. This copies thereferences to all the kinds of business partner in this internal table. Its importparameter is already typed as the reference to the interface.

Figure 91: Polymorphism: Generic Access Using the Interface Reference

Polymorphism can also be performed for interfaces. Interface references can be usedto call methods, whereby different implementations can be executed depending on theobject of the reference.

The dynamic type and not the static type of the reference variable is used to search forthe implementation of a method. In the above example, r_partner->display_partner() therefore uses the class of the instance to which r_partner actually refers in order tosearch for the implementation of display_partner. It does not, for example, use thestatic type for r_partner (which is always REF TO lif_partner).

162 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 173: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

The implementation that is now executed when DISPLAY_PARTNER is calleddepends 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 isknown 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 behalfof the client.

Polymorphism can be used to write programs that are highly generic, that is, they donot 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 rentaladdition. The relevant class � for example, with the name LCL_SHIPPING �would simply have to implement the interface LIF_PARTNER and thus the methodDISPLAY_PARTNER defined there. Business partner management could then easilyinclude shipowning companies and also request them to display their attributes.

Your demonstration program should now resemble the executable programSAPBC401_VEHICLE_MAIN_K. You should run your program in debugging mode.

At this point, we recommend having the participants do the second exercise of thislesson.

Note: If the participants have already done this type of exercise as part ofinheritance, reduce the next exercise to a simple recapitulation.

In terms of programming, there are no new ideas.

2005/Q4 © 2005 SAP AG. All rights reserved. 163

Page 174: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

At this point, we recommend that you add to your narrowing cast diagram and hidethe slides:

1. Draw a reference variable R_RENTAL2 below R_PARTNER.2. WriteR_RENTAL2 ?= R_PARTNER above the third reference variable and

discuss with the participants the necessity of including the �?�. Then ask theparticipants what the content of the third reference variable is.

3. Draw an arrow from R_RENTAL2 to the object.

You must ask which components are addressed with R_RENTAL2.

Figure 92: Widening Cast Assignment and Exception Handling

If you want to assign an interface reference to a class reference where the class hasimplemented the interface, you must use the widening cast assignment operatorMOVE ... ?TO ... or its short form ?=. Otherwise, the system would returna message stating that it is not certain that all components that can be accessedsyntactically after the cast assignment is 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 implementingclass at runtime. After assigning this type of reference (back) to a reference to theimplementing class, clients are no longer limited to interface components. In theexample given here, all components of the LCL_CARRIER instance can be accessedagain after the assignment using reference R_CARRIER.

164 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 175: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

The view is thus usually widened, or at least unchanged, which is why we describethis type of assignment of reference variables as widening cast. There is a switchfrom a view of a few components to a view of more components. The term downcastis also common.

A typical area of use for widening cast assignments is when specific componentsof instances need to be addressed whose references are kept in variables that aretyped on the interface. A user who is interested in the finer points of instances ofimplementing classes cannot use the interface reference for this access because thisonly allows access to the interface components. In the example here, a travel agency(LCL_TRAVEL_AGENCY) needs to book a flight but keeps all the various businesspartner 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 referenceR_PARTNER at runtime but the widening cast assignment operator is used to copythe reference to the then invalid reference R_CARRIER? In contrast to narrowing castassignment, it is possible that the static type of the target variable (R_CARRIER) isneither more general than nor the same as the dynamic type of the source variable(R_PARTNER), specifically if 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 requirementsof the target variable. Otherwise, an exception that can be handled is triggered, andthe original value of the target variable remains the same. This exception of errorclass CX_SY_MOVE_CAST_ERROR can be identified using TRY-ENDTRY andthe CATCH statement.

Another way of preventing this runtime error would be to use runtime typeidentification (RTTI) classes. They can be used to determine the dynamic type atruntime and to set a condition for the cast.

Assignments between interface reference variables, whose typing interfaces are notrelated to each other, cannot be checked statically and must therefore be performedusing widening cast. With such an assignment, the system checks at runtime whetherthe class of the instance to which the source reference refers also supports the interfacewith which the target reference is typed.

We recommend you do a separate demonstration to show the necessity of identifyingthe exception.

Note: You must refer to the specific lesson about the exception concept. Youdo not have enough time to discuss this topic now.

2005/Q4 © 2005 SAP AG. All rights reserved. 165

Page 176: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Interface HierarchiesWe have already seen several times that an interface implementation stronglyresembles regular inheritance. We therefore need to ask what the interface counterpartof hierarchical inheritance looks like. We want to explain interface hierarchies usingan application example.

Compound interfaces are only discussed here as a preview of what is covered later inthe course. Do not spend too much time on this topic at this stage.

Figure 93: Interface Hierarchy in the Application Example

In this example, we need to know whether it would be useful to define a furtherservice �room reservation� in the interface LIF_PARTNER. In this case, the classesLCL_CARRIER and LCL_RENTAL would have to implement the appropriatemethod because they have integrated the interface LIF_PARTNER. However,implementation of a room reservation � keeping the same semantics � is not possiblefor airlines or car rental companies.

However, because there are several other business partner types for which animplementation would be useful (for example, motels and hotels), the method needs tobe centrally defined and not defined individually for motels and hotels. On the otherhand, the option of easily extending the model with other accommodation providertypes (for example, guesthouse) must be retained.

166 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 177: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

Figure 94: 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 includedinterface. It represents an extension of the included interface.

The including interface is known as a compound interface. An included interfacerepresents a component of another interface and is therefore known as a componentinterface. An elementary interface does not itself contain other interfaces.

The UML notation corresponds to the implementation of an elementary interfaceby a class.

2005/Q4 © 2005 SAP AG. All rights reserved. 167

Page 178: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Figure 95: Definition and Implementation of Compound Interfaces: Syntax

As with regular inheritance, the implementing class only needs to list the compoundinterface in order to integrate all components. Nevertheless, the components of thecomponent interfaces keep their original names:

component_interface_name~component_name

They are therefore not prefixed by the name of the compound interface.

All implementations of methods from all higher-level interfaces must take place inthe first implementing class. Alias names are suitable for short-form syntax whenaccessing components from different interfaces. You can get a central documentaryview of all components with the definition of these alias names in the implementingclass.

168 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 179: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

Figure 96: Addressing Components in Compound Interfaces: Syntax

The same possibilities apply for accessing its components from a compound interfaceand for cast assignments.

Figure 97: Using Interfaces

Interfaces are used to describe protocols for using components without connectinga kind of implementation. An intermediate layer is introduced between the clientand the server to protect the client from the explicit server, thereby making the clientindependent.

2005/Q4 © 2005 SAP AG. All rights reserved. 169

Page 180: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Interfaces enable different classes to be handled uniformly, providing theyimplemented the interfaces. As with inheritance, you can also perform polymorphismusing interface reference variables.

As with regular inheritance, the definition of an interface means an abstraction of theimplementing classes to a specific partial aspect.

Multiple inheritance can be simulated using interfaces: If several interfaces areincluded, all components are available to all of these interfaces. All methods must beimplemented.

170 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 181: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

159 Exercise 10: Interface ImplementationExercise Duration: 45 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Define interfaces� Implement interfaces

Business ExampleYou now need to add a vehicle management procedure to your airplane managementprogram. The airlines and car rental companies then need to be abstracted to businesspartners; that is, they need to offer general services using an abstract interface.

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 ZBC401_##_MAIN program or copy the programSAPBC401_CASS_MAIN_B (where ## is your two-digit group number).

2. From the include program SAPBC401_VEHT_F, copy the portions of the sourcecode for the local classes LCL_VEHICLE, LCL_TRUCK, LCL_BUS, andLCL_RENTAL into a new include program ZBC401_##_VEHICLE to extendthem there if necessary (## is your two-digit group number). Include this newinclude program in your main program.

3. From program SAPBC401_VEHT_MAIN_A, copy the portions of the sourcecode for the generation of the instances and for the method calls into your mainprogram to extend them there if necessary.

4. To test your work so far, call the DISPLAY_ATTRIBUTES method for the carrental company. The list should now display all airplanes of your airline and allvehicles of your car rental company.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 171

Page 182: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Task 2:Define and implement an interface to offer general services from business partners.

1. Remove the calls of the DISPLAY_ATTRIBUTES method from your mainprogram again.

Note: You need to store the relevant list outputs as a general service.

Caution: You will not receive any immediate output on the list.

2. If necessary, add an interface LIF_PARTNERS to your UML diagram. Thisneeds to define a DISPLAY_PARTNER method. Draw the relationships to theclasses LCL_RENTAL and LCL_CARRIER.

3. Define the local interface LIF_PARTNERS and the methodDISPLAY_PARTNER.

Hint: Include the portions of the source code needed for this inyour main program in an appropriate order with the remaining classdefinitions.

4. Implement the interface in the classes LCL_CARRIER and LCL_RENTAL. Youneed to display a business partner�s attributes in such a way that they call theirown DISPLAY_ATTRIBUTES methods.

172 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 183: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

Solution 10: Interface ImplementationTask 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 ZBC401_##_MAIN program or copy the programSAPBC401_CASS_MAIN_B (where ## is your two-digit group number).

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

b) Model solution: SAPBC401_INTS_MAIN_A

2. From the include program SAPBC401_VEHT_F, copy the portions of the sourcecode for the local classes LCL_VEHICLE, LCL_TRUCK, LCL_BUS, andLCL_RENTAL into a new include program ZBC401_##_VEHICLE to extendthem there if necessary (## is your two-digit group number). Include this newinclude program in your main program.

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

3. From program SAPBC401_VEHT_MAIN_A, copy the portions of the sourcecode for the generation of the instances and for the method calls into your mainprogram to extend them there if necessary.

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

4. To test your work so far, call the DISPLAY_ATTRIBUTES method for the carrental company. The list should now display all airplanes of your airline and allvehicles of your car rental company.

a) See the source code extract from the model solution.

Task 2:Define and implement an interface to offer general services from business partners.

1. Remove the calls of the DISPLAY_ATTRIBUTES method from your mainprogram again.

Note: You need to store the relevant list outputs as a general service.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 173

Page 184: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Caution: You will not receive any immediate output on the list.

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

2. If necessary, add an interface LIF_PARTNERS to your UML diagram. Thisneeds to define a DISPLAY_PARTNER method. Draw the relationships to theclasses LCL_RENTAL and LCL_CARRIER.

a) Ask your instructor if you have any questions.

3. Define the local interface LIF_PARTNERS and the methodDISPLAY_PARTNER.

Hint: Include the portions of the source code needed for this inyour main program in an appropriate order with the remaining classdefinitions.

a) See the source code extract from the model solution.

4. Implement the interface in the classes LCL_CARRIER and LCL_RENTAL. Youneed to display a business partner�s attributes in such a way that they call theirown DISPLAY_ATTRIBUTES methods.

a) Refer to the model solution.

ResultSource code extract:

SAPBC401_INTS_MAIN_A

REPORT sapbc401_ints_main_a.

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,

Continued on next page

174 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 185: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

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

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.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 175

Page 186: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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 s_capacity

RETURNING value(re_avgfuel) TYPE s_consum.

METHODS constructor IMPORTING im_make TYPE string.

METHODS display_attributes.

METHODS set_make IMPORTING im_make TYPE string.

METHODS get_make EXPORTING ex_make TYPE string.

CLASS-METHODS get_count EXPORTING re_count TYPE i.

PRIVATE SECTION.

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

DATA: make TYPE string.

METHODS init_make.

CLASS-DATA: n_o_vehicles TYPE i.

Continued on next page

176 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 187: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

ENDCLASS. "lcl_vehicle DEFINITION

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

* CLASS lcl_vehicle IMPLEMENTATION

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

CLASS lcl_vehicle IMPLEMENTATION.

METHOD get_average_fuel.

re_avgfuel = im_distance / im_fuel.

ENDMETHOD. "get_average_fuel

METHOD constructor.

make = im_make.

ADD 1 TO n_o_vehicles.

ENDMETHOD. "constructor

METHOD set_make.

IF im_make IS INITIAL.

init_make( ). " me->init_make( ). also possible

ELSE.

make = im_make.

ENDIF.

ENDMETHOD. "set_make

METHOD init_make.

make = ’default make’.

ENDMETHOD. "init_make

METHOD get_make.

ex_make = make.

ENDMETHOD. "get_make

METHOD display_attributes.

WRITE: make.

ENDMETHOD. "display_attributes

METHOD get_count.

re_count = n_o_vehicles.

ENDMETHOD. "get_count

ENDCLASS. "lcl_vehicle IMPLEMENTATION

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 177

Page 188: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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

* CLASS lcl_truck DEFINITION

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

CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.

PUBLIC SECTION.

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

METHODS: constructor IMPORTING im_make TYPE string

im_cargo TYPE s_plan_car.

METHODS display_attributes REDEFINITION.

METHODS get_cargo RETURNING value(re_cargo) TYPE s_plan_car.

PRIVATE SECTION.

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

DATA: max_cargo TYPE s_plan_car.

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

ENDCLASS.

Continued on next page

178 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 189: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

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

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

ENDMETHOD. "constructor

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

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

CLASS lcl_rental DEFINITION.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 179

Page 190: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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.

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

* CLASS lcl_rental IMPLEMENTATION

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

CLASS lcl_rental IMPLEMENTATION.

METHOD lif_partners~display_partner.

display_attributes( ).

ENDMETHOD.

METHOD constructor.

name = im_name.

ENDMETHOD. "constructor

METHOD add_vehicle.

APPEND im_vehicle TO vehicle_list.

ENDMETHOD. "add_vehicle

METHOD display_attributes.

DATA: r_vehicle TYPE REF TO lcl_vehicle.

WRITE: / icon_transport_proposal AS ICON, name.

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

LOOP AT vehicle_list INTO r_vehicle.

r_vehicle->display_attributes( ).

ENDLOOP.

ENDMETHOD. "display_attributes

ENDCLASS. "lcl_rental IMPLEMENTATION

Continued on next page

180 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 191: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

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.

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

INTERFACES lif_partners.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 181

Page 192: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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.

Continued on next page

182 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 193: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

ex_name = name.

ENDMETHOD. "get_name

ENDCLASS. "lcl_carrier IMPLEMENTATION

2005/Q4 © 2005 SAP AG. All rights reserved. 183

Page 194: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

184 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 195: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

173 Exercise 11: Aggregation, Generic Calls,and PolymorphismExercise Duration: 45 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Create aggregation relationships between classes� Program narrowing cast assignments� Use inheritance relationships for polymorphic method calls

Business ExampleYou now need to add a user class to your program. Travel agencies need to managevarious business partners using the interface and access the business partners� generalservices.

Task 1:Define a local class for travel agencies.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise (## is your two-digit group number.)

2. If necessary, add a class to your UML diagram LCL_TRAVEL_AGENCY thatuses the interface LIF_PARTNERS.

3. From program SAPBC401_VEHT_B, copy the portions of the source code forthe local class LCL_TRAVEL_AGENCY into your main program or one of yourinclude programs to extend them there.

4. Add to the row type of the internal table PARTNER_LIST so that references tothe business partners that have implemented your interface can be buffered.

5. Add to the signature and implementation of method ADD_PARTNER so thatbusiness partner references can be added to the list PARTNER_LIST.

6. Add to the implementation of method DISPLAY_AGENCY_PARTNERS sothat the attributes of all the travel agency�s business partners can be added to thelist. The centrally provided method DISPLAY_PARTNER needs to be called foreach business partner.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 185

Page 196: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Task 2:In the main program, generate a travel agency instance, transfer the references to theairline and car rental company to this instance, and add the attributes.

1. In the main program, define a suitably typed reference variable for your newtravel 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 generatedairline and car rental company instances to the travel agency.

4. Add the attributes of the travel agency by calling its methodDISPLAY_AGENCY_PARTNERS.

186 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 197: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

Solution 11: Aggregation, Generic Calls,and PolymorphismTask 1:Define a local class for travel agencies.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise (## is your two-digit group number.)

a) Carry out this step in the usual manner. For more information, refer tothe SAP Library.

b) Model solution: SAPBC401_INTS_MAIN_B

2. If necessary, add a class to your UML diagram LCL_TRAVEL_AGENCY thatuses the interface LIF_PARTNERS.

a) Ask your instructor if you have any questions.

3. From program SAPBC401_VEHT_B, copy the portions of the source code forthe local class LCL_TRAVEL_AGENCY into your main program or one of yourinclude programs to extend them there.

a) Carry out this step in the usual manner. For more information, refer tothe SAP Library.

4. Add to the row type of the internal table PARTNER_LIST so that references tothe business partners that have implemented your interface can be buffered.

a) See the source code extract from the model solution.

5. Add to the signature and implementation of method ADD_PARTNER so thatbusiness partner references can be added to the list PARTNER_LIST.

a) See the source code extract from the model solution.

6. Add to the implementation of method DISPLAY_AGENCY_PARTNERS sothat the attributes of all the travel agency�s business partners can be added to thelist. The centrally provided method DISPLAY_PARTNER needs to be called foreach business partner.

a) See the source code extract from the model solution.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 187

Page 198: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Task 2:In the main program, generate a travel agency instance, transfer the references to theairline and car rental company to this instance, and add the attributes.

1. In the main program, define a suitably typed reference variable for your newtravel agency class.

a) See the source code extract from the model solution.

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

a) See the source code extract from the model solution.

3. Call the method ADD_PARTNER to transfer the references to the generatedairline and car rental company instances to the travel agency.

a) See the source code extract from the model solution.

4. Add the attributes of the travel agency by calling its methodDISPLAY_AGENCY_PARTNERS.

a) See the source code extract from the model solution.

ResultSource code:

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,

Continued on next page

188 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 199: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

r_rental TYPE REF TO lcl_rental,

r_truck TYPE REF TO lcl_truck,

r_bus TYPE REF TO lcl_bus.

START-OF-SELECTION.

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

***** Create TRAVEL_AGENCY **************************************

CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’.

***** Create CARRIER ********************************************

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

...

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 189

Page 200: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

...

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

* CLASS lcl_rental DEFINITION

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

*

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

CLASS lcl_rental DEFINITION.

PUBLIC SECTION.

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

METHODS: constructor IMPORTING im_name TYPE string.

METHODS add_vehicle IMPORTING im_vehicle

TYPE REF TO lcl_vehicle.

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

TYPE REF TO lif_partners.

METHODS display_agency_partners.

PRIVATE SECTION.

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

Continued on next page

190 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 201: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Interfaces and Casting

DATA: name TYPE string,

partner_list TYPE TABLE OF REF TO lif_partners.

ENDCLASS. "lcl_travel_agency DEFINITION

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

* CLASS lcl_travel_agency IMPLEMENTATION

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

*

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

CLASS lcl_travel_agency IMPLEMENTATION.

METHOD display_agency_partners.

DATA: r_partner TYPE REF TO lif_partners.

WRITE: icon_dependents AS ICON, name.

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

ULINE.

ULINE.

LOOP AT partner_list INTO r_partner.

r_partner->display_partner( ).

ENDLOOP.

ENDMETHOD. "display_agency_partners

METHOD constructor.

name = im_name.

ENDMETHOD. "constructor

METHOD add_partner.

APPEND im_partner TO partner_list.

ENDMETHOD. "add_partner

ENDCLASS. "lcl_travel_agency IMPLEMENTATION

2005/Q4 © 2005 SAP AG. All rights reserved. 191

Page 202: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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� Define polymorphism with reference to interfaces� Use cast assignments with interfaces to make generic calls

Related InformationFor more information, refer to the SAP Library.

192 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 203: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

Lesson:181

EventsLesson Duration: 75 Minutes

Lesson OverviewThis lesson provides a general introduction to the concept of events in objectorientation, followed by an explanation of all related modeling aspects and syntaxelements. The Registration section contains the information that is probably mostimportant to understand the topic.

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

Note: This application example used here does not specify that the events aredefined in superclasses or interfaces.

Therefore, before you look at the first graphic about the event concept, you could alsostart the course by turning the approach around and having the participants discusswhich class should do the defining and triggering and which should do the handling.Assuming that the participants have understood the inheritance concept, they shouldbe able to come up with the solution themselves. The same applies to the optionalexercise in which participants define the event in the interface.

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

Event-Controlled Method CallsBesides attributes and methods, classes � and their instances � can contain a third typeof 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.

2005/Q4 © 2005 SAP AG. All rights reserved. 193

Page 204: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Figure 98: Event-Controlled Method Calls

Given the right circumstances, handler methods can react to the triggering of thisevent. This means that the runtime system may call these handler methods after theevent has been triggered. In other words, the handler method is not usually calleddirectly by the client.

This results in a completely different modeling concept: While you are developing theclass that triggers the event, you do not need to know anything about the class that ishandling it. The triggering class sends a specific message to all classes of the runningprogram (and, if need be, their instances). At the time of development, it is completelyunclear 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 benarrowed down; however, which, if any, of these results actually will occur can onlybe determined after the event has been triggered.

An event can have exporting parameters, which means that, in contrast to the explicitmethod call, the calling program determines the protocol.

In this application example, after an instance in the �vehicle� class is created, ittriggers the event �vehicle created.� This event is received by different instances andis processed differently by each one. The rental car company considers purchasing avehicle, the vehicle registration office registers the car, and so on.

Caution: Do not confuse this concept of events in object-orientedprogramming with events in the ABAP runtime system(LOAD-OF-PROGRAM, START-OF-SELECTION, and so on). Also, do notconfuse it with background processing or workflow control.

194 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 205: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

Figure 99: Event Handling in a UML Class Diagram

In UML class diagrams, a dotted arrow with the stereotype «handlesEventOf» pointsfrom the handling class to the triggering class. The event definition and signatureonly appear implicitly in the handling class within the handler method. The handlermethods are separated from the other methods using the stereotype «eventHandler».

Triggering and Handling EventsThe following summarizes all of the required programming steps for event-controlling.

Figure 100: Triggering and Handling Events: Overview

2005/Q4 © 2005 SAP AG. All rights reserved. 195

Page 206: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

Keep in mind that depending on the status of your application, you may not need toprogram all steps. The separation of cause and effect in your programming should bereflected in the way you construct complex applications. Often, the event is alreadytriggered and all you have to do is create another event handler.

Figure 101: Defining and Triggering Events: Syntax

Within a class, instance events are defined using the EVENTS statement, while staticevents 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. Onlystatic events can be triggered in static methods.

When an event is triggered, the handler methods that are registered to this event arecalled in sequence. Of course, these handler methods can trigger more events oftheir own.

196 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 207: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

Figure 102: Handling Events: Syntax

Instance events or static methods can be defined within a class to handle events. To doso, you must specify the event (FOR EVENT) and the class or interface in which theevent was defined (OF).

If the event contains exporting parameters and you want to be able to addressthese syntactically, you must specify the exporting parameters immediately afterIMPORTING in the definition of the method. The handler method�s signature canconsist of no more than the exporting parameters of the associated event. Theparameters are typed by the handler method during the definition of the event. Theobject that triggers the event determines the protocol.

In addition to the explicitly defined exporting parameters, the predefined importingparameter SENDER can always be listed. By using this parameter, you can place areference to the event-trigger object into the handler method.

Therefore, handler methods are usually called by triggered events (RAISE EVENT);however, they can also be called explicitly (CALL METHOD).

Registering for EventsThe definition of the handler method only specifies how and to which event of whichclass the method will react. At runtime, it needs to be determined which possiblereactions will actually take place and when each of these will happen.

2005/Q4 © 2005 SAP AG. All rights reserved. 197

Page 208: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

When triggering instance events, you also have to specify what event the reaction willtrigger. If instance methods are set to carry out the reaction, you also have to specifywhich instance(s) will perform the reaction.

The most common mistake in relation to event control 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 withoutthe registration, so that you can show that the registration is a necessary step.

Figure 103: Registering Event Handling

These specifications are collectively known as registration. The registration isalways carried out using the trigger. When the event is triggered, the runtime uses thetrigger registrations 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 carrental class, and the vehicle registration class. However, you can only predeterminewhich car rental instances and vehicle registration instances will react to whichvehicle instance, and when they will do so.

Registrations can also be revoked.

198 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 209: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

Figure 104: Registering Event Handling: Syntax

Events are registered using the SET HANDLER statement. Registration is only activeat program runtime.

With instance events, FOR is followed by the reference to the object that triggers theevent. Alternately, you can also use the addition ALL INSTANCES. That way, youcan also register objects that have not yet been created.

The additionACTIVATION ’X’ is optional during registration. To undo the registration, useACTIVATION 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 ... .

2005/Q4 © 2005 SAP AG. All rights reserved. 199

Page 210: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

If several methods were registered to one event, the sequence in which the eventhandler methods are called is not defined: that is, there is no guaranteed sequence inwhich the event handler methods are called.

If a new event handler is registered within an event handler method for an event thathas just been triggered, this event handler is added to the end of the sequence and isalso executed when in turn. If an existing event handler is deregistered in an eventhandler method, this handler is deleted from the event handler method sequence.

Figure 105: Registration/Deregistration: Handler Tables

Every object or class that has defined events has an internal table: the handlertable. All handler methods that are registered to the various events are listed withinthe table. For instance methods, the handler table also contains references to theregistered objects.

Objects that are registered for event handling are not deleted by the garbage collectorif there are no remaining references to them.

Your demonstration program should now resemble the executable programSAPBC401_VEHICLE_MAIN_L. You should run your program in debugging mode.

200 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 211: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

Visibility Sections in Event HandlingEvents are 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 determines who is authorized to handle the event.

PUBLICAll

PROTECTEDCan only be handled by users within that class or its subclasses

PRIVATECan only be handled within its class

� The visibility of a handler method controls who is authorized to register themethod, that is, the locations where the SET HANDLER statement may beprogrammed.

PUBLICAnywhere in the program

PROTECTEDCan be handled by users within that class or its subclasses

PRIVATECan only be handled within its class

Event handler methods can only have the same visibility or more restricted visibilitythan the events to which they refer.

Our experience shows that some participants are worried when they finish this lesson,as they feel that event control makes it difficult to follow the program flow by lookingat the source code. If these concerns are voiced, repeat the characteristics of the eventconcept and its advantages from the beginning of the lesson. Then point out thesignificance of modeling and the diagrams.

2005/Q4 © 2005 SAP AG. All rights reserved. 201

Page 212: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

202 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 213: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

191 Exercise 12: Events in SuperclassesExercise Duration: 40 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Define and trigger events� Handle events� Register event handling

Business ExampleAirplane and vehicle references are to be included in the airline and the car rentalcompanies� lists. This process is to be event-controlled.

Task 1:Define an event for the creation of an airplane. Trigger and handle it so that thereference to the airplane is entered into the airline�s list of airplanes.

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

2. Remove the calls of the ADD_AIRPLANE method from your main program.

Note: The entry of an airplane reference into the airline�s list is to beevent-controlled.

3. Identify the class that is suitable for triggering the event and the classes thatshould be used for handling the event. Use your UML diagram if necessary.

If applicable, illustrate the relationships in your UML diagram.

4. Define the public event AIRPLANE_CREATED and trigger it in the classLCL_AIRPLANE using a suitable method.

5. Change the method ADD_AIRPLANE in class LCL_CARRIER into a handlermethod for the event that you just defined. You will need to change both thesignature and the implementation.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 203

Page 214: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

6. Register the new handler method so that the airline enters every airplane thatwas created after itself in the list.

Note: Although this model is unrealistic, we will use it for the timebeing. A different rule for entering the airplane can be created later.

7. Observe the execution of the program in the ABAP Debugger.

8. Where could the SET-HANDLER statement be executed in the given example?Could this also be done from the main program? What would the syntax have tobe in this case?

Task 2:Define an event for the creation of a vehicle. Trigger and handle it so that the referenceto the vehicle is entered into the car rental company�s list of vehicles.

1. Remove the calls of the ADD_VEHICLE method from your main program.

2. Define the event VEHICLE_CREATED and proceed as you did in the previousexercise.

204 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 215: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

Solution 12: Events in SuperclassesTask 1:Define an event for the creation of an airplane. Trigger and handle it so that thereference to the airplane is entered into the airline�s list of airplanes.

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

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

b) Model solution: SAPBC401_EVES_MAIN_A

2. Remove the calls of the ADD_AIRPLANE method from your main program.

Note: The entry of an airplane reference into the airline�s list is to beevent-controlled.

a) Ask your instructor if you have any questions.

3. Identify the class that is suitable for triggering the event and the classes thatshould be used for handling the event. Use your UML diagram if necessary.

If applicable, illustrate the relationships in your UML diagram.

a) Ask your instructor if you have any questions.

4. Define the public event AIRPLANE_CREATED and trigger it in the classLCL_AIRPLANE using a suitable method.

a) See the source code extract from the model solution.

5. Change the method ADD_AIRPLANE in class LCL_CARRIER into a handlermethod for the event that you just defined. You will need to change both thesignature and the implementation.

a) See the source code extract from the model solution.

6. Register the new handler method so that the airline enters every airplane thatwas created after itself in the list.

Note: Although this model is unrealistic, we will use it for the timebeing. 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

2005/Q4 © 2005 SAP AG. All rights reserved. 205

Page 216: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

7. Observe the execution of the program in the ABAP Debugger.

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

8. Where could the SET-HANDLER statement be executed in the given example?Could this also be done from the main program? What would the syntax have tobe in this case?

a) SET HANDLER r_vehicle->add_vehicle FOR ALL INSTANCES

Task 2:Define an event for the creation of a vehicle. Trigger and handle it so that the referenceto the vehicle is entered into the car rental company�s list of vehicles.

1. Remove the calls of the ADD_VEHICLE method from your main program.

a) See the source code extract from the model solution.

2. Define the event VEHICLE_CREATED and proceed as you did in the previousexercise.

a)

b) See the source code extract from the model solution.

.

ResultSource code extract:

SAPBC401_EVES_MAIN_A

REPORT sapbc401_eves_main_a.

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,

Continued on next page

206 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 217: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

r_cargo TYPE REF TO lcl_cargo_plane,

r_carrier TYPE REF TO lcl_carrier,

r_rental TYPE REF TO lcl_rental,

r_agency TYPE REF TO lcl_travel_agency.

START-OF-SELECTION.

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

***** Create TRAVEL_AGENCY **************************************

CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’.

***** Create CARRIER ********************************************

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 207

Page 218: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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

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 s_capacity

RETURNING value(re_avgfuel) TYPE s_consum.

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.

Continued on next page

208 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 219: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

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.

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.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 209

Page 220: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

re_count = n_o_vehicles.

ENDMETHOD. "get_count

ENDCLASS. "lcl_vehicle IMPLEMENTATION

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

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

METHODS display_attributes.

INTERFACES: lif_partners.

PRIVATE SECTION.

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

DATA: name TYPE string,

vehicle_list TYPE TABLE OF REF TO lcl_vehicle.

ENDCLASS. "lcl_rental DEFINITION

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

* CLASS lcl_rental IMPLEMENTATION

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

CLASS lcl_rental IMPLEMENTATION.

METHOD lif_partners~display_partner.

display_attributes( ).

ENDMETHOD. "lif_partners~display_partner

Continued on next page

210 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 221: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

METHOD constructor.

name = im_name.

SET HANDLER add_vehicle FOR ALL INSTANCES.

ENDMETHOD. "constructor

METHOD add_vehicle.

APPEND sender TO vehicle_list.

ENDMETHOD. "add_vehicle

METHOD display_attributes.

DATA: r_vehicle TYPE REF TO lcl_vehicle.

WRITE: / icon_transport_proposal AS ICON, name.

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

LOOP AT vehicle_list INTO r_vehicle.

r_vehicle->display_attributes( ).

ENDLOOP.

ENDMETHOD. "display_attributes

ENDCLASS. "lcl_rental IMPLEMENTATION

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

* CLASS lcl_travel_agency DEFINITION

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

...

SAPBC401_EVES_A

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

*& Include SAPBC401_EVES_A *

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

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

* CLASS lcl_airplane DEFINITION *

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

CLASS lcl_airplane DEFINITION.

PUBLIC SECTION.

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

CONSTANTS: pos_1 TYPE i VALUE 30.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 211

Page 222: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

METHODS: constructor IMPORTING

im_name TYPE string

im_planetype TYPE saplane-planetype,

display_attributes.

CLASS-METHODS: class_constructor.

CLASS-METHODS: display_n_o_airplanes.

EVENTS airplane_created.

PRIVATE SECTION.

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

CLASS-METHODS: get_technical_attributes

IMPORTING im_type TYPE saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacity.

DATA: name TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i.

CLASS-DATA: list_of_planetypes TYPE z_00_planetype.

ENDCLASS. "lcl_airplane DEFINITION

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

* CLASS lcl_airplane IMPLEMENTATION *

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

CLASS lcl_airplane IMPLEMENTATION.

METHOD class_constructor.

SELECT * FROM saplane INTO TABLE list_of_planetypes.

ENDMETHOD. "constructor

METHOD constructor.

name = im_name.

planetype = im_planetype.

n_o_airplanes = n_o_airplanes + 1.

RAISE EVENT airplane_created.

ENDMETHOD. "constructor

METHOD display_attributes.

DATA: weight TYPE saplane-weight,

Continued on next page

212 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 223: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

cap TYPE saplane-tankcap.

WRITE: / icon_ws_plane AS ICON,

/ ’Name of Airplane:’(001), AT pos_1 name,

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

get_technical_attributes( EXPORTING im_type = planetype

IMPORTING ex_weight = weight

ex_tankcap = cap ).

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

’Tankkap:’(004), cap.

ENDMETHOD. "display_attributes

METHOD display_n_o_airplanes.

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

AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.

ENDMETHOD. "display_n_o_airplanes

METHOD get_technical_attributes.

DATA: wa TYPE saplane.

READ TABLE list_of_planetypes INTO wa

WITH TABLE KEY planetype = im_type

TRANSPORTING weight tankcap.

ex_weight = wa-weight.

ex_tankcap = wa-tankcap.

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.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 213

Page 224: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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

Continued on next page

214 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 225: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

name = im_name.

ENDMETHOD. "constructor

METHOD get_name.

ex_name = name.

ENDMETHOD. "get_name

ENDCLASS. "lcl_carrier IMPLEMENTATION

2005/Q4 © 2005 SAP AG. All rights reserved. 215

Page 226: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

216 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 227: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

205 Exercise 13: (Optional): Events in InterfacesExercise Duration: 30 Minutes

Exercise ObjectivesAfter 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 ExampleAirline 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 beeasily extended to manage additional business partners of the travel agent in the future.

System DataSystem: will be assignedClient: will be assignedUser ID: will be assignedPassword: will be assignedSet up instructions: No special settings for using a standard SAP Web AS6.20 system.

Task:Define an event for the creation of a business partner. Trigger and handle it so that thereference to the business partner is entered into the travel agent�s list of partners.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise (where ## is your two-digit group number).

2. Remove the calls of the ADD_PARTNER method from your main program.

Note: The entry of a business partner reference into the travel agent�slist is to be event-controlled.

3. If necessary, examine your UML diagram. Which class or interface shoulddefine the event? Which class or interface should trigger it? Which class orinterface should handle it?

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 217

Page 228: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

If applicable, illustrate the relationships in your UML diagram.

4. Define the event PARTNER_CREATED and trigger it using a suitable methodin the class that you selected.

5. Change the method ADD_PARTNER in the class LCL_TRAVEL_AGENCYinto a handler method for the event that you just defined. You will need tochange both the signature and the implementation.

6. Register the new handler method, so that the travel agent enters every businesspartner that was created after itself into the list.

Note: Although this model is unrealistic, we will use it for the timebeing. A different rule for entering the business partner can be createdlater.

7. Observe the execution of the program in the ABAP Debugger.

218 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 229: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

Solution 13: (Optional): Events in InterfacesTask:Define an event for the creation of a business partner. Trigger and handle it so that thereference to the business partner is entered into the travel agent�s list of partners.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe previous exercise (where ## is your two-digit group number).

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

b) Model solution: SAPBC401_EVES_MAIN_B

2. Remove the calls of the ADD_PARTNER method from your main program.

Note: The entry of a business partner reference into the travel agent�slist is to be event-controlled.

a) See the source code extract from the model solution

3. If necessary, examine your UML diagram. Which class or interface shoulddefine the event? Which class or interface should trigger it? Which class orinterface should handle it?

If applicable, illustrate the relationships in your UML diagram.

a) Speak to your instructor if you have any questions.

4. Define the event PARTNER_CREATED and trigger it using a suitable methodin the class that you selected.

a) See the source code extract from the model solution.

5. Change the method ADD_PARTNER in the class LCL_TRAVEL_AGENCYinto a handler method for the event that you just defined. You will need tochange both the signature and the implementation.

a) See the source code extract from the model solution.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 219

Page 230: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

6. Register the new handler method, so that the travel agent enters every businesspartner that was created after itself into the list.

Note: Although this model is unrealistic, we will use it for the timebeing. A different rule for entering the business partner can be createdlater.

a) See the source code extract from the model solution.

7. Observe the execution of the program in the ABAP Debugger.

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

ResultSource code extract:

SAPBC401_EVES_MAIN_B

REPORT sapbc401_eves_main_b.

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

220 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 231: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 221

Page 232: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

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

INTERFACE lif_partners.

METHODS display_partner.

EVENTS: partner_created.

ENDINTERFACE. "lif_partners

...

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

* CLASS lcl_rental DEFINITION

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

*

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

CLASS lcl_rental DEFINITION.

PUBLIC SECTION.

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

METHODS: constructor IMPORTING im_name TYPE string.

METHODS add_vehicle for event vehicle_created of lcl_vehicle

importing sender.

METHODS display_attributes.

INTERFACES: lif_partners.

PRIVATE SECTION.

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

DATA: name TYPE string,

vehicle_list TYPE TABLE OF REF TO lcl_vehicle.

ENDCLASS. "lcl_rental DEFINITION

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

* CLASS lcl_rental IMPLEMENTATION

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

*

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

CLASS lcl_rental IMPLEMENTATION.

METHOD lif_partners~display_partner.

display_attributes( ).

ENDMETHOD. "lif_partners~display_partner

METHOD constructor.

name = im_name.

SET HANDLER add_vehicle FOR ALL INSTANCES.

RAISE EVENT lif_partners~partner_created.

ENDMETHOD. "constructor

Continued on next page

222 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 233: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

METHOD add_vehicle.

APPEND sender TO vehicle_list.

ENDMETHOD. "add_vehicle

METHOD display_attributes.

DATA: r_vehicle TYPE REF TO lcl_vehicle.

skip 2.

WRITE: / icon_transport_proposal AS ICON, name.

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

LOOP AT vehicle_list INTO r_vehicle.

r_vehicle->display_attributes( ).

ENDLOOP.

ENDMETHOD. "display_attributes

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

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

*

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 223

Page 234: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

CLASS lcl_travel_agency IMPLEMENTATION.

METHOD display_agency_partners.

DATA: r_partner TYPE REF TO lif_partners.

WRITE: icon_dependents AS ICON, name.

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

LOOP AT partner_list INTO r_partner.

r_partner->display_partner( ).

ENDLOOP.

ENDMETHOD. "display_agency_partners

METHOD constructor.

name = im_name.

SET HANDLER add_partner FOR ALL INSTANCES.

ENDMETHOD. "constructor

METHOD add_partner.

APPEND sender TO partner_list.

ENDMETHOD. "add_partner

ENDCLASS. "lcl_travel_agency IMPLEMENTATION

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,

Continued on next page

224 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 235: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

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

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 225

Page 236: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 2: Object-Oriented Concepts and Programming Techniques TAW10_3

ENDCLASS. "lcl_carrier IMPLEMENTATION

226 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 237: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Events

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 InformationFor more information, refer to the SAP Library.

2005/Q4 © 2005 SAP AG. All rights reserved. 227

Page 238: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit Summary TAW10_3

Unit SummaryYou 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 inheritance� 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� Define 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

228 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 239: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Test Your Knowledge

217Test Your Knowledge

1. What is the ABAP syntax required to make a local subclass inherit from asuperclass?

2. What is the ABAP syntax required to redefine an inherited method in a localclass?

3. Suppose you are copying a subclass reference to a reference variable that istyped to the superclass (narrowing cast). What components can you accesswith this reference variable?Choose the correct answer(s).□ A Redefined components of the superclass□ B Newly defined components of the subclass□ C Inherited components of the superclass□ D Redefined components of the subclass

4. Assume that a reference variable typed on a superclass contains a subclassreference 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 thisreference variable?Choose the correct answer(s).□ A Redefined components of the superclass□ B Newly defined components of the subclass□ C Inherited components of the superclass□ D Redefined components of the subclass

2005/Q4 © 2005 SAP AG. All rights reserved. 229

Page 240: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Test Your Knowledge TAW10_3

5. For what purpose do you use inheritance?

6. Does an interface have an implementation part?

7. Suppose that you copy an instance reference of a class that implements aninterface to a reference variable that is typed on the interface (narrowing cast).What components can you access with this reference variable?Choose the correct answer(s).□ A The components of the interface□ B The components of the class that are not defined in the interface□ C All components of the class□ D The components of the interface for which alias names have been

defined

8. Suppose that a reference variable that is typed on an interface contains aninstance reference of a class that implements this interface and you copy thisto a reference variable that is typed on the class (widening cast). Which of thefollowing components can you access with this reference variable?Choose the correct answer(s).□ A The components of the interface□ B The components from the class that are not defined on the interface□ C All components of the class□ D The components of the interface for which alias names have been

defined

230 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 241: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Test Your Knowledge

9. What is the statement for defining events?

10. What is the statement for triggering events?

11. With which statement would you define a handler method M_H for event Eof class C?

12. With which statement would you register handler method M_H of the reactinginstance REF_H with the triggering instance REF_R?

13. Can events be defined in interfaces?

14. Can events be triggered in interfaces?

2005/Q4 © 2005 SAP AG. All rights reserved. 231

Page 242: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Test Your Knowledge TAW10_3

220Answers

1. What is the ABAP syntax required to make a local subclass inherit from asuperclass?

Answer: The INHERITING FROM addition to the CLASS-DEFINITIONstatement.

2. What is the ABAP syntax required to redefine an inherited method in a localclass?

Answer: The REDEFINITION addition to the METHODS statement.

3. Suppose you are copying a subclass reference to a reference variable that istyped to the superclass (narrowing cast). What components can you accesswith this reference variable?

Answer: A, C

4. Assume that a reference variable typed on a superclass contains a subclassreference 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 thisreference variable?

Answer: A, B, C

5. For what purpose do you use inheritance?

Answer: Inheritance is how generalization/specialization relationships betweenclasses are implemented in a program.

232 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 243: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Test Your Knowledge

6. Does an interface have an implementation part?

Answer: No

7. Suppose that you copy an instance reference of a class that implements aninterface to a reference variable that is typed on the interface (narrowing cast).What components can you access with this reference variable?

Answer: A

8. Suppose that a reference variable that is typed on an interface contains aninstance reference of a class that implements this interface and you copy thisto a reference variable that is typed on the class (widening cast). Which of thefollowing components can you access with this reference variable?

Answer: A, B, C, D

9. What is the statement for defining events?

Answer: EVENTS

10. What is the statement for triggering events?

Answer: RAISE EVENT

11. With which statement would you define a handler method M_H for event Eof class C?

Answer:METHODS m_h FOR EVENT e OF c ... .

12. With which statement would you register handler method M_H of the reactinginstance 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.

2005/Q4 © 2005 SAP AG. All rights reserved. 233

Page 244: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Test Your Knowledge TAW10_3

13. Can events be defined in interfaces?

Answer: Yes

14. Can events be triggered in interfaces?

Answer: No

234 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 245: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3223 Object-Oriented Repository Objects

For more information, see the introductory instructor notes in the lesson.

Unit OverviewTHis unit introduces you to Class Builder. Class Builder is a tool that enables you tocreate global classes and interfaces that can be used by any program.

Unit ObjectivesAfter 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 and interfaces in other Repository objects� Create a simple ALV Grid Control� React to a double-click on an ALV Grid Control with a handler method� Explain the fundamentals of BAdI technology and implement a BAdI

Unit ContentsLesson: Global Classes and Interfaces .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .237

Procedure: Importing Local Classes and Interfaces .. . . . . . . . . . . . . . . . . . . . . .247Procedure: Moving the Method Definition of a Global Class to anImplemented Interface ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .255Demonstration: Moving a Method Definition to an Interface.. . . . . . . . . . . . .255Procedure: Creating an OO Transaction .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .271Demonstration: Creating an Object-Oriented Transaction ... . . . . . . . . . . . . .271

2005/Q4 © 2005 SAP AG. All rights reserved. 235

Page 246: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Exercise 14: Global Classes ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .273Exercise 15: Global Interfaces.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .277Exercise 16: (Optional): Refactoring Assistant . . . . . . . . . . . . . . . . . . . . . . . . . . . .289Exercise 17: ALV Grid Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .293

236 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 247: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Lesson:224

Global Classes and InterfacesLesson Duration: 180 Minutes

Lesson OverviewThis 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 willexamine the Class Builder�s main functions, its integration into the ABAPWorkbench,and, in particular, the Object Navigator.

We will demonstrate the use of global standard classes using the powerful example ofthe ALV Grid Control.

Lesson ObjectivesAfter 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 and interfaces in other Repository objects� Create a simple ALV Grid Control� React to a double-click on an ALV Grid Control with a handler method� Explain the fundamentals of BAdI technology and implement a BAdI

The participants will not learn any new programming skills in this lesson. This lessononly serves to introduce new types of Repository objects and the associated tools.

Once again, you should highlight the strengths of the ABAP Workbench SAPdevelopment environment, particularly in comparison to working with otherprogramming languages. For example, a context-sensitive editor does not necessarilyoffer a high-performance, cross-platform, upwardly compatible, actively integrated,and business-oriented application language.

Business ExampleYou want to develop your classes and interfaces as actively integrated Repositoryobjects.

2005/Q4 © 2005 SAP AG. All rights reserved. 237

Page 248: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Creating Global Classes and InterfacesAs with subroutines, local classes or interfaces can only be used within the program inwhich they are defined and implemented. The CLASS statement is a local, declarativestatement in the program. Just as the TYPES statement defines local data types, theCLASS statement defines local object types.

In both cases, it is irrelevant whether or not the source text is stored separately ininclude programs.

On the other hand, global classes or global interfaces are individual Repository objectswith all of the normal attributes (active integration, versioning, transport system, andso on). The namespace convention (Y*, Z*, or a special customer namespace) is thesame as that used for the namespace of other Repository objects.

A special maintenance tool is available for global classes in the ABAP Workbenchas of SAP R/3 4.6A: the Class Builder.

Be sure to explain the correct use of the Class Builder slowly and indetail. In addition to the presentation, you should show all of the steps ina separate demonstration class. For instance, you could create the class ofairplanes globally as a demo and then have the participants build housesand hotels in the exercise. They will take to this quite enthusiastically!A further idea: do not perform the inheritance, redefinition and overloading of theconstructor yourself, but rather let the participants discover this themselves in theClass Builder. This was a huge motivation in the First Teach of the course!

238 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 249: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Figure 106: Creating Global Classes in the Object Navigator

The separate navigation area of the Object Navigator makes it the ideal developmenttool for all Repository objects. It also supports the Class Builder. As with otherRepository objects, the easiest way to create a new global class is to use the contextmenu in the navigation area. First select the package node or select the class nodeitself within a package.

A dialog box asks you to make further attributes for the new class. Do not changethe default attributes at this point; you will learn about the different settings andtheir effects later.

Do the same when creating global classes.

The global class or global interface is then displayed in the Class Builder table inthe editor area of the Object Navigator.

2005/Q4 © 2005 SAP AG. All rights reserved. 239

Page 250: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Figure 107: Definition of Attributes

Choose the Attributes tab to open the list of all attribute definitions in the class. Youcan define new attributes here.

You can use the input help when you are defining the type attributes. Remember touse meaningful short descriptions.

Figure 108: Definition of Methods

240 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 251: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Choose the Methods tab to open the list of all method definitions in the class. You candefine 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.

Caution: Finding the signature of methods is often overlooked, or evenforgotten, in the exercises. Demonstrate this several times!

Choose the Constructor button to define an instance constructor. The constructorname is chosen automatically and the selection possibilities in the editor window forthe signature are restricted appropriately.

Hint: Methods can be transported separately.

We suggest that you include the interface in your demonstration class later, after thefirst exercise is complete. The focus is on working with the Class Builder, and not onintegrating the class with implemented interface methods in the application; this shouldhappen right at the end. You will have to hold back some of the participants here.

2005/Q4 © 2005 SAP AG. All rights reserved. 241

Page 252: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Figure 109: Including Global Classes

If you want to include a global interface in your global class, you must enter the nameof the interface in the Interfaces tab. Once you have done that, all of the interface�scomponents automatically appear under the relevant tabs according to the namingconvention and the interface resolution operator.

Figure 110: Definition of Method Signatures

242 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 253: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

In the method list, select a method and choose the Parameter button to go to thesignature maintenance. You can define new formal parameters here.

You can use the input help when defining the attributes. Remember to use meaningfulshort descriptions.

You can scroll between the signatures using the Previous Method or Next Methodbuttons. Choose the Methods button to return to the method list.

Figure 111: 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 implementthe modifications here.

You can display the method�s signature by choosing the relevant button.

2005/Q4 © 2005 SAP AG. All rights reserved. 243

Page 254: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Figure 112: Displaying the Method Definition

Choose Goto→Method definition if you want to change the attributes of your methodduring the implementation.

Figure 113: Definition of Components Using the Navigation Area

244 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 255: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

You can also define attributes, methods, or events in the context menu in the ObjectNavigator�s navigation area. The properties are then maintained in a dialog box, andnot in the table we saw before.

Hint: Print selected portions of the source text using Class→ Print orMethod→ Print.

Remind participants of the importance of documentation. They should documentevery class individually as well as the class as a whole.

Figure 114: The Class Builder Testing Environment

You can test active global classes.

The class�s templates are allocated temporarily. Static ones are allocated immediately,while instance components are allocated when you choose the Instance button.

The system only lists the public components. Methods can be tested using the Callmethod icon.

2005/Q4 © 2005 SAP AG. All rights reserved. 245

Page 256: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

You can test the triggering of events in a class as follows:

1. Select an event.2. Choose Handler. This registers a standard method for the event.3. Call a method in which the event trigger was implemented.

The event that was triggered and all of the exported actual parameters are displayedin a list.

Demonstrate the following procedure in the system because the menu path is not easyto find and it may not be clear how to use the next screen correctly. This is a goodopportunity to create a global interface for the business partners. You will also need itlater when you add global classes to your demonstration program.

246 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 257: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

232Importing Local Classes and InterfacesUseThis procedure is an easy way to make global copies of local classes and localinterfaces.

Hint: This function cannot be used from within OBJECT-NAVIGATOR.

Procedure1. In the SAP Easy Access menu, choose Tools → ABAP Workbench →

Development→ Class Builder or use transaction SE24.

2. From the initial screen of SE24, choose Object type→ Import→ Local programclasses.

3. Enter the name of the main program and, if the local classes and interfaces weredefined within include programs, select Expand Includes.

4. Choose 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 theImport button.

Figure 115: Importing a Local Program Class

2005/Q4 © 2005 SAP AG. All rights reserved. 247

Page 258: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Other Functions of the Class BuilderYou set out the inheritance relationships between global classes on the Properties tab.

Figure 116: Defining an Inheritance Relationship

You can specify a superclass after you choose Superclass. In this example, the subclassZCL_CARGO_PLANE_00 will inherit from superclass ZCL_AIRPLANE_00.

248 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 259: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Figure 117: Redefining an Inherited Method

To redefine an inherited method, select the relevant method in the list and choose theRedefine button. Alternately, you can use the context menu in the navigation area.

Figure 118: Defining a Local Type

You can define local types in global classes. This includes local classes in particular.

2005/Q4 © 2005 SAP AG. All rights reserved. 249

Page 260: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Technically, you are not defining a class within a class, but a class that is local inthe Repository object of the global class.

All components of the global class have access to these local types, but they areencapsulated if you try to access them from outside.

The same applies for local interfaces in global classes.

To edit the implementation parts of these local classes, choose the Impl. button (forLocal Class Implementations).

Figure 119: Structured Display of Inherited Components

To improve your understanding of inheritance and interface components, you can setthe Group by Classes and Interfaces flag in the User-Specific Settings for the ClassBuilder. The system will then display the components of the global class in a structure.

250 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 261: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Figure 120: Sorting the Component Display of Global Classes

You can also sort all components by five criteria in three levels. To do this, displaythe appropriate dialog box by choosing the Sort button.

Addition of Global Classes Using the ABAP EditorLike other repository objects, global classes and interfaces are added in the navigationarea of the OBJECT-NAVIGATOR.

Be sure to demonstrate the following editing possibilities, ideally using the globaldemonstration class that you just created.

Show both possibilities: Drag&Drop and the Pattern button.

2005/Q4 © 2005 SAP AG. All rights reserved. 251

Page 262: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Figure 121: Separating the Navigation and Editing Areas of the Object Navigator.

This way, the advantages also apply to working with global classes and interfaces.

Figure 122: Object Instantiation Using Drag&Drop

252 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 263: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

In the navigation area, click on a class name and drag it to the editing area. Thiscreates a CREATE OBJECT statement. You must then add the reference variable andthe actual parameters, if applicable, to the statement.

Alternately, you can choose the Pattern button. The CREATE-OBJECT statement isunder ABAP Objects Pattern. You can generate the statement using the input help.

Figure 123: Method Calls Using Drag and Drop

In the navigation area, click a method name and drag it to the editing area. Thiscreates a CREATE METHOD statement. You must then add the reference variableand the actual parameters, if applicable, to the statement.

Alternately, you can choose the Pattern button. The CALL-METHOD statement isunder ABAP Objects Pattern. You can generate the statement using the input help.

Optionally, you can prepare the participants for the next exercise by including theglobal interface in the global class and adapting the demonstration program to use theglobal interface. This step may not be necessary for more able groups of participants.

Make sure you take advantage of the positive motivational effect at the end ofthe exercise: Again, this should show the participants how easy it is to extendobject-oriented software applications if they have been modeled well and consistently.

2005/Q4 © 2005 SAP AG. All rights reserved. 253

Page 264: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

The Refactoring AssistantIn an ideal world, all classes, interfaces, and the associations between themwould be modeled completely using UML diagrams before developers beganimplementing them. However, in some cases, the model needs to be adaptedduring the implementation phase. The Refactoring Assistant offers a range ofuser-friendly options for you to change Repository objects. For example, you can usethe Refactoring Assistant to move the components of a class within the inheritancehierarchy. Hint: For a complete list of features of the Refactoring Assistant, refer tothe SAP Library.

Working with the tool is simple, since it is based on Drag&Drop dialogs.

Figure 124: Working with the Refactoring Assistant

Hint: The Tool Info button opens an SAP Library article about the RefactoringAssistant. You can also find the descriptions of the tool�s other abilities here.

Generally, you do not adjust the implementation of methods, since you cannot knowhow much you will need to alter object references after making these changes.

254 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 265: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

240Moving the Method Definition of a Global Class to anImplemented Interface

1. Change to the editing mode of a global class that implements a global interface.

2. Choose Tools→ Refactoring Assistant.

3. In the tree structure that appears, open the folder for the method you want tomove and for the target � in this case, the implemented interface.

4. Move the method to the interface.

5. Save your work.

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

Purpose

This section demonstrates the correct use of the Refactoring Assistant. This is also agood time to point out the easy connection to the SAP Library.

System DataSystem: will be assignedClient: will be assignedUser ID: will be assignedPassword: will be assignedSet up instructions: No special settings required if you are using a standardSAP Web AS 6.20 training system1. 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 thecopy of the interface.

Analyze, activate, and test the copy of the class.

3. Open the Refactoring Assistant and refer to the SAP Library.

2005/Q4 © 2005 SAP AG. All rights reserved. 255

Page 266: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Move the SEND_MESSAGE method from the class to the interface usingDrag&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 CALLERmethod.

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

If your time schedule allows, you can perform the exercise on the Refactoring Assistant.

Hint: Alternatively, as a more simple solution you could also create theZCL_##_HOUSE class and then create the ZCL_##_HOTEL class as asubclass. The hotel could then be integrated into the application.

256 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 267: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Object-Oriented ABAP Programming:ALV Grid ControlThe following will illustrate possible application areas of object-oriented ABAPprogramming and the use of SAP standard classes. As examples, there will be briefdiscussions of the ALV Grid Control (ALV stands for Advanced List Viewer) in thecontext of the SAP Control Framework and the Business Add-Ins.

The Control Framework is a collection of global classes and interfaces that youcan use to add SAP GUI controls in your ABAP Objects programs, regardless ofthe platform. We will show you how to use SAP standard classes effectively withreference to the widely used ALV Grid Control.

Be flexible while working on this section:

If the participants truly meet all prerequisites of this course, this material is simplyrevision. If that is the case, consider demonstrating a different application control oradding event handling to the SAP Grid Control.

You must emphasize that this is an application example. This is not an introductionto dialog programming with EnjoySAP controls.

Figure 125: The ALV Grid Control

The ALV Grid Control is a tool that you can use to display non-hierarchical lists in astandardized form. The list data is displayed in tables. It is very easy to work with,as very few programming steps have to be carried out.

2005/Q4 © 2005 SAP AG. All rights reserved. 257

Page 268: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

The ALV Grid Control contains a number of interactive standard functions that usersof lists often need, for example, print, export, and so on. As a developer, you havethe option of hiding these standard functions. When required, you can adapt theimplementations to fit the needs of your application. You can also add your ownfunctions to the application toolbar.

Figure 126: Including an ALV Grid Control Instance in a Dialog Program

The technical connection between the screen and application control is provided bycontainer controls. Generally, application controls (ALV Grid Control, Tree Control,Picture Control, and so on) are always embedded in this container control, which, inturn, is connected to the screen.

There are different types of container controls. However, they all incorporatefundamental control functions, such as scroll bars.

Let us take a common case as an example: placing an ALV Grid Control in a screenarea with a fixed size.

You need to create an instance of each of the global classes CL_GUI_CUS-TOM_CONTAINER and CL_GUI_ALV_GRID.

258 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 269: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Figure 127: Displaying Application Data Using an SAP Grid Control Instance

For normal display, the following programming steps are sufficient:

1. Use the fullscreen editor of the Screen Painter to define a custom control areaon your screen.

2. Create an instance of the class CL_GUI_CUSTOM_CONTAINER and transferthe name of the custom control area to the constructor.

3. Create an instance of the class CL_GUI_GUI_ALV_GRID and transfer thereference to the custom control instance to the constructor.

4. Call the method SET_TABLE_FOR_FIRST_DISPLAY of the grid controlinstance and transfer the internal standard table to it.

If this table has a global row type, you can transfer the name of this globalstructure to the same method. The ALV Grid Control instance then automaticallycreates the field catalog.

If you change the contents of the internal tables while the program is running, youonly need to call the REFRESH_TABLE_DISPLAY method in the relevant dialogstep to refresh the display.

2005/Q4 © 2005 SAP AG. All rights reserved. 259

Page 270: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Figure 128: ALV Grid Control: Double-Click

An ALV Grid Control can react to the user�s double-click. As a possible reaction,you can trigger a follow-on processing step in which additional information isdisplayed, for example. In the example displayed, the booking data for the individualflight customers, or data on the aircraft, could also be displayed for the flight data.Technically, this is executed by catching the DOUBLE_CLICK event with a handlermethod.

260 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 271: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Figure 129: ALV Grid Control: Reacting to a Double-Click

Here, a static handler method would in fact be easier and perfectly adequate. However,this could distract the participants from the actual topic. Be prepared for a discussionthough!

The SET-HANDLER statement is easily forgotten in the exercise for the ALV grid.However, this is good training - the participants need to learn from their mistakes aswell.

A handler method can either be a class method (static method) or an instance methodof an object. If a class method is defined as a handler method, no object of the handledclass needs to be instantiated to use the method.

To create a handler object for an event, first define a class. This class has apublic method (in the PUBLIC SECTION) that can react to an event. During theimplementation of the handler method, define the source text that should be run whenthe event is triggered. The method receives the information delivered by the eventfrom the mouse position when you double-click, and creates an information messagein the control example that displays the row and field of the mouse click.

2005/Q4 © 2005 SAP AG. All rights reserved. 261

Page 272: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Preferably, use the system to demonstrate how you can easily catch the double-clickthrough this new handler class. As an exercise, the participants should at leastprogram this in order to reinforce their knowledge of the event handling as well (thedouble-click exercise is therefore a must!).

With advanced participants, we recommend that you also use the optional exercisethree and four here, to integrate the ALV into the existing application; an existing class(LCL_CARRIER in exercise 4) would then be used here as the handling class.

Caution: Study all exercises in detail and think through your teachingapproach carefully! A total of four exercises on the ALV are available. Ofcourse, your time schedule will also determine the number of exercisesyou can cover.

Note: Extensive documentation about the SAP Control Framework isavailable. The SAP Library contains comprehensive descriptions of allclasses and a complete tutorial.

The Object Navigator also contains the Enjoy Demo Center, which makesit very easy to use standard template programs. You can find it by choosingEnvironment→ Examples→ Control Examples.

Individual elements of the SAP Control Framework are also covered in othercourses.

SAP also offers a separate comprehensive course about dialog programmingwith the EnjoySAP controls. It covers all aspects, including complexprogramming techniques like drag and drop functions.

It may be worth pointing out the relevant SAP course at this point.

262 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 273: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Object-Oriented ABAP Programming:Business Add-InsUnlike customer exits, Business Add-Ins of the changed software delivery processare taken into account here. Generally, the typical delivery process does not onlyconsist of providers and users,: rather, several intermediate providers may be involvedin the delivery chain for software. For example, an SAP application program canbe extended with an industry solution (Industrial Business Unit [IBU]); the sameprogram could then again be extended by the customer.

Be flexible while working on this section:

If the participants show interest and time permits, you can show a fulldemo here from the corresponding ABAP course. You can also use theSAPBC401_CLSS_MAIN_BADI program as a reference, and demonstrate thisstep-by-step.

You must emphasize that this is an application example. This is not a complete,detailed introduction to SAP�s enhancement techniques.

Figure 130: BAdI: basics

2005/Q4 © 2005 SAP AG. All rights reserved. 263

Page 274: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Caution: The adapter displayed here on the graphic is always the same. Both thepartner and the customer are connected to the application using the same adapter.Make this clear.

With a Business Add-In (BAdI), an SAP application program provides theenhancement option through an interface and an adapter class that implements theinterface.

The interface can then be implemented by several possible users in the deliverychain. Multiple implementations are therefore also possible; once a BAdI has beenimplemented, it can also be implemented by users who appear further to the right inthe chain. Furthermore, an implementation itself could again offer a BAdI.

Figure 131: Definition of a BAdI: Basics

When you define a BAdI, you must specify an interface (IF_EX_<badi>) withcorresponding, formally defined methods. The adapter class that is automaticallygenerated during the interface definition (CL_EX_<badi>) has, among other things,the function of calling all active implementations of the BAdI. This does not need tobe coded, but happens in the adapter class itself in an undefined sequence. When youhave several active implementations, there is no predefined processing sequence.

264 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 275: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Figure 132: Definition of a BAdl: SE18

To create a BAdI, the BAdI Builder tool (Tools→ ABAP Workbench→ Utilities→Business Add-Ins→ Definition) (SE18) is used.

Once the name has been issued for the BAdI, the system suggests names for theBAdI interface and the adapter class. To ensure you keep a clear overview, it isrecommended that you retain these names.

Note: Detailed information on the BAdI interface definition is provided inthe specific training course on the enhancement techniques and is not partof this introduction.

If you double-click on the interface name, the system switches to the Class Builder,where the interface methods can be defined.

After the interface methods are defined, the interface must be activated!

2005/Q4 © 2005 SAP AG. All rights reserved. 265

Page 276: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Figure 133: BAdI: The Calling Program

The call of a BAdI is displayed in the figure above.

First, a reference variable must be defined of the type �Reference to the BusinessAdd-In interface.�

An object of the adapter class is instantiated by the call of the GET_INSTANCE staticmethod of the CL_EXITHANDLER class. R_ADAPTER points to this instance.

The interface methods of the BAdI can now be called through this object reference.

266 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 277: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Figure 134: Finding Business Add-Ins

Before a BAdI can be implemented by the customer, its name must,of course, be defined beforehand. When you search for this BAdIname, you can use one of the following proven search mechanisms:The Repository Information-System (SE84)The application hierarchy (SE81)The Implementation Guide through SPRONavigate directly via F1->Technical Info into the application program andsearch for the instantiation of the BAdI adapter class using the CL_EX-ITHANDLER=>GET_INSTANCE call.

Double-clicking on the reference variable(here, R_ADAPTER) brings you to its definition, in which the BAdI interface is usedfor typing. You can derive the BAdI name from the name of the interface.

2005/Q4 © 2005 SAP AG. All rights reserved. 267

Page 278: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Figure 135: Implementation of a BAdI: SE19

If the name of the BAdI has been determined, the BAdI can be implemented after youstudy the documentation on this subject. The implementation is performed throughthe implementation maintenance (Tools→ ABAP Workbench→ Business Add-Ins→Implementation). Alternately, you could also go to the implementations by navigatingin the menu from the BAdI definition.

To implement a BAdI, a BAdI implementation name must be issued. The namingconvention here, as usual, is Z<impl>. A dialog box then appears for selecting thecorresponding BAdI.

The code to be implemented is stored in a method of an automatically generatedcustomer class. For this reason, the name of the implementing class must now begiven in a final dialog box. The default name from the system is comprised of �Yor Z� (the namespace prefix), �CL_� (for class), �IM_� (for implementation) and�<impl>� (the actual name of the implementation).

After you double-click on one of the BAdI methods, you can enter the code of themethod. Of course, you can also create auxiliary methods in the implementing class tobetter structure the required code of the BAdI method.

Note: Do not forget to finally activate the methods or the implementation!

268 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 279: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

It may be worth pointing out the relevant SAP course at this point.

If you want, and if time permits, you can add in a BAdI exercise here from thecorresponding course. However, it is vital that the trainer test this first in advance!

Object-Oriented Transactions as a Transaction TypeIn Transaction maintenance, you can create a transaction code as an object-orientedtransaction (OO). This means that you link the transaction code to either thetransaction service of the ABAP Objects services for persistent objects or to a publicmethod in a global or local class of a program. When calling this type of OOtransaction, which is linked to an instance method, the system automatically creates aninstance of the class in its own internal session and then executes this instance method.

This section is interesting for two reasons:

1. This new transaction type has made it possible to develop purely object-orientedapplications, that is, applications that are not associated with proceduralframework programs.

Caution: Procedural framework programs are still required for screenfields.

2. Participants need to learn about the object-oriented transaction services beforethey can understand the flag OO Transaction Model. However, they need toknow the OO transaction as a transaction type before they learn this.

2005/Q4 © 2005 SAP AG. All rights reserved. 269

Page 280: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Figure 136: Creating an OO Transaction Code

If the OO Transaction Model flag is set, the transaction code is linked to thetransaction service of the ABAP Objects services. Conversely, if it is not set, you cancall any method in a global or local class.

Users therefore now have the opportunity to call methods themselves (through menuoptions, command field entries, and so on).

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 messagefrom the Extended Syntax Check. Instead, you will either cause a runtimeerror, or there will be no display.

Therefore, you may have to resort to methods in local program classes. Naturally, youcan then use all the conventional dialog programming techniques.

270 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 281: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

254Creating an OO 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 thetransaction code to a normal instance method.

4. Enter the Class Name and Method. Set the Local in Program flag and, if you areusing a local class, enter the program name.

5. Save the transaction code.

Demonstration: Creating an Object-Oriented Transaction

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

System DataSystem: will be assignedClient: will be assignedUser ID: will be assignedPassword: will be assignedSet up instructions: No special settings required if you are using a standardSAP Web AS 6.20 training system1. 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 classCL_BC401_BOOD_ID or to your own method.

5. Save the transaction code.

2005/Q4 © 2005 SAP AG. All rights reserved. 271

Page 282: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

6. Enter the transaction code in the command field or insert it in a role � forexample, in your personal Favorites � and execute the transaction.

7. Sample objects in package BC401:

� Global class CL_BC401_BOOD_ID� Transaction code BC401_BOOD

272 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 283: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

255 Exercise 14: Global ClassesExercise Duration: 40 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Describe the functions of the Class Builder� Create global classes using the Class Builder

Business ExampleYou want to create a global class to represent hotels.

Task 1:Create a global class for hotels.

1. Create the global class ZCL_##_HOTEL (## is your two-digit group number).

2. Define the following attributes in the class:

NAME of the typeSTRING

as a private instanceattribute

MAX_BEDS of the type I as a private instanceattribute

N_O_HOTELS of the type I as a private static attribute

Maintain the short texts.

3. Define the following methods in the class:

CONSTRUCTOR Instance constructor for setting the privateattributes with the import parametersIM_NAME and IM_BEDS

DISPLAY_ATTRIBUTES Instance method for displaying attributesin an ABAP list

DISPLAY_N_O_HOTELS Static method to display the number ofcreated hotel instances in an ABAP list

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 273

Page 284: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Maintain the short texts.

Task 2:Check your work.

1. Activate your class.

2. Test your class in the Class Builder�s testing environment.

274 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 285: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Solution 14: Global ClassesTask 1:Create a global class for hotels.

1. Create the global class ZCL_##_HOTEL (## is your two-digit group number).

a) Follow the processes as outlined in the relevant section of this lesson.

b) Model solution: CL_HOTEL

Caution: If you copy from this model solution, you must removethe inheritance relationship to the global class CL_HOUSE and theglobal interface IF_PARTNERS.

2. Define the following attributes in the class:

NAME of the typeSTRING

as a private instanceattribute

MAX_BEDS of the type I as a private instanceattribute

N_O_HOTELS of the type I as a private static attribute

Maintain the short texts.

a) Follow the processes as outlined in the relevant section of this lesson.

b)

3. Define the following methods in the class:

CONSTRUCTOR Instance constructor for setting the privateattributes with the import parametersIM_NAME and IM_BEDS

DISPLAY_ATTRIBUTES Instance method for displaying attributesin an ABAP list

DISPLAY_N_O_HOTELS Static method to display the number ofcreated hotel instances in an ABAP list

Maintain the short texts.

a) Follow the processes as outlined in the relevant section of this lesson.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 275

Page 286: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Task 2:Check your work.

1. Activate your class.

a) Carry out this step in the usual manner. Additional information is availablein the SAP Library.

2. Test your class in the Class Builder�s testing environment.

a) Follow the processes as outlined in the relevant section of this lesson.

276 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 287: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

259 Exercise 15: Global InterfacesExercise Duration: 30 Minutes

Exercise ObjectivesAfter 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 ExampleYou want to add a hotel as a new business partner in your program for managing atravel agency�s business partners. Replace the local interface that you have been usingwith a global one so that it can also be implemented by the global hotel class.

System DataSystem: will be assignedClient: will be assignedUser ID: will be assignedPassword: will be assignedSet up instructions: No special settings if you are using a standard SAP Web AS6.20 system.

Task 1:Create a global interface for generalized access to business partner instances.

1. If applicable, change the interface name in your UML diagram toZIF_##_PARTNERS. (## is your two-digit group number).

2. Create the global interface ZIF_##_PARTNERS.

Define the instance method DISPLAY_PARTNER and the instance eventPARTNER_CREATED in the interface.

Hint: Import the local interface from your ZBC401_##_MAINprogram or from the previous lesson�s model solutionSAPBC401_EVES_MAIN_B.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 277

Page 288: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Task 2:Have your hotel class implement the interface.

1. If necessary, add the class ZCL_##_HOTEL to your UML diagram. It shouldimplement the interface method DISPLAY_PARTNER and trigger the instanceevent PARTNER_CREATED. Draw the corresponding relationships in yourdiagram.

2. Include the interface in your hotel class.

3. Implement the interface method in such a way that the hotel�sDISPLAY_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.

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

2. Remove the definition of the local interface and adapt all places where it wasused to suit the new global interface.

3. Define a reference variable, specify your global hotel class as the type, andcreate an instance.

4. Run your program. If you have done everything correctly, the simple instantiationshould be enough to be able to display the hotel attributes on the list as well.

278 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 289: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Solution 15: Global InterfacesTask 1:Create a global interface for generalized access to business partner instances.

1. If applicable, change the interface name in your UML diagram toZIF_##_PARTNERS. (## is your two-digit group number).

a) Ask your instructor if you have any questions.

2. Create the global interface ZIF_##_PARTNERS.

Define the instance method DISPLAY_PARTNER and the instance eventPARTNER_CREATED in the interface.

Hint: Import the local interface from your ZBC401_##_MAINprogram or from the previous lesson�s model solutionSAPBC401_EVES_MAIN_B.

a) Follow the processes as outlined in the relevant section of this lesson.

b) Suggested name: IF_PARTNERS

Task 2:Have your hotel class implement the interface.

1. If necessary, add the class ZCL_##_HOTEL to your UML diagram. It shouldimplement the interface method DISPLAY_PARTNER and trigger the instanceevent PARTNER_CREATED. Draw the corresponding relationships in yourdiagram.

a) Speak to your instructor if you have any questions.

2. Include the interface in your hotel class.

a)

3. Implement the interface method in such a way that the hotel�sDISPLAY_ATTRIBUTES instance method is called.

a) Follow the processes as outlined in the relevant section of this lesson.

b) Speak to your instructor if you have any questions.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 279

Page 290: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

4. Trigger the instance event in a suitable instance method of the hotel class.

a) Carry out this step in the usual manner. For more information, refer tothe SAP Library.

Task 3:Add an instance of your global hotel class to your main program.

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

a) Carry out this step in the usual manner. For more information, refer tothe SAP Library.

b) Model solution: SAPBC401_CLSS_MAIN_A

2. Remove the definition of the local interface and adapt all places where it wasused to suit the new global interface.

a) See the source code extract from the model solution.

3. Define a reference variable, specify your global hotel class as the type, andcreate an instance.

a) See the source code extract from the model solution.

4. Run your program. If you have done everything correctly, the simple instantiationshould be enough to be able to display the hotel attributes on the list as well.

a) Carry out this step in the usual manner. For more information, refer tothe SAP Library.

ResultSource code:

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.

Continued on next page

280 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 291: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

INCLUDE sapbc401_clss_a.

DATA: r_vehicle TYPE REF TO lcl_vehicle,

r_truck TYPE REF TO lcl_truck,

r_bus TYPE REF TO lcl_bus,

r_passenger TYPE REF TO lcl_passenger_plane,

r_cargo TYPE REF TO lcl_cargo_plane,

r_carrier TYPE REF TO lcl_carrier,

r_rental TYPE REF TO lcl_rental,

r_agency TYPE REF TO lcl_travel_agency,

r_hotel TYPE REF TO cl_hotel.

START-OF-SELECTION.

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

******* create travel_agency *****************************************

CREATE OBJECT r_agency EXPORTING im_name = ’Fly&Smile Travel’.

******* create rental *****************************************

CREATE OBJECT r_rental EXPORTING im_name = ’HAPPY CAR RENTAL’.

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 281

Page 292: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

***** cargo Plane ************************************************

CREATE OBJECT r_cargo EXPORTING

im_name = ’US Hercules’

im_planetype = ’747-500’

im_cargo = 533.

******* create hotel *****************************************

CREATE OBJECT r_hotel EXPORTING im_name = ’Holiday Inn’

im_beds = 345.

******* show attributes of all partners of travel_agency ******

r_agency->display_agency_partners( ).

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

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

*

Continued on next page

282 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 293: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

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

CLASS lcl_rental DEFINITION.

PUBLIC SECTION.

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

METHODS: constructor IMPORTING im_name TYPE string.

METHODS add_vehicle FOR EVENT vehicle_created OF lcl_vehicle

IMPORTING sender.

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. "lif_partners~display_partner

METHOD constructor.

name = im_name.

SET HANDLER add_vehicle FOR ALL INSTANCES.

RAISE EVENT if_partners~partner_created.

ENDMETHOD. "constructor

METHOD add_vehicle.

APPEND sender TO vehicle_list.

ENDMETHOD. "add_vehicle

METHOD display_attributes.

DATA: r_vehicle TYPE REF TO lcl_vehicle.

skip 2.

WRITE: / icon_transport_proposal AS ICON, name.

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

LOOP AT vehicle_list INTO r_vehicle.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 283

Page 294: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

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

METHOD constructor.

Continued on next page

284 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 295: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

name = im_name.

SET HANDLER add_partner FOR ALL INSTANCES.

ENDMETHOD. "constructor

METHOD add_partner.

APPEND sender TO partner_list.

ENDMETHOD. "add_partner

ENDCLASS. "lcl_travel_agency IMPLEMENTATION

SAPBC401_CLSS_A

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

* INCLUDE SAPBC401_CLSS_A

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

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 285

Page 296: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

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

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 if_partners~partner_created.

Continued on next page

286 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 297: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

ENDMETHOD. "constructor

METHOD get_name.

ex_name = name.

ENDMETHOD. "get_name

ENDCLASS. "lcl_carrier IMPLEMENTATION

2005/Q4 © 2005 SAP AG. All rights reserved. 287

Page 298: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

288 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 299: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

271 Exercise 16: (Optional): RefactoringAssistantExercise Duration: 15 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Describe the functions of the Class Builder� Create global classes using the Class Builder

Business ExampleYou want to include your global hotel class in a class hierarchy.

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 (## is yourtwo-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 yourdiagram.

2. Create the global class ZCL_##_HOTEL and leave it empty.

3. Define an inheritance relationship to make ZCL_##_HOUSE the superclassand 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 instanceconstructor, and the DISPLAY_ATTRIBUTES method into the classZCL_##_HOUSE.

2. Adapt the signature and the implementation of the instance constructor in thesuperclass.

3. Adapt the implementation of the DISPLAY_ATTRIBUTES method in thesuperclass.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 289

Page 300: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

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 sameas in the previous exercise.

290 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 301: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Solution 16: (Optional): RefactoringAssistantTask 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 (## is yourtwo-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 yourdiagram.

a) Speak to your instructor if you have any questions.

2. Create the global class ZCL_##_HOTEL and leave it empty.

a) Follow the processes as outlined in the relevant section of this lesson.

b) Speak to your instructor if you have any questions.

c) Model solution: CL_HOUSE

3. Define an inheritance relationship to make ZCL_##_HOUSE the superclassand ZCL_##_HOTEL the subclass.

a) Follow the processes as outlined in the relevant section of this lesson.

b) 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 instanceconstructor, and the DISPLAY_ATTRIBUTES method into the classZCL_##_HOUSE.

a) Follow the processes as outlined in the relevant section of this lesson.

b) Speak to your instructor if you have any questions.

2. Adapt the signature and the implementation of the instance constructor in thesuperclass.

a) Follow the processes as outlined in the relevant section of this lesson.

b) Speak to your instructor if you have any questions.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 291

Page 302: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

3. Adapt the implementation of the DISPLAY_ATTRIBUTES method in thesuperclass.

a) Follow the processes as outlined in the relevant section of this lesson.

b) Speak to your instructor if you have any questions.

4. Overload the instance constructor in the subclass.

a) Follow the processes as outlined in the relevant section of this lesson.

b) Speak to your instructor if you have any questions.

5. Redefine the DISPLAY_ATTRIBUTES method in the subclass.

a) Follow the processes as outlined in the relevant section of this lesson.

b) Speak to your instructor if you have any questions.

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 sameas in the previous exercise.

a) Carry out this step in the usual manner. For more information, refer tothe SAP Library.

292 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 303: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

275 Exercise 17: ALV Grid ControlExercise Duration: 45 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Create an ALV Grid Control� React to double-clicking on the ALV Grid Control

Business ExampleThe user wants to receive further information about an output list.

You can display additional information by double-clicking on a special row in a listthat was created using an ALV Grid Control.

2005/Q4 © 2005 SAP AG. All rights reserved. 293

Page 304: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

294 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 305: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

295 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 306: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Task 1:Program an ALV Grid Control.

Display a simple ALV Grid Control with data for flight connections in a new program.

1. Create a new program called ZBC401_##_ALV to create an ALV Grid Control.You can also use the program SAPBC401_CLST_ALV as a template.

Model solution: SAPBC401_CLSS_ALV

2. You want to display flight connection data from the SPFLI database table inan internal IT_SPFLI table and then display it in the ALV GRID CONTROL.Create a new internal standard table called IT_SPFLI and fill it with the datafrom the SPFLI database table.

3. Define the reference variables R_CONTAINER and R_ALV_GRID requiredfor the ALV Grid Control in the main program. Do this directly after the reportstatement.

4. If a screen does not yet exist, create one by calling CALL SCREEN �0100�.

Reserve an area of your choice on the screen for the Custom Container Control,which is used as the basis for the ALV Grid Control.

You should call an SAP_GRID�� PBO module for the PBO time. Use thereference variables to instantiate the two classes in this PBO module. Payparticular attention to the fact that the CREATE OBJECT is NOT calledrepeatedly when the PBO is called repeatedly.

5. To display the ALV Grid Control data, call the method SET_TA-BLE_FOR_FIRST_DISPLAY and transfer the internal table with the flightconnection data.

Caution: Note that you are working with a SCREEN in this exerciseand that you should always activate all parts of the program. Therefore,do not forget to activate the screen.

Continued on next page

296 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 307: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Task 2:Double-click on the ALV Grid Control.

If the user double-clicks on a row in the ALV Grid Control with flight connection data,the number of rows and columns where the user double-clicked should be displayed.

1. Enhance the program you created earlier or copy the model solutionSAPBC401_CLSS_ALV of the last exercise to ZBC401_##_ALV_EVENT1.Alternatively, you can also use and enhance the copy templateSAPBC401_CLST_ALV_EVENT (where you fill in the blanks).

2. If the user double-clicks on a row in the ALV Grid Control, the triggeredDOUBLE_CLICK event should be caught by a handler method of the classLCL_EVENT_HANDLER to be created.

Note that this class only acts as a handler and does not have any other functions.

Use ON_DOUBLE_CLICK with the import parameters ES_ROW_NO andE_COLUMN as the handler method.

3. The row number and the name of the column that the user clicked on should bedisplayed in the handler method. Use the MESSAGE statement here.

Tip: MESSAGE text TYPE �I�

You must first move the row number and the name of the column into the stringvariable ��TEXT using a suitable string command.

Hint: Do not forget to register the event (SET HANDLER ...)

Task 3: (Optional)Integrate the SAP Grid Control into the application.

You want to integrate an ALV Grid Control into the existing data modelTRAVEL_AGENCY. When you execute a function using the toolbar, an ALV GridControl should appear with a list of all airplane types. When you double-click on thislist, another list of flights should be displayed for this airplane type.

1. Enhance your last program version for the travel agency(LCL_TRAVEL_AGENCY) and airlines (LCL_CARRIER) examples. Alter-nately, you could also copy the model solution SAPBC401_CLSS_MAIN_A orthe copy template SAPBC401_CLST_MAIN_B (where you fill in the blanks) toZBC401_##_ALV_EVENT2.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 297

Page 308: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

2. If the user clicks on the �Display plane types� button, an ALV Grid Controlshould be displayed with the list of airplane types. The data for this listis contained in the internal table LIST_OF_PLANETYPES of the classLCL_AIRPLANE. You can use the functional method GET_PLANETYPESto obtain this internal table.

The function code of the button should be PLANETYPES. You can catch thisfunction code using the processing block AT USER-COMMAND and thesystem field SY-UCOMM.

If SY-UCOMM has the value PLANETYPES, you must call the screen with theALV Grid Control using the command CALL SCREEN �0100�.

Hint: If you are not familiar with ABAP reporting concepts, ask yourinstructor for assistance.

Motivate the group to work together as a team. Some participants will certainlybe very familiar with Reporting concepts and will be willing to help here.

Task 4: (Optional)Reaction to a double-click by a handler class that already exists

If a user double-clicks on a special airplane type on the ALV Grid Control with theairplane types, a list of flights with this type of airplane should be displayed.

1. Enhance your last program version or copy the model solutionSAPBC401_CLSS_MAIN_B to ZBC401_##_ALV_EVENT3.

Model solution: SAPBC401_CLSS_ALV_EVENT_2

2. When the user double-clicks on an ALV Grid Control airplane type, a list offlights should be displayed for this airplane type from the SFLIGHT databasetable. This list should be displayed on the same ALV Grid Control.

Program the method DISPLAY_FLIGHTS of the class LCL_CARRIER as thehandler method of the event DOUBLE_CLICK.

Hint: Previously, an additional class was always defined as the handlerclass. In this exercise, a class of the model that already exists shouldmake the handling method available for the first time.

Continued on next page

298 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 309: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

The appropriate records in this handler method must be read from the databasetable SFLIGHT into an internal table. Set up the ALV Grid Control again usingthe parameter SET_TABLE_FOR_FIRST_DISPLAY.

Hint: To ensure that the application returns a result that logically makessense, only read records from SFLIGHT with the relevant airplanetypes and �Lufthansa� or �American Airlines� airline. Also assignthe corresponding name in the main program of your airline instance(CREATE OBJECT r_carrier EXPORTING ... �Lufthansa�).

Reason: When you instantiate the airline in the main program, youhave to check the check table SCARR to make sure that the airlineexists. Only those airlines that appear in this check table are allowed. Inaddition, only some flights and bookings exist in the training system forthese airlines (Lufthansa flights definitely exist).

Hint: Do not forget to register the event (SET HANDLER ...)

2005/Q4 © 2005 SAP AG. All rights reserved. 299

Page 310: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Solution 17: ALV Grid ControlTask 1:Program an ALV Grid Control.

Display a simple ALV Grid Control with data for flight connections in a new program.

1. Create a new program called ZBC401_##_ALV to create an ALV Grid Control.You can also use the program SAPBC401_CLST_ALV as a template.

Model solution: SAPBC401_CLSS_ALV

a) Carry out this step in the usual manner.

2. You want to display flight connection data from the SPFLI database table inan internal IT_SPFLI table and then display it in the ALV GRID CONTROL.Create a new internal standard table called IT_SPFLI and fill it with the datafrom the SPFLI database table.

a) Create the internal standard table in the ABAP Dictionary (SE11) underData type - Table type. Additional information is available in the SAPLibrary.��

3. Define the reference variables R_CONTAINER and R_ALV_GRID requiredfor the ALV Grid Control in the main program. Do this directly after the reportstatement.

a) See the source code extract from the model solution or refer to thecorresponding slides about the ALV Grid Control.

4. If a screen does not yet exist, create one by calling CALL SCREEN �0100�.

Reserve an area of your choice on the screen for the Custom Container Control,which is used as the basis for the ALV Grid Control.

You should call an SAP_GRID�� PBO module for the PBO time. Use thereference variables to instantiate the two classes in this PBO module. Payparticular attention to the fact that the CREATE OBJECT is NOT calledrepeatedly when the PBO is called repeatedly.

a) See the source code extract from the model solution. Speak to yourinstructor if you have any questions.

5. To display the ALV Grid Control data, call the method SET_TA-BLE_FOR_FIRST_DISPLAY and transfer the internal table with the flightconnection data.

Continued on next page

300 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 311: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

Caution: Note that you are working with a SCREEN in this exerciseand that you should always activate all parts of the program. Therefore,do not forget to activate the screen.

a) See the source code extract from the model solution. Speak to yourinstructor if you have any questions.

Task 2:Double-click on the ALV Grid Control.

If the user double-clicks on a row in the ALV Grid Control with flight connection data,the number of rows and columns where the user double-clicked should be displayed.

1. Enhance the program you created earlier or copy the model solutionSAPBC401_CLSS_ALV of the last exercise to ZBC401_##_ALV_EVENT1.Alternatively, you can also use and enhance the copy templateSAPBC401_CLST_ALV_EVENT (where you fill in the blanks).

a) Model solution: SAPBC401_CLSS_ALV_EVENT_1

2. If the user double-clicks on a row in the ALV Grid Control, the triggeredDOUBLE_CLICK event should be caught by a handler method of the classLCL_EVENT_HANDLER to be created.

Note that this class only acts as a handler and does not have any other functions.

Use ON_DOUBLE_CLICK with the import parameters ES_ROW_NO andE_COLUMN as the handler method.

a) See the source code extract from the model solution.

3. The row number and the name of the column that the user clicked on should bedisplayed in the handler method. Use the MESSAGE statement here.

Tip: MESSAGE text TYPE �I�

You must first move the row number and the name of the column into the stringvariable ��TEXT using a suitable string command.

Hint: Do not forget to register the event (SET HANDLER ...)

a)

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 301

Page 312: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

*& Report SAPBC401_CLSS_ALV_EVENT_1 *

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

*& Demo on ALV-Grid event-processing of double_click *

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

REPORT SAPBC401_CLSS_ALV_EVENT_1.

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

* CLASS lcl_event_handler DEFINITION

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

CLASS lcl_event_handler DEFINITION.

PUBLIC SECTION.

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

METHODS on_double_click FOR EVENT double_click OF cl_gui_alv_grid

IMPORTING es_row_no e_column.

ENDCLASS. "lcl_event_handler DEFINITION

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

* CLASS lcl_event_handler IMPLEMENTATION

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

CLASS lcl_event_handler IMPLEMENTATION.

METHOD on_double_click.

DATA: text TYPE string, es_row_string TYPE string.

es_row_string = es_row_no-row_id.

CONCATENATE ’row: ’ es_row_string ’column: ’

e_column-fieldname INTO text .

MESSAGE text TYPE ’I’.

ENDMETHOD. "handler_method

ENDCLASS. "lcl_event_handler IMPLEMENTATION

************** Types and Data Definitions ************************

TYPES: ty_spfli TYPE STANDARD TABLE OF spfli

WITH KEY carrid connid.

DATA: r_handler TYPE REF TO lcl_event_handler.

DATA: r_container TYPE REF TO cl_gui_custom_container,

r_alv_grid TYPE REF TO cl_gui_alv_grid.

DATA: it_spfli TYPE ty_spfli.

Continued on next page

302 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 313: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

START-OF-SELECTION.

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

CREATE OBJECT r_handler.

SELECT * FROM spfli INTO TABLE it_spfli.

*** calling the dynpro on which ALV-Grid will be shown *****

CALL SCREEN ’0100’.

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

*& Module STATUS_0100 OUTPUT

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

MODULE status_0100 OUTPUT.

SET PF-STATUS ’DYNPROSTATUS’.

SET TITLEBAR ’TITLE1’.

ENDMODULE. " STATUS_0100 OUTPUT

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

*& Module ALV_GRID OUTPUT

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

MODULE alv_grid OUTPUT.

*** Create object of class CL_GUI_CUSTOM_CAONTAINER to manage data !

IF NOT r_container IS BOUND.

CREATE OBJECT r_container

EXPORTING

container_name = ’CONTAINER_1’

EXCEPTIONS

OTHERS = 6.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDIF.

*** create object of class cl_gui_alv_grid to visualize data !

IF NOT r_alv_grid IS BOUND.

CREATE OBJECT r_alv_grid

EXPORTING

i_parent = r_container

EXCEPTIONS

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 303

Page 314: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

OTHERS = 5.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

*** set handler to react on double-click *******************

SET HANDLER r_handler->on_double_click FOR r_alv_grid.

ENDIF.

*** Call method to visualize data of internal table ************

CALL METHOD r_alv_grid->set_table_for_first_display

EXPORTING

i_structure_name = ’SPFLI’

CHANGING

it_outtab = it_spfli

EXCEPTIONS

OTHERS = 4.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDMODULE. " ALV_GRID OUTPUT

Task 3: (Optional)Integrate the SAP Grid Control into the application.

You want to integrate an ALV Grid Control into the existing data modelTRAVEL_AGENCY. When you execute a function using the toolbar, an ALV GridControl should appear with a list of all airplane types. When you double-click on thislist, another list of flights should be displayed for this airplane type.

1. Enhance your last program version for the travel agency(LCL_TRAVEL_AGENCY) and airlines (LCL_CARRIER) examples. Alter-nately, you could also copy the model solution SAPBC401_CLSS_MAIN_A orthe copy template SAPBC401_CLST_MAIN_B (where you fill in the blanks) toZBC401_##_ALV_EVENT2.

a) Carry out this step in the usual manner.

Continued on next page

304 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 315: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

2. If the user clicks on the �Display plane types� button, an ALV Grid Controlshould be displayed with the list of airplane types. The data for this listis contained in the internal table LIST_OF_PLANETYPES of the classLCL_AIRPLANE. You can use the functional method GET_PLANETYPESto obtain this internal table.

The function code of the button should be PLANETYPES. You can catch thisfunction code using the processing block AT USER-COMMAND and thesystem field SY-UCOMM.

If SY-UCOMM has the value PLANETYPES, you must call the screen with theALV Grid Control using the command CALL SCREEN �0100�.

Hint: If you are not familiar with ABAP reporting concepts, ask yourinstructor for assistance.

Motivate the group to work together as a team. Some participants will certainlybe very familiar with Reporting concepts and will be willing to help here.

a) See the source code extract from the model solution. Speak to yourinstructor if you have any questions.

Task 4: (Optional)Reaction to a double-click by a handler class that already exists

If a user double-clicks on a special airplane type on the ALV Grid Control with theairplane types, a list of flights with this type of airplane should be displayed.

1. Enhance your last program version or copy the model solutionSAPBC401_CLSS_MAIN_B to ZBC401_##_ALV_EVENT3.

Model solution: SAPBC401_CLSS_ALV_EVENT_2

a)

2. When the user double-clicks on an ALV Grid Control airplane type, a list offlights should be displayed for this airplane type from the SFLIGHT databasetable. This list should be displayed on the same ALV Grid Control.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 305

Page 316: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

Program the method DISPLAY_FLIGHTS of the class LCL_CARRIER as thehandler method of the event DOUBLE_CLICK.

Hint: Previously, an additional class was always defined as the handlerclass. In this exercise, a class of the model that already exists shouldmake the handling method available for the first time.

The appropriate records in this handler method must be read from the databasetable SFLIGHT into an internal table. Set up the ALV Grid Control again usingthe parameter SET_TABLE_FOR_FIRST_DISPLAY.

Hint: To ensure that the application returns a result that logically makessense, only read records from SFLIGHT with the relevant airplanetypes and �Lufthansa� or �American Airlines� airline. Also assignthe corresponding name in the main program of your airline instance(CREATE OBJECT r_carrier EXPORTING ... �Lufthansa�).

Reason: When you instantiate the airline in the main program, youhave to check the check table SCARR to make sure that the airlineexists. Only those airlines that appear in this check table are allowed. Inaddition, only some flights and bookings exist in the training system forthese airlines (Lufthansa flights definitely exist).

Hint: Do not forget to register the event (SET HANDLER ...)

a) See the source code extract from the model solution. Speak to yourinstructor if you have any questions.

Result

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

*& Report SAPBC401_CLSS_MAIN_C *

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

*& Final program with event processing of ALV-GRID double-click; *

*& airplanetypes are shown in ALV-Grid --> double-click --> *

*& all flights concerning this planetype are shown ! *

*& The event is handled by lcl_carrier class. *

*& Handler-method is "display_flights" *

*& --> all flights concerning this planetype are shown ! *

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

Continued on next page

306 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 317: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

REPORT sapbc401_clss_main_c.

TYPE-POOLS icon.

DATA: r_container TYPE REF TO cl_gui_custom_container,

r_alv_grid TYPE REF TO cl_gui_alv_grid.

DATA: it_planetypes TYPE ty_planetypes.

DATA: ok_code TYPE sy-ucomm.

INCLUDE sapbc401_vehd_j.

INCLUDE sapbc401_clss_c.

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,

r_plane TYPE REF TO lcl_airplane.

AT USER-COMMAND.

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

CASE sy-ucomm.

WHEN ’PLANETYPES’.

CALL SCREEN ’0100’.

ENDCASE.

START-OF-SELECTION.

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

SET PF-STATUS ’LISTSTATUS’.

******* create travel_agency Lufthansa **********************

CREATE OBJECT r_agency EXPORTING im_name = ’Fly & Smile’.

******* create hotel *****************************************

CREATE OBJECT r_hotel EXPORTING im_name = ’Holiday Inn’

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 307

Page 318: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

im_beds = 345.

******* 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 = ’Lufthansa’.

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

***** cargo Plane 2 *********************************************

CREATE OBJECT r_cargo EXPORTING

im_name = ’US Navy 1’

im_planetype = ’747-400’

im_cargo = 460.

***** Passenger Plane ********************************************

CREATE OBJECT r_passenger EXPORTING

im_name = ’AA Chicago’

im_planetype = ’747-400’

im_seats = 420.

******* show attributes of all partners of travel_agency ******

r_agency->display_agency_partners( ).

Continued on next page

308 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 319: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

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

*& Module STATUS_0100 OUTPUT

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

* text

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

MODULE status_0100 OUTPUT.

SET PF-STATUS ’DYNPROSTATUS’.

SET TITLEBAR ’TITEL1’.

ENDMODULE. " STATUS_0100 OUTPUT

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

*& Module USER_COMMAND_0100 INPUT

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

* text

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

MODULE user_command_0100 INPUT.

DATA: save_ok TYPE sy-ucomm.

save_ok = ok_code.

CLEAR ok_code.

CASE save_ok.

WHEN ’BACK’.

SET SCREEN ’0100’.

WHEN ’EXIT’.

LEAVE PROGRAM.

WHEN OTHERS.

ENDCASE.

ENDMODULE. " USER_COMMAND_0100 INPUT

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

*& Module ALV_GRID OUTPUT

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

* text

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

MODULE alv_grid OUTPUT.

*** Create object of class CL_GUI_CUSTOM_CAONTAINER to manage data !

IF NOT r_container IS BOUND.

CREATE OBJECT r_container

EXPORTING

container_name = ’CONTAINER_1’

EXCEPTIONS

OTHERS = 6.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 309

Page 320: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDIF.

*** create object of class cl_gui_alv_grid to visualize data !

IF NOT r_alv_grid IS BOUND.

CREATE OBJECT r_alv_grid

EXPORTING

i_parent = r_container

EXCEPTIONS

OTHERS = 5.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

*** set handler to react on double-click *******************

SET HANDLER r_carrier->display_flights FOR r_alv_grid.

*** call functional static method to get all planetypes in itab

it_planetypes = lcl_airplane=>get_planetypes( ).

ENDIF.

*** Call method to visualize data of internal table ************

CALL METHOD r_alv_grid->set_table_for_first_display

EXPORTING

i_structure_name = ’SAPLANE’

CHANGING

it_outtab = it_planetypes

EXCEPTIONS

OTHERS = 4.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDMODULE. " ALV_GRID OUTPUT

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

*INCLUDE SAPBC401_CLSS_B *

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

Continued on next page

310 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 321: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

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

* process ALV GRID Control to show all airplanetypes of class *

* LCL_AIRPLANE ( static internal table ). React on double-click... *

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

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

CLASS-METHODS: class_constructor.

CLASS-METHODS: get_planetypes RETURNING value(re_planetypes)

TYPE ty_planetypes.

EVENTS:airplane_created.

PRIVATE SECTION.

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

METHODS: get_technical_attributes

IMPORTING im_type TYPE saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacity.

DATA: name TYPE string,

planetype TYPE saplane-planetype.

CLASS-DATA: n_o_airplanes TYPE i.

CLASS-DATA: list_of_planetypes TYPE ty_planetypes.

ENDCLASS. "lcl_airplane DEFINITION

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

* CLASS lcl_airplane IMPLEMENTATION *

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

CLASS lcl_airplane IMPLEMENTATION.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 311

Page 322: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

METHOD get_planetypes.

re_planetypes = list_of_planetypes.

ENDMETHOD. "get_planetypes

METHOD class_constructor.

SELECT * FROM saplane INTO TABLE list_of_planetypes.

ENDMETHOD. "class_constructor

METHOD constructor.

name = im_name.

planetype = im_planetype.

n_o_airplanes = n_o_airplanes + 1.

RAISE EVENT airplane_created.

ENDMETHOD. "constructor

METHOD display_attributes.

DATA: weight TYPE saplane-weight,

cap TYPE saplane-tankcap.

WRITE: / icon_ws_plane AS ICON,

/ ’Name of Airplane:’(001), AT pos_1 name,

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

get_technical_attributes( EXPORTING im_type = planetype

IMPORTING ex_weight = weight

ex_tankcap = cap ).

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

’Tankkap:’(004), cap.

ENDMETHOD. "display_attributes

METHOD display_n_o_airplanes.

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

AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.

ENDMETHOD. "display_n_o_airplanes

METHOD get_technical_attributes.

DATA: wa TYPE saplane.

READ TABLE list_of_planetypes INTO wa

WITH TABLE KEY planetype = im_type

TRANSPORTING weight tankcap.

ex_weight = wa-weight.

ex_tankcap = wa-tankcap.

ENDMETHOD. "get_technical_attributes

Continued on next page

312 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 323: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

ENDCLASS. "lcl_airplane IMPLEMENTATION

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

* CLASS lcl_cargo_plane DEFINITION

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

CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.

*...

ENDCLASS. "lcl_cargo_plane DEFINITION

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

* CLASS lcl_cargo_plane IMPLEMENTATION

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

CLASS lcl_cargo_plane IMPLEMENTATION.

*...

ENDCLASS. "lcl_cargo_plane IMPLEMENTATION

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

* CLASS lcl_passenger_plane DEFINITION

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

CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..

*...

ENDCLASS. "lcl_passenger_plane DEFINITION

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

* CLASS lcl_passenger_plane IMPLEMENTATION

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

CLASS lcl_passenger_plane IMPLEMENTATION.

*...

ENDCLASS. "lcl_passenger_plane IMPLEMENTATION

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

* CLASS lcl_carrier DEFINITION

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

*

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

CLASS lcl_carrier DEFINITION.

PUBLIC SECTION.

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

INTERFACES if_partners.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 313

Page 324: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

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.

*** handler method for double_click of ALV-GRID *******

METHODS display_flights FOR EVENT double_click

OF cl_gui_alv_grid IMPORTING es_row_no e_column.

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

DATA: it_planetypes TYPE ty_planetypes.

DATA: it_flights TYPE STANDARD TABLE OF sflight.

DATA: wa_plane TYPE saplane.

SET TITLEBAR ’TITEL2’.

*** get planetypes out of lcl_airplane *******************

it_planetypes = lcl_airplane=>get_planetypes( ).

READ TABLE it_planetypes INTO wa_plane INDEX es_row_no-row_id.

*** read flights from sflight into internal table it_flights *******

SELECT * FROM sflight INTO TABLE it_flights

WHERE carrid = ’LH’

AND planetype = wa_plane-planetype.

IF sy-subrc = 0.

*** show flight data in ALV-GRID-CONTROL *******

CALL METHOD r_alv_grid->set_table_for_first_display

EXPORTING

i_structure_name = ’SFLIGHT’

CHANGING

it_outtab = it_flights

Continued on next page

314 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 325: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Global Classes and Interfaces

EXCEPTIONS

OTHERS = 4.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ELSE.

MESSAGE

’SORRY, no Lufthansa-flights with this planetype’ TYPE ’I’.

ENDIF.

ENDMETHOD. "display_flights

METHOD if_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 if_partners~partner_created.

ENDMETHOD. "constructor

METHOD get_name.

ex_name = name.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 315

Page 326: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 3: Object-Oriented Repository Objects TAW10_3

ENDMETHOD. "get_name

ENDCLASS. "lcl_carrier IMPLEMENTATION

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

*& Include SAPBC401_VEHD_J *

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

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

* CLASS lcl_vehicle DEFINITION

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

*...nothing has changed here !

316 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 327: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 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 and interfaces in other Repository objects� Create a simple ALV Grid Control� React to a double-click on an ALV Grid Control with a handler method� Explain the fundamentals of BAdI technology and implement a BAdI

Related InformationInformation about this topic is available in the SAP Library.

2005/Q4 © 2005 SAP AG. All rights reserved. 317

Page 328: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit Summary TAW10_3

Unit SummaryYou 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 and interfaces in other Repository objects� Create a simple ALV Grid Control� React to a double-click on an ALV Grid Control with a handler method� Explain the fundamentals of BAdI technology and implement a BAdI

318 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 329: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Test Your Knowledge

301Test Your Knowledge

1. Which of the following statements are correct?Choose the correct answer(s).□ A You can create function modules using the Class Builder.□ B A global class can contain a local class.□ C A global interface can contain a local interface.□ D A global class can contain a local interface.□ E A nested definition of classes is when a local class is within a global

class.□ F Using the Class Builder, a local class can be converted into a global

class.□ G A local class can be copied using the Class Builder: the copy is then a

global class.□ H You can use the Refactoring Assistant to move the methods to a

different class within an inheritance hierarchy.□ I You can use the Refactoring Assistant to design model diagrams.

2. For a user to be able to execute an object-oriented program, you always need tosupply a module pool program or a function group program. Otherwise, there isnowhere for the CREATE OBJECT statement to create the instance.Determine whether this statement is true or false.□ True□ False

2005/Q4 © 2005 SAP AG. All rights reserved. 319

Page 330: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Test Your Knowledge TAW10_3

302Answers

1. Which of the following statements are correct?

Answer: B, D, G, H, I

Additional information is available in the SAP Library.

2. For a user to be able to execute an object-oriented program, you always need tosupply a module pool program or a function group program. Otherwise, there isnowhere 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 realizedusing an OO transaction. However, certain restrictions apply.Additional information is available in the SAP Library.

320 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 331: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4303 ALV Grid Control

Tell the participants that ALV Grid Control application is valid for global classes andthis technique can be used for all types of lists.

Unit OverviewIn this unit, we will look at an application area using object-oriented ABAPprograming with ALV Grid Control application in general and global classes. ALVmeans Advanced List Viewer. ALV Grid Control can also be used to create lists inthe SAP system and replaces the classic method for creating lists using the WRITEcommand.

Unit ObjectivesAfter completing this unit, you will be able to:

� Describe the Control Framework� Create simple lists using ALV Grid Control� Explain the purpose of the field catalog� Add columns to the ALV Grid Control and change ALV columns� Create the layout structure of an ALV Grid Control� Set colors of lines and cells in the ALV Grid Control� Hide standard toolbar functions� React to ALV Grid Control events

Unit ContentsLesson: ALV Grid Control - Simple Lists... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .323

Exercise 18: ALV Grid Control - Simple Lists .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .329Lesson: ALV Grid Control - Field Catalog .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .337

2005/Q4 © 2005 SAP AG. All rights reserved. 321

Page 332: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Lesson: ALV Grid Control - Layout . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .349Exercise 19: ALV Grid Control - Field Catalog and Layout . . . . . . . . . . . . . . .357

Lesson: ALV Grid Control - Events ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .368Exercise 20: ALV Grid Control - Events .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .371

322 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 333: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Simple Lists

Lesson:304

ALV Grid Control - Simple ListsLesson Duration: 1 Minutes

Lesson OverviewThis lesson covers the Control Framework, providing an overview of the programmingmodel that can be used to work with the ALV Grid Control. We will then look at howyou can use the ALV Grid Control to quickly create lists that are simple, but contain awide variety of functions.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Describe the Control Framework� Create simple lists using ALV Grid Control

Business ExampleYou are a programmer at ABC Travel. You have been asked to take an existingreport that displays flight information in a list, and enhance it so that users candisplay additional information in a details list. You will use the ALV Grid Control toimplement this details list.

SAP Control Framework and ALV Grid ControlThe SAP Control Framework is a network of global classes and interfaces that youcan use to incorporate SAP GUI controls into your ABAP object program for allplatforms. Using the widely implemented ALV Grid Control, in the following sectionwe will demonstrate how you can effectively use the classes delivered by SAP.

Make sure that you emphasize that this is a sample application. This is not anintroduction to dialog programming with EnjoySAP controls.

2005/Q4 © 2005 SAP AG. All rights reserved. 323

Page 334: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Figure 137: The ALV Grid Control

The ALV Grid Control is a tool that you can use to display non-hierarchical lists in auniform format. The list data is displayed as a table on the screen. This tool is veryuser-friendly: You only have to carry out a minimum number of programming steps.

The ALV Grid Control has a number of interactive standard functions that listusers frequently use, for example, printing, and export. Developers can hide thesestandard functions if they wish. However, you can modify the implementations onan application-specific basis if required. You can also add your own functions tothe application toolbar.

324 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 335: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Simple Lists

Figure 138: Including a Grid Control Instance in a Dialog Program

Container controls form the technical connection between a screen and an applicationcontrol. Application controls (for example, ALV Grid Control, tree controls, andpicture controls) must be embedded in a container control, which in turn must beconnected with the screen.

There are different types of container controls. All of these types encapsulate basiccontrol functions (for example, scroll bars).

In the following sections, we will work rough a standard case as an example:Positioning an ALV Grid Control in a screen area with a fixed size.

To do this, an instance of each of the global classes CL_GUI_CUSTOM_CONTAINERand CL_GUI_ALV_GRID must be generated.

2005/Q4 © 2005 SAP AG. All rights reserved. 325

Page 336: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Figure 139: Displaying Application Data Using an SAP Grid Control Instance

For a basic standard display, it is enough to program the following steps:

1. Define a custom control area on your screen using the screen painter�s grahicalfullscreen editor.

2. Generate an instance of the CL_GUI_CUSTOM_CONTAINER class and givethe constructor the name of the custom control area you have defined.

3. Generate an instance of the class CL_GUI_ALV_GRID and assign theconstructor the reference to the container control instance you have justgenerated.

4. Call the SET_TABLE_FOR_FIRST_DISPLAY method of the Grid Controlinstance and assign it the internal standard table and application data.

If this method has a global line type, you can give it the name of this globalstructure. The field catalog will then be set up by the grid control instance itself.

326 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 337: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Simple Lists

If the contents of the internal table change during the rest of the program run, it isenough to call the method REFRESH_TABLE_DISPLAY in the corresponding dialogstep, to update the display accordingly.

Note: Comprehensive information is available on the SAP ControlFramework. The SAP Library contains details and an entire tutorial on allclasses.

The Enjoy Demo Center is also located in the Object Navigator underEnvironment -> Examples -> Control Examples. This provides user-friendlystandard template program functions.

Individual elements of the SAP Control Framework are also covered by othertraining courses.

SAP also offers a comprehensive training course on dialog programmingusing the Enjoy SAP controls, covering complex programming techniquessuch as the Drag&Drop function.

Remember to make participants aware of other relevant SAP training courses.

2005/Q4 © 2005 SAP AG. All rights reserved. 327

Page 338: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

328 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 339: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Simple Lists

309 Exercise 18: ALV Grid Control - Simple ListsExercise Duration: Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Output data using an ALV Grid Control

Business ExampleUsers would like to obtain detailed information in an output list.

System DataSystem: Will be announced by trainerClient: Will be announced by trainerUser ID: Will be announced by trainerPassword: Will be announced by trainerSet up instructions:

1. No particular settings required when a standard training system is used.

Task:Add an option to your program that allows users to select the aircraft type, and displaya list of all flights for which this type is used. Implement the list using the ALV GridControl.

Hint: Use the hide technique to go to the list. To do this, define a globalvariant.

1. Copy the template program TAW10_ALVT from the BC_TAW10 package(Copy all). Enter the name ZTAW10_##_ALV_1 for the copied program, andfamiliarize yourself with the program.

2. Go to the display_attributes method of the lcl_airplane class and implementthe hide technique. Make sure you read the note displayed above.

3. Define an internal table that has the same structure as the sflight table and fillthis table with the flights (sflight table) for which the aircraft type that wasclicked by the user in the basic list is used. If no flights exist for an aircraft type,display message 100 of the TAW10 message class.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 329

Page 340: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

4. In the main program, define reference variables required for the ALV GridControl.

5. For screen 100, go to the graphical Screen Painter and create a container areathat is sufficiently large. Give this area a self-explanatory name. Activate thescreen and leave the graphical Screen Painter.

6. Instantiate the container controland ALV Grid Control objects in the existingmanage_alv_grid PBO module. Make sure that only one object is generatedeven if the module is called several times. Call the set_table_for_first_displaymethod and pass your internal table that already contains the flights.

7. Activate the entire program, start it, and test your new functions.

330 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 341: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Simple Lists

Solution 18: ALV Grid Control - Simple ListsTask:Add an option to your program that allows users to select the aircraft type, and displaya list of all flights for which this type is used. Implement the list using the ALV GridControl.

Hint: Use the hide technique to go to the list. To do this, define a globalvariant.

1. Copy the template program TAW10_ALVT from the BC_TAW10 package(Copy all). Enter the name ZTAW10_##_ALV_1 for the copied program, andfamiliarize yourself with the program.

a) Carry out this step as normal.

2. Go to the display_attributes method of the lcl_airplane class and implementthe hide technique. Make sure you read the note displayed above.

a) See the source text in the sample solution.

3. Define an internal table that has the same structure as the sflight table and fillthis table with the flights (sflight table) for which the aircraft type that wasclicked by the user in the basic list is used. If no flights exist for an aircraft type,display message 100 of the TAW10 message class.

a) See the source text in the sample solution.

4. In the main program, define reference variables required for the ALV GridControl.

a) See the source text in the sample solution.

5. For screen 100, go to the graphical Screen Painter and create a container areathat is sufficiently large. Give this area a self-explanatory name. Activate thescreen and leave the graphical Screen Painter.

a) Go to the Screen Painter by double-clicking 100 in the navigation areaunder the screen flolder of your program. In the application toolbar, selectLayout and go to the graphical Screen Painter. Here, generate the containerarea by selecting the corresponding button (button with a small c, forcontainer) in the application toolbar on the left and then use the cursor todrag the area to the required location. Enter the name of the container areain the name field on the top left.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 331

Page 342: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

6. Instantiate the container controland ALV Grid Control objects in the existingmanage_alv_grid PBO module. Make sure that only one object is generatedeven if the module is called several times. Call the set_table_for_first_displaymethod and pass your internal table that already contains the flights.

a) See the source text in the sample solution.

7. Activate the entire program, start it, and test your new functions.

a) Carry out this step as normal.

Result

Solution program: TAW10_ALVS_1

REPORT taw10_alvs_1 message-id taw10.

TYPE-POOLS icon.

INCLUDE TAW10_VEHICLES_1.

INCLUDE TAW10_AIRPLANES_1.

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.

* References for ALV grid

DATA: r_container TYPE REF TO cl_gui_custom_container,

r_alv_grid TYPE REF TO cl_gui_alv_grid.

* Table for data displayed by the ALV grid

DATA: it_flights TYPE TABLE OF sflight.

Continued on next page

332 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 343: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Simple Lists

* Show flight data in ALV grid after double click

AT LINE-SELECTION.

CHECK NOT gl_hide_planetype IS INITIAL.

SELECT * FROM sflight INTO TABLE it_flights

WHERE planetype = gl_hide_planetype.

IF sy-subrc = 0.

CALL SCREEN ’100’.

ELSE.

MESSAGE s100 with gl_hide_planetype.

ENDIF.

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 333

Page 344: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

im_name = ’LH BERLIN’

im_planetype = ’747-400’

im_seats = 345.

***** cargo Plane ************************************************

CREATE OBJECT r_cargo EXPORTING

im_name = ’US Hercules’

im_planetype = ’747-500’

im_cargo = 533.

******* create hotel *****************************************

CREATE OBJECT r_hotel EXPORTING im_name = ’Holiday Inn’

im_beds = 345.

******* show attributes of all partners of travel_agency ******

r_agency->display_agency_partners( ).

*** Clear global hide variable ***

CLEAR gl_hide_planetype.

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

*& Module manage_alv_grid OUTPUT

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

* text

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

MODULE manage_alv_grid OUTPUT.

*** Create object of class CL_GUI_CUSTOM_CAONTAINER to manage data !

IF NOT r_container IS BOUND.

CREATE OBJECT r_container

EXPORTING

container_name = ’MY_CONTAINER’

EXCEPTIONS

OTHERS = 6.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDIF.

Continued on next page

334 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 345: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Simple Lists

*** create object of class cl_gui_alv_grid to visualize data !

IF NOT r_alv_grid IS BOUND.

CREATE OBJECT r_alv_grid

EXPORTING

i_parent = r_container

EXCEPTIONS

OTHERS = 5.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDIF.

*** Call method to visualize data of internal table ************

CALL METHOD r_alv_grid->set_table_for_first_display

EXPORTING

i_structure_name = ’SFLIGHT’

CHANGING

it_outtab = it_flights

EXCEPTIONS

OTHERS = 4.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDMODULE. " manage_alv_grid OUTPUT

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

*& Module USER_COMMAND_0100 INPUT

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

* text

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

MODULE user_command_0100 INPUT.

CASE sy-ucomm.

WHEN ’BACK’.

LEAVE TO SCREEN 0.

ENDCASE.

ENDMODULE. " USER_COMMAND_0100 INPUT

2005/Q4 © 2005 SAP AG. All rights reserved. 335

Page 346: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Lesson Summary

You should now be able to:� Describe the Control Framework� Create simple lists using ALV Grid Control

336 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 347: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Field Catalog

Lesson:316

ALV Grid Control - Field CatalogLesson Duration: 50 Minutes

Lesson OverviewThis lesson demonstrates how you can use the field catalog to display user-definedfields in the ALV Grid Control, amongst other things.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Explain the purpose of the field catalog� Add columns to the ALV Grid Control and change ALV columns

Participants will learn about basic ALV Grid Control techniques. The ALV GridControl is SAP's recommended procedure for creating lists.

Business ExampleYou are a programmer at ABC Travel. You have been requested to enhance flightinformation by adding data that is only calculated at runtime. To do this, you have toadd a new column to the ALV.

2005/Q4 © 2005 SAP AG. All rights reserved. 337

Page 348: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Objective of Field Catalogs

Figure 140: ALV Grid Control: Field Catalog

The field catalog is a format description of the data display area.

Figure 141: Function of Field Catalogs

338 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 349: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Field Catalog

The internal table with the data to be displayed can have a user-specific line type. Inorder for the proxy instance to satisfactorily format the data it receives during thescreen output or when a print list is created, it requires relevant information known asthe field catalog.

You can have the proxy instance automatically generate the field catalog. For linetypes that are defined in the ABAP Dictionary, you only need to inform the proxyinstance of the structure's name in the ABAP Dictionary.

Alternativly, or in addition to this, you can provide the proxy instance with this displayinformation using an additional internal table. For the sake of simplicity, we will callthis additional table a field catalog. The global data type of this internal table isLVC_T_FCAT. Its line type is LVC_S_FCAT.

Typical examples of where you need to transfer a field catalog include:

� The internal table with data has a line type with a dictionary reference, but thedisplay of the column position or heading is different.

� The internal table has (exclusive or additional) columns that are not contained ina dictionary structure.

For each column in the data table that deviates from an underlying dictionary structureor is not available in a dictionary structure, the field catalog must contain a line thatdetermines the technical characteristics and other column format information.

Figure 142: Grid Structure Options

2005/Q4 © 2005 SAP AG. All rights reserved. 339

Page 350: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Field catalogs are generated in a number of ways, depending on the line type usedby the data table. The following three cases may occur:

Case1:

All fields of a global structure type appear in the data table with the same name.These exact fields are to be displayed.

In this case, you can have the proxy instance create the field catalog. You only need toenter the name of the global structure type. Data table columns that are not defined inthe global structure type are not displayed.

Case 2:

All fields of a global structure type appear in the data table with the same name.However, the requirements of the ABAP Dictionary are to be changed and/oradditional columns are to be displayed.

In this case, the field catalog must be completely created by the calling program.

Case 3:

The data table's line type either contains no references to the ABAP Dictionary or itonly contains references to individual global structure fields or data elements.

In this case, the field catalog must be created entirely by the calling program.

Cases 2 and 3 are described in detail below.

340 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 351: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Field Catalog

Figure 143: Overview of the Field Catalog Structure

The details provided below only relate to cases 2 and 3.

In the calling program, create the field catalog as follows:

� Define an internal table for the field catalog, based on the lvc_t_fcat global tabletype and a line-compatible structure as a work area.

� Fill the work area's fields for each relevant column in your data table, and insertit in the internal table for the field catalog.

Enter a data table column name for the fieldname field. This field is used to assign afield catalog column to a data table column.

The other fields in the field catalog can be broken down into two groups as regardsusage when setting up a field catalog:

� The reference to global types (structure fields in the ABAP Dictionary) is createdusing the ref_field and ref_table fields.

� All other fields in the field catalog contain values for the column characteristics.

When you enter values for the ref_table and possibly ref_field, all type definitions ofthe specified structure fields will be transferred from the ABAP Dictionary. You canoverwrite these using values from individual fields from the last group.

If you do not enter any values for ref_field or ref_table, you may have toentervaluesfor all fields in the last group.

2005/Q4 © 2005 SAP AG. All rights reserved. 341

Page 352: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Figure 144: Column Typing with Dictionary Reference

The fieldname column in the field catalog contains the data table's column names.Each column in the data table whose formatting you wish to control must have aline in the field catalog.

If you want to refer to a field of a global structure type that has the same name, it isenough to enter the name of this structure in the ref_table field. You only need toenter the field name from the structure in the ref_field field if the column name of thedata table and structure field name differ.

342 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 353: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Field Catalog

Adding or Changing Columns

Figure 145: Example: Adding and Changing Columns (1)

In the example outlined above, the data table is made up of fields (columns) of theSBOOK type and two others. These must be described in the field catalog, alongwith the column to be hidden.

2005/Q4 © 2005 SAP AG. All rights reserved. 343

Page 354: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Figure 146: Example: Adding and Changing Columns (2)

The above example shows a semi-automatic field description: Part of the fielddescription comes from the Dictionary structure(SBOOK), while another part isexplicitly defined in the field catalog (it_fieldcat).

The field catalog (internal table) is filled in the program and is passed on togetherwith the name of the Dictionary structure during the method call. The information ismerged accordingly in the set_table_for_first_display method.

Note that the fields of the it_sbook data table must also contain useful entries thatcannot be read from the SBOOK table.

If you set up the field catalog semi-automatically or manually, you should check that itis consistent by double right-clicking in an area of the ALV grid that does not containany data (for example, the heading), keeping the Shift key pressed.

344 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 355: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Field Catalog

Figure 147: Output Attributes of a Column

col_pos: field

To calculate the column position, hidden columns, but no exceptions must be takeninto account. Without explicit positioning, fields that are manually attached to thefield catalog are positioned before the other data table fields. Exceptions are alwaysdisplayed in the first column.

emphasize field:

To highlight in a standard color, set �X� here.

Alternatively, you can determine the color yourself by entering a four-digit code thatmust adhere to the following convention:

C<col_constant> {0|1}{0|1}.In this context, <col_constant> represents a colorconstant of the col type group. The second digit determines whether the color willbe displayed intensified. If the third digit is 1, the display is inverted. For example:C300, C401.

no_out field:

The column is hidden in the list (screen or print), but appears in the field selectiondialogs of the standard functions (sorting, filter).

tech field:

The column is not displayed in the list or in the field selection dialogs.

2005/Q4 © 2005 SAP AG. All rights reserved. 345

Page 356: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

For further information, refer to the online documentation.

Figure 148: Format attributes of column content

Similar to the formatting options for currency fields, you can use the decmlfield anddecimals_o fields, to determine the number of decimal places.

These entries impact on numeric content.

If you would like to output a column as an icon, set the icon field of the layoutstructure to �X�. Run the SHOWICON report, to display an overview of the icons.Note that only some icons can be printed.

To display a column as a symbol, set the symbol field of the layout structure to �X�.Run the report SHOWSYMB, to display an overview of symbols.

For further information, refer to the online documentation.

346 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 357: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Field Catalog

Facilitated DiscussionAny questions can now be discussed.

Discussion QuestionsUse the following questions to engage the participants in the discussion. Feel free touse your own additional questions.

See list of objectives

2005/Q4 © 2005 SAP AG. All rights reserved. 347

Page 358: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Lesson Summary

You should now be able to:� Explain the purpose of the field catalog� Add columns to the ALV Grid Control and change ALV columns

348 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 359: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Layout

Lesson:326

ALV Grid Control - LayoutLesson Duration: 80 Minutes

Lesson OverviewIn this lesson you will learn how to change the layout of an ALV Grid Control.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Create the layout structure of an ALV Grid Control� Set colors of lines and cells in the ALV Grid Control� Hide standard toolbar functions

No notes

Business ExampleYou are a programmer at ABC Travel. You have been requested to display some linesin the ALV output in red, depending on the content. Other lines are to be displayedin orange, again depending on the content. As usual, it is up to you to complete thisdifficult task.

Filling and Passing on the Layout Structure

Figure 149: Filling and Passing On the Layout Structure

2005/Q4 © 2005 SAP AG. All rights reserved. 349

Page 360: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

You can change the layout of your ALV Grid Control, for example, select the title,create a striped (zebra) pattern for the lines, or optimize the column width.

To do this, create the <wa_layout> work area in the program, with referenceto the Dictionary structure lvc_s_layo and fill the relevant fields, such as<wa_layout>-grid_title, <wa_layout>-cwidth_opt, or <wa_layout>-zebra.

Then, pass on the work area to the is_layout parameter of the set_table_for_first_dis-play method.

Figure 150: Key Fields of the Layout Structure

350 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 361: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Layout

lvc_s_layo is a global structure type. Fields include the following:

� grid_title: A title with a maximum of 70 digits� zebra: If �X�, the list is displayed with a striped pattern.� no_headers: If�X�, no column headers are displayed.� sel_mode: Setting that determines how many cells, lines, and columns can

be selected.� cwidth_opt: If �X� all column widths are optimized. The column heading and

the cell contents are then displayed.� info_fname: Additional data table field that contains information on the

required line colors.� ctab_fname: Additional data table field that contains information on the

required cell colors.� For more fields and details, refer to the following sections or to the online

documentation.

Figure 151: Selection of Cells, Columns, and Lines

Depending on the value you enter in the sel_mode field in the layout structure, userscan select individual or several lines or cells.

To select several entries, select the Ctrl key and keep the mouse button pressed.

To make a selection from one entry to another, select the Shift key and keep themouse button pressed.

2005/Q4 © 2005 SAP AG. All rights reserved. 351

Page 362: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Figure 152: Display of Threshold Values: Exceptions

You can use exceptions to display whether threshold values have been achieved,exceeded, or not achieved, on a line-by-line basis. Proceed as follows:

Add a one-digit character field to your data table structure.

Fill this field for each line in your data table, based on the desired threshold value: 0 =Grey, 1 = Red, 2 = Yellow, 3 = Green, Space = Nothing.

Enter the name of the exception column in the excp_fname field of the layoutstructure, and pass the layout structure to the is_layout parameter of theset_table_for_first_display method.

If you enter �X� in the excp_led field of the layout structure, colored LEDs aredisplayed instead of the normal traffic light icons.

352 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 363: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Layout

Figure 153: Sort Criteria for First List Output

Data in the ALV Grid Control can be dynamically sorted by users.

To sort data in a certain way at the very beginning, you must enter an internal table forthe it_sort parameter of the set_table_for_first_display method. Use the lvc_t_sorttype for this table.

In this internal table, you must insert a line for each field that will be used as a sortcriterion.

� Enter the column name in fieldname.� If you use more than one sort criterion, you must enter the sequence in which the

sort criterion will be evaluated in the spos field in each case. Alternatively, youcan also insert the fields in the required sequence in the sort criteria's internaltable.

� Enter �X� in the up field, if you wish to sort the the entries in ascending order.

2005/Q4 © 2005 SAP AG. All rights reserved. 353

Page 364: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Colors of Lines and Cells

Figure 154: Changing the Line Color

If the field catalog is to be set up automatically using a global structure type, it isenough to maintain another field for the color values in the data table. This field shouldbe the last component of the data table's line type. If the original global structure typeis used as the line type for the ALV Grid Control, the color values are not displayed asa column on the screen. Instead, only the color required for the line is used.

The INCLUDE TYPE (or INCLUDE STRUCTURE) statement provides a simpleoption for defining the required line type for the data table locally in the program.

Fill the color column of your data table. As a rule, adhere to the following convention:�C<color_constant>10�. In this context, <color_constant> represents the eight colorconstants of the COL type group that you must incorporate into your program, forexample using the TYPE-POOLS col statement.

In the info_fname field, enter the component name of your color column for astructure of the global type lvc_s_layo and pass the structure to the parameteris_layout of the method set_table_for_first_display.

354 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 365: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Layout

Figure 155: Color Options

The value of the color field is made up of four components:

� The letter �C�� The number of one of the eight colors� 1 (intensified display) or 0 (intensified display off)� 1 (inversion of foreground and background color) or 0 (no inversion)

For example: C111, C710, C501

For an overview of colors, refer to the online documentation for the ABAP commandFORMAT.

2005/Q4 © 2005 SAP AG. All rights reserved. 355

Page 366: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Hiding Standard Functions

Figure 156: Hiding Standard Functions

Depending on the application and the data displayed in the ALV Grid Control, onlysome standard functions are useful. You can display either only a subset of thestandard functions, or hide the entire toolbar.

To hide individual functions, define an internal table of the ui_functions type. Fillthe internal table with the name of the functions that are to be kept inactive. Inactivefunctions on the application toolbar are not displayed. Inactive functions that areassigned a menu entry, on the other hand, are grayed out.

The possible function codes are defined as constants of the class cl_gui_alv_grid. Theclass constants for function codes all have the prefixMC_FC_. The prefix MC_MB_represents an entire menu in the toolbar.

Finally, pass the table to the standard functions when you call theset_table_for_first_display method.

To completely deactivate all functions on the application toolbar, you can use theMC_FC_EXCL_ALL class constant.

To hide the entire toolbar, only set the no_toolbar parameter of the layout structureto �X� and pass this structure to set_table_for_first_display.

We will look at the (event-driven) addition of functions to the application toolbar ata later stage.

356 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 367: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Layout

335 Exercise 19: ALV Grid Control - FieldCatalog and LayoutExercise Duration: Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Use the field catalog to add user-defined columns and hide existing columns� Influence the ALV Grid Control layout at the time of implementation

Business ExampleInstead of displaying the occupied and maximum spaces for each flight class, theflight list should now only display one value: The number of free seats. To enhancereadability, the list is to be output with a striped zebra pattern, and the number of freeseats should be indicated using traffic lights.

System DataSystem: Will be announced by trainerClient: Will be announced by trainerUser ID: Will be announced by trainerPassword: Will be announced by trainerSet up instructions:

1. No particular settings required when a standard training system is used.

Task:Change your list so that the fields with the occupied and maximum number of seatsfor the classes economy, business, and first class will be hidden, and the total numberof free seats displayed instead. To improve readability, a traffic light should appearin front of each flight, as determined by a threshold value. This light will specifywhether the flight is fully booked, nearly booked, or whether there are still seatsavailable. This list is also to appear with a zebra pattern.

1. Use your program from the last exercise or copy the sample solutionTAW10_ALVS_1from the packageBC_TAW10.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 357

Page 368: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

2. Change the definition of your internal table for the flights. Attach the columnsfreeseats and lights to the internal table. The freeseats field should have thesame type as the seatsmax table field and the lights field should have a characterfield with a length of 1.

3. In the main program for the ALV Grid Control, create a layout structure and afield catalog (internal table) with a work area.

4. During data selection, calculate the total number of free seats for a flight. Foreach flight, enter the values 1, 2, or 3 for the lights field, depending on whetherthe flight is fully booked, there are only a maximum of 10 seats, or more than10 seats available.

5. In the flow logic of screen 100, create the set_field_catalog module under PBO(Process Before Output). The module can be created in the main program. Takenote of the module sequence. Fill the field catalog so that the free seats appear inthe last column of the list. Hide any other seat-related fields.

6. In the flow logic, create another module: set_layout output. Create this modulein the main program as well. Fill the layout structure so that a light appearsfor each flight, based on the values in the lights column. Format the list in astriped zebra pattern.

7. Go to the manage_alv_grid module and pass the field catalog and the layoutstructure to the set_table_for_first_display method.

8. Activate the entire program, start it, and view your list.

358 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 369: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Layout

Solution 19: ALV Grid Control - Field Catalogand LayoutTask:Change your list so that the fields with the occupied and maximum number of seatsfor the classes economy, business, and first class will be hidden, and the total numberof free seats displayed instead. To improve readability, a traffic light should appearin front of each flight, as determined by a threshold value. This light will specifywhether the flight is fully booked, nearly booked, or whether there are still seatsavailable. This list is also to appear with a zebra pattern.

1. Use your program from the last exercise or copy the sample solutionTAW10_ALVS_1from the packageBC_TAW10.

a) Carry out this step as normal.

2. Change the definition of your internal table for the flights. Attach the columnsfreeseats and lights to the internal table. The freeseats field should have thesame type as the seatsmax table field and the lights field should have a characterfield with a length of 1.

a) See the source text in the sample solution.

3. In the main program for the ALV Grid Control, create a layout structure and afield catalog (internal table) with a work area.

a) See the source text in the sample solution.

4. During data selection, calculate the total number of free seats for a flight. Foreach flight, enter the values 1, 2, or 3 for the lights field, depending on whetherthe flight is fully booked, there are only a maximum of 10 seats, or more than10 seats available.

a) See the source text in the sample solution.

5. In the flow logic of screen 100, create the set_field_catalog module under PBO(Process Before Output). The module can be created in the main program. Takenote of the module sequence. Fill the field catalog so that the free seats appear inthe last column of the list. Hide any other seat-related fields.

a) See the source text in the sample solution.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 359

Page 370: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

6. In the flow logic, create another module: set_layout output. Create this modulein the main program as well. Fill the layout structure so that a light appearsfor each flight, based on the values in the lights column. Format the list in astriped zebra pattern.

a) See the source text in the sample solution.

7. Go to the manage_alv_grid module and pass the field catalog and the layoutstructure to the set_table_for_first_display method.

a) See the source text in the sample solution.

8. Activate the entire program, start it, and view your list.

a) Carry out this step as normal.

Result

Solution program: TAW10_ALVS_2

REPORT taw10_alvs_2 message-id taw10.

TYPE-POOLS icon.

INCLUDE TAW10_VEHICLES_2.

INCLUDE TAW10_AIRPLANES_2.

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.

DATA: r_container TYPE REF TO cl_gui_custom_container,

r_alv_grid TYPE REF TO cl_gui_alv_grid.

* Define structure for ALV grid

Continued on next page

360 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 371: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Layout

data: begin of wa_flights.

include type sflight.

data: freeseats type sflight-seatsmax,

lights,

end of wa_flights.

DATA: it_flights like TABLE OF wa_flights.

* Layout structure for ALV grid

data: wa_layout type lvc_s_layo.

* Field catalog for ALV grid

data: it_fieldcat type lvc_t_fcat,

wa_fieldcat like line of it_fieldcat.

AT LINE-SELECTION.

CHECK NOT gl_hide_planetype IS INITIAL.

* Caculate number of free seats

SELECT * FROM sflight INTO wa_flights

WHERE planetype = gl_hide_planetype.

wa_flights-freeseats = wa_flights-seatsmax + wa_flights-seatsmax_b

+ wa_flights-seatsmax_f - wa_flights-seatsocc

- wa_flights-seatsocc_b

- wa_flights-seatsocc_f.

* Set traffic lights depending on the number of free seats

if wa_flights-freeseats = 0.

wa_flights-lights = ’1’.

elseif wa_flights-freeseats < 10.

wa_flights-lights = ’2’.

else.

wa_flights-lights = ’3’.

endif.

append wa_flights to it_flights.

endselect.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 361

Page 372: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

IF sy-subrc = 0.

CALL SCREEN ’100’.

ELSE.

MESSAGE s100 with gl_hide_planetype.

ENDIF.

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

362 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 373: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Layout

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

CLEAR gl_hide_planetype.

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

*& Module manage_alv_grid OUTPUT

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

* text

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

MODULE manage_alv_grid OUTPUT.

*** Create object of class CL_GUI_CUSTOM_CAONTAINER to manage data !

IF NOT r_container IS BOUND.

CREATE OBJECT r_container

EXPORTING

container_name = ’MY_CONTAINER’

EXCEPTIONS

OTHERS = 6.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDIF.

*** create object of class cl_gui_alv_grid to visualize data !

IF NOT r_alv_grid IS BOUND.

CREATE OBJECT r_alv_grid

EXPORTING

i_parent = r_container

EXCEPTIONS

OTHERS = 5.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 363

Page 374: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

ENDIF.

ENDIF.

*** Call method to visualize data of internal table ************

CALL METHOD r_alv_grid->set_table_for_first_display

EXPORTING

i_structure_name = ’SFLIGHT’

* Set layout

is_layout = wa_layout

CHANGING

it_outtab = it_flights

* Set field catalog

it_fieldcatalog = it_fieldcat

EXCEPTIONS

OTHERS = 4.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDMODULE. " manage_alv_grid OUTPUT

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

*& Module USER_COMMAND_0100 INPUT

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

* text

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

MODULE user_command_0100 INPUT.

CASE sy-ucomm.

WHEN ’BACK’.

LEAVE TO SCREEN 0.

ENDCASE.

ENDMODULE. " USER_COMMAND_0100 INPUT

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

*& Module set_layout OUTPUT

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

* text

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

module set_layout output.

Continued on next page

364 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 375: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Layout

wa_layout-grid_title = ’Flüge anzeigen’(fli).

wa_layout-zebra = ’X’.

wa_layout-excp_fname = ’LIGHTS’.

endmodule. " set_layout OUTPUT

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

*& Module set_field_catalog OUTPUT

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

* text

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

module set_field_catalog output.

* Set new field FREESEATS

wa_fieldcat-fieldname = ’FREESEATS’.

wa_fieldcat-ref_field = ’SEATSMAX’.

wa_fieldcat-ref_table = ’SFLIGHT’.

wa_fieldcat-reptext = ’freie Plätze’(fse).

wa_fieldcat-col_pos = 11.

append wa_fieldcat to it_fieldcat.

* Hide fields in ALV grid

clear wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSMAX’.

wa_fieldcat-no_out = ’X’.

append wa_fieldcat to it_fieldcat.

clear wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSMAX_B’.

wa_fieldcat-no_out = ’X’.

append wa_fieldcat to it_fieldcat.

clear wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSMAX_F’.

wa_fieldcat-no_out = ’X’.

append wa_fieldcat to it_fieldcat.

clear wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSOCC’.

wa_fieldcat-no_out = ’X’.

append wa_fieldcat to it_fieldcat.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 365

Page 376: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

clear wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSOCC_B’.

wa_fieldcat-no_out = ’X’.

append wa_fieldcat to it_fieldcat.

clear wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSOCC_F’.

wa_fieldcat-no_out = ’X’.

append wa_fieldcat to it_fieldcat.

clear wa_fieldcat.

wa_fieldcat-fieldname = ’PLANETYPE’.

wa_fieldcat-no_out = ’X’.

append wa_fieldcat to it_fieldcat.

endmodule. " set_field_catalog OUTPUT

366 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 377: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Layout

Lesson Summary

You should now be able to:� Create the layout structure of an ALV Grid Control� Set colors of lines and cells in the ALV Grid Control� Hide standard toolbar functions

2005/Q4 © 2005 SAP AG. All rights reserved. 367

Page 378: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Lesson:346

ALV Grid Control - EventsLesson Duration: 1 Minutes

Lesson OverviewThe ALV Grid Control can also react to user-defined entries. To demonstrate howthis works in principle, in this lesson we will look at how the system reacts to a userdouble-clicking the mouse button.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� React to ALV Grid Control events

The theory presented in this lesson recaps on the material covered in the lesson onevents, which means that a quick overview will suffice. The priority here is forparticipants to implement the theory using a practical example. In other words, thefocus here is on the actual exercise.

Business ExampleYou are a programmer at ABC Reisen. You have been requested to enhance the list sothat when users double-click on a line, a dialog box appears displaying the free seatsfor each flight class (economy, business, and first class).

Events for ALV Grid Control - Double-ClickingAn ALV Grid Control can react to a user double-clicking the mouse button. Onepossible reaction is that a subsequent processing is triggered in which additionalinformation is displayed, for example.

368 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 379: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Events

Figure 157: ALV Grid Control - Double-Click

In the example displayed above, the booking data of the individual customers oraircraft data could be displayed in addition to the flight data. From a technical point ofview, the event DOUBLE_CLICK is caught using a handler method.

2005/Q4 © 2005 SAP AG. All rights reserved. 369

Page 380: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Figure 158: ALV Grid Control - Reaction to Double-Click

Here, a static handler method would be even easier, and would suffice. However, thiscould distract participants from the actual topic, so be prepared for a discussion.

A handler method can be either a class method (static method) or an object's instancemethod. If a class method is defined as a handler method, there is no need toinstantiate an object of the handling class, to use the method.

To create a handler object for an event, you must first of all define a class. Thisclass has a public method (in the PUBLIC SECTION) that can react to an event. Inthe handler method's implementation, create the source text that will run when youtrigger the event. The method receives the information delivered by the event fromthe position of the mouse when the user executes a double-click, and in the controlexample, generates an information message that displays the line and field where themouse is clicked.

370 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 381: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Events

349 Exercise 20: ALV Grid Control - EventsExercise Duration: Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� React to a user mouse-click in the ALV Grid Control

Business ExampleWhen a user double-clicks a line in the flight list, a dialog box should appear displayingthe number of available seats for each flight class (economy, business, and first class).

System DataSystem: Will be announced by trainerClient: Will be announced by trainerUser ID: Will be announced by trainerPassword: Will be announced by trainerSet up instructions:

1. No particular settings required when a standard training system is used.

Task:Add the following function to your flight list: When users select a flight, a dialog boxappears displaying the number of free seats for each flight class (economy, business,and first class). To do this, you must write a handler method in a user-defined class forthe double_click event of the ALV Grid Control (class: CL_GUI_ALV_GRID).

1. Use your program from the last exercise or copy the sample solutionTAW10_ALVS_2from the packageBC_TAW10.

2. In your program, create a local class, and in this class write a handler method forthe on_double_click event of the CL_GUI_ALV_GRID class.

3. The handler method should provide more information on the number of freeseats for a flight (selected line), by specifying in a dialog box the number ofspaces left for each of the categories first, business, and economy class.

4. Remember to register for the event at the appropriate location.

5. Activate your program, start it, and test what happens when you double-click ona line in the ALV list.

2005/Q4 © 2005 SAP AG. All rights reserved. 371

Page 382: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Solution 20: ALV Grid Control - EventsTask:Add the following function to your flight list: When users select a flight, a dialog boxappears displaying the number of free seats for each flight class (economy, business,and first class). To do this, you must write a handler method in a user-defined class forthe double_click event of the ALV Grid Control (class: CL_GUI_ALV_GRID).

1. Use your program from the last exercise or copy the sample solutionTAW10_ALVS_2from the packageBC_TAW10.

a) Carry out this step as normal.

2. In your program, create a local class, and in this class write a handler method forthe on_double_click event of the CL_GUI_ALV_GRID class.

a) See the source text in the sample solution.

3. The handler method should provide more information on the number of freeseats for a flight (selected line), by specifying in a dialog box the number ofspaces left for each of the categories first, business, and economy class.

a) See the source text in the sample solution.

4. Remember to register for the event at the appropriate location.

a) See the source text in the sample solution.

5. Activate your program, start it, and test what happens when you double-click ona line in the ALV list.

a) Carry out this step as normal.

Result

Solution program: TAW10_ALVS_3

REPORT TAW10_ALVS_3 MESSAGE-ID taw10.

TYPE-POOLS icon.

INCLUDE TAW10_VEHICLES_3.

INCLUDE TAW10_AIRPLANES_3.

DATA: r_vehicle TYPE REF TO lcl_vehicle,

Continued on next page

372 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 383: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Events

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.

DATA: r_container TYPE REF TO cl_gui_custom_container,

r_alv_grid TYPE REF TO cl_gui_alv_grid.

* Define structure for ALV grid

DATA: BEGIN OF wa_flights.

INCLUDE TYPE sflight.

DATA: freeseats TYPE sflight-seatsmax,

lights,

END OF wa_flights.

DATA: it_flights LIKE TABLE OF wa_flights.

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

* CLASS lcl_event_handler DEFINITION

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

*

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

CLASS lcl_event_handler DEFINITION.

PUBLIC SECTION.

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

CLASS-METHODS on_double_click FOR EVENT double_click

OF cl_gui_alv_grid

IMPORTING es_row_no.

ENDCLASS. "lcl_event_handler DEFINITION

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

* CLASS lcl_event_handler IMPLEMENTATION

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

*

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 373

Page 384: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

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

CLASS lcl_event_handler IMPLEMENTATION.

METHOD on_double_click.

DATA: lwa_flights LIKE wa_flights,

eco_free(8) type c,

bus_free(8) type c,

fir_free(18) type c,

text TYPE string.

READ TABLE it_flights INTO lwa_flights

INDEX es_row_no-row_id.

eco_free = lwa_flights-seatsmax - lwa_flights-seatsocc.

bus_free = lwa_flights-seatsmax_b - lwa_flights-seatsocc_b.

fir_free = lwa_flights-seatsmax_f - lwa_flights-seatsocc_f.

concatenate ’Economy Class:’ eco_free

’ Business Class:’ bus_free

’ First Class:’ fir_free

into text.

MESSAGE text TYPE ’I’.

ENDMETHOD. "handler_method

ENDCLASS. "lcl_event_handler IMPLEMENTATION

DATA: wa_layout TYPE lvc_s_layo.

DATA: it_fieldcat TYPE lvc_t_fcat,

wa_fieldcat LIKE LINE OF it_fieldcat.

AT LINE-SELECTION.

CHECK NOT gl_hide_planetype IS INITIAL.

SELECT * FROM sflight INTO wa_flights

WHERE planetype = gl_hide_planetype.

Continued on next page

374 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 385: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Events

wa_flights-freeseats = wa_flights-seatsmax + wa_flights-seatsmax_b

+ wa_flights-seatsmax_f - wa_flights-seatsocc

- wa_flights-seatsocc_b

- wa_flights-seatsocc_f.

IF wa_flights-freeseats = 0.

wa_flights-lights = ’1’.

ELSEIF wa_flights-freeseats < 10.

wa_flights-lights = ’2’.

ELSE.

wa_flights-lights = ’3’.

ENDIF.

APPEND wa_flights TO it_flights.

ENDSELECT.

IF sy-subrc = 0.

CALL SCREEN ’100’.

ELSE.

MESSAGE s100 WITH gl_hide_planetype.

ENDIF.

START-OF-SELECTION.

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

******* create travel_agency *****************************************

CREATE OBJECT r_agency EXPORTING im_name = ’Fly 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.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 375

Page 386: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

******* create truck *****************************************

CREATE OBJECT r_truck EXPORTING im_make = ’VOLVO’

im_cargo = 48.

***** Create CARRIER ********************************************

CREATE OBJECT r_carrier EXPORTING im_name = ’Smile Travel’.

***** Passenger Plane ********************************************

CREATE OBJECT r_passenger EXPORTING

im_name = ’LH BERLIN’

im_planetype = ’747-400’

im_seats = 345.

***** cargo Plane ************************************************

CREATE OBJECT r_cargo EXPORTING

im_name = ’US Hercules’

im_planetype = ’747-500’

im_cargo = 533.

******* create hotel *****************************************

CREATE OBJECT r_hotel EXPORTING im_name = ’Holiday Inn’

im_beds = 345.

******* show attributes of all partners of travel_agency ******

r_agency->display_agency_partners( ).

CLEAR gl_hide_planetype.

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

*& Module manage_alv_grid OUTPUT

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

* text

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

MODULE manage_alv_grid OUTPUT.

IF NOT r_container IS BOUND.

CREATE OBJECT r_container

EXPORTING

container_name = ’MY_CONTAINER’

EXCEPTIONS

Continued on next page

376 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 387: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Events

OTHERS = 6.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDIF.

IF NOT r_alv_grid IS BOUND.

CREATE OBJECT r_alv_grid

EXPORTING

i_parent = r_container

EXCEPTIONS

OTHERS = 5.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

*** set handler to react on double-click *******************

SET HANDLER lcl_event_handler=>on_double_click FOR r_alv_grid.

ENDIF.

CALL METHOD r_alv_grid->set_table_for_first_display

EXPORTING

i_structure_name = ’SFLIGHT’

is_layout = wa_layout

CHANGING

it_outtab = it_flights

it_fieldcatalog = it_fieldcat

EXCEPTIONS

OTHERS = 4.

IF sy-subrc <> 0.

MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno

WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

ENDIF.

ENDMODULE. " manage_alv_grid OUTPUT

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

*& Module USER_COMMAND_0100 INPUT

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

* text

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 377

Page 388: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

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

MODULE user_command_0100 INPUT.

CASE sy-ucomm.

WHEN ’BACK’.

LEAVE TO SCREEN 0.

ENDCASE.

ENDMODULE. " USER_COMMAND_0100 INPUT

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

*& Module set_layout OUTPUT

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

* text

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

MODULE set_layout OUTPUT.

wa_layout-grid_title = ’Flüge anzeigen’(fli).

wa_layout-zebra = ’X’.

wa_layout-excp_fname = ’LIGHTS’.

ENDMODULE. " set_layout OUTPUT

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

*& Module set_field_catalog OUTPUT

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

* text

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

MODULE set_field_catalog OUTPUT.

* Set new field FREESEATS

wa_fieldcat-fieldname = ’FREESEATS’.

wa_fieldcat-ref_field = ’SEATSMAX’.

wa_fieldcat-ref_table = ’SFLIGHT’.

wa_fieldcat-reptext = ’freie Plätze’(fse).

wa_fieldcat-col_pos = 11.

APPEND wa_fieldcat TO it_fieldcat.

* Hide fields in ALV grid

CLEAR wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSMAX’.

wa_fieldcat-no_out = ’X’.

Continued on next page

378 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 389: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: ALV Grid Control - Events

APPEND wa_fieldcat TO it_fieldcat.

CLEAR wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSMAX_B’.

wa_fieldcat-no_out = ’X’.

APPEND wa_fieldcat TO it_fieldcat.

CLEAR wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSMAX_F’.

wa_fieldcat-no_out = ’X’.

APPEND wa_fieldcat TO it_fieldcat.

CLEAR wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSOCC’.

wa_fieldcat-no_out = ’X’.

APPEND wa_fieldcat TO it_fieldcat.

CLEAR wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSOCC_B’.

wa_fieldcat-no_out = ’X’.

APPEND wa_fieldcat TO it_fieldcat.

CLEAR wa_fieldcat.

wa_fieldcat-fieldname = ’SEATSOCC_F’.

wa_fieldcat-no_out = ’X’.

APPEND wa_fieldcat TO it_fieldcat.

CLEAR wa_fieldcat.

wa_fieldcat-fieldname = ’PLANETYPE’.

wa_fieldcat-no_out = ’X’.

APPEND wa_fieldcat TO it_fieldcat.

ENDMODULE. " set_field_catalog OUTPUT

2005/Q4 © 2005 SAP AG. All rights reserved. 379

Page 390: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 4: ALV Grid Control TAW10_3

Lesson Summary

You should now be able to:� React to ALV Grid Control events

380 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 391: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Unit Summary

Unit SummaryYou should now be able to:� Describe the Control Framework� Create simple lists using ALV Grid Control� Explain the purpose of the field catalog� Add columns to the ALV Grid Control and change ALV columns� Create the layout structure of an ALV Grid Control� Set colors of lines and cells in the ALV Grid Control� Hide standard toolbar functions� React to ALV Grid Control events

2005/Q4 © 2005 SAP AG. All rights reserved. 381

Page 392: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit Summary TAW10_3

382 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 393: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5361 Exception Handling and RTTS

For more information, see the introductory instructor notes in the lesson.

Unit OverviewThis unit describes how closely the procedures and object-oriented parts of theprogramming language ABAP Objects are integrated, using the new exception conceptand language scope for Run Time Type Services (RTTS) as an example.

Unit ObjectivesAfter completing this unit, you will be able to:

� Create exception classes� Raise 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 to each other in ABAP Objects programs� Query type attributes at runtime� Create types dynamically

Unit ContentsLesson: Exception Handling in ABAP Objects .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .385

Procedure: Define Global Exception Classes ... . . . . . . . . . . . . . . . . . . . . . . . . . . .391Demonstration: Defining a Global Exception Class... . . . . . . . . . . . . . . . . . . . . .393Demonstration: Raising, Propagating, and Handling an Exception.. . . . .395Demonstration: Mapping Other Exceptions to the Original Exception ..403Exercise 21: Class-Based Exceptions.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .407

2005/Q4 © 2005 SAP AG. All rights reserved. 383

Page 394: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Exercise 22: (Optional): Mapping Exceptions to Each Other.. . . . . . . . . . . .417Lesson: RTTS (Run Time Type Service) .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .428

Exercise 23: RTTI: Querying Object Attributes .. . . . . . . . . . . . . . . . . . . . . . . . . . . .439Exercise 24: (Optional): RTTC: Creating Types at Runtime... . . . . . . . . . . .443

384 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 395: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

Lesson:362

Exception Handling in ABAP ObjectsLesson Duration: 90 Minutes

Lesson OverviewThis lesson provides a comprehensive introduction to the new class-based exceptionconcept in ABAP Objects. The essential attributes and activities are presented indetail and then applied in practical examples for SAP Web Application Server 6.20.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Create exception classes� Raise 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 to each other in ABAP Objects programs

It is particularly important to point out that these are enhancements of the existingfeatures of ABAP Objects. Naturally, the old exceptions concept can still be used butthey will no longer be developed.

Participants with experience in Java will notice marked similarities in syntax andruntime behavior. The main point again is to present the additional user-friendlyoptions available in ABAP Objects and the ABAP Workbench.

In the unlikely event that participants are (still) skeptical about object-orientedprogramming, it may be helpful to motivate them with a simple example fromprocedural programming: Until now, subroutines could not raise exceptions thatcould be handled. Instead, you had to implement a relationship check yourself, usingEXIT (or RETURN as of SAP Web AS 6.10) and auxiliary variables that you had todefine. Now, any processing block in ABAP Objects can raise a class-based exception.

Business ExampleYou need to use the new exceptions concept in your ABAP Object programs.

2005/Q4 © 2005 SAP AG. All rights reserved. 385

Page 396: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Class-Based Exception HandlingWe use the term exception to refer to a situation that arises while a program is beingexecuted, when there is no point in continuing to run the program in the normal way.SAP Web AS 6.10 introduced a new ABAP Objects exception concept, parallel tothe existing concept. Exceptions and exception handling are now based on classes.This concept includes the concepts that preceded it but also enhances (and thusreplaces) them.

Figure 159: An Overview of the Class-Based Exception Concept

Class-based exceptions are raised either by the RAISE EXCEPTION statement or bythe runtime environment. Division by zero, for example, would be an example of anexception raised by the runtime environment.

In an exception situation, an exception is represented by an exception object - thatis, an instance of an exception class. The attributes of each exception object containinformation about the error situation.

When handling an exception, you can have it raise new exceptions and thus create achain of exceptions. Therefore, in special cases, you can catch a runtime exceptionand have it raise an exception of its own.

You can define exception classes yourself, but there is already a range of predefinedexception classes in the system, particularly for exceptions in the runtime environment.You usually create exception classes globally in the Class Builder, but you can alsodefine local exception classes within a program or global class.

386 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 397: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

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. Inparticular, all previously catchable runtime errors can now be handled as class-basedexceptions.

If a class-based exception is raised, the system interrupts the normal program flow andtries 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, which are themselves derivedfrom the common superclass CX_ROOT.

Figure 160: Exception Classes: The Inheritance Hierarchy

The way in which exception classes are assigned to one of these three paths in thehierarchy defines how the associated exceptions are propagated.

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 allexception classes:.The GET_SOURCE_POSITION method returns the name of themain program and (if relevant) the names of the include program and the line numberin the source code where the exception occurred. The GET_TEXT method returnsan exception text in the form of a string.

Newly defined exception classes inherit from one of these superclasses, so othercomponents can be added. These are usually individual exception texts.

2005/Q4 © 2005 SAP AG. All rights reserved. 387

Page 398: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

You can assign several texts to each class. The IDs assigned to these are created bythe Class Builder as identically named static constants. You can then specify whichtext is to be used when an exception is raised by passing one of these constants to theimport parameter TEXTID of the instance constructor.

All exception classes inherit the KERNEL_ERRID attribute from CX_ROOT. Thisattribute contains the name of the appropriate runtime error if the exception wasraised by the runtime environment, for example, BCD_ZERODIVIDE if the programcatches a CX_SY_ZERODIVIDE exception (division by zero). If the exception is notlisted, a runtime error occurs.

An exception can only be handled if the statement that could raise it is enclosed in aTRY-ENDTRY block. The exception is then handled using the CATCH statement inthe TRY-ENDTRY block.

Figure 161: Structure of a TRY-ENDTRY Block

The TRY block contains the set of statements that handle the exceptions. If anexception occurs in the TRY block, the system searches first for a CATCH statementin the same TRY-ENDTRY block and then gradually searches outwards in all theenclosing TRY-ENDTRY blocks that handle the exception. If it finds one, it navigatesto this handler. If it cannot find a handler but the TRY-ENDTRY block is in aprocedure, the system then tries to propagate the exception to the calling program.

A CATCH block contains the exception handler that is executed if a specifiedexception has occurred in the associated TRY block. You can specify any number ofexception classes to the CATCH statement. In this way, you define an exceptionhandler for all these exception classes and their subclasses.

388 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 399: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

Like all control structures in ABAP Objects, TRY-ENDTRY blocks can be nestedto any depth. Thus the TRY block, CATCH blocks, and the CLEANUP block inparticular can contain complete TRY-ENDTRY blocks.

After an exception occurs, the system searches through the listed exception handlersin the order specified. It then executes the first exception handler whose CATCHstatement contains the relevant exception class or one of its superclasses.

A CLEANUP block is executed if the TRY-ENDTRY block is exited because thesystem cannot find a handler for an exception within a specific TRY-ENDTRY blockbut the exception is handled in a surrounding TRY-ENDTRY block or propagated toa calling program.

In the following sections, we will focus on global exception classes that are handledlocally. Remember, you can also use local exception classes handled locally or globalexception classes handled in methods of other global classes.

Example: Handling a Predefined ExceptionThere are two special features to note in the following example. First, we will simplyinstantiate a standard exception class, rather than define a new one. Second, theexception will be raised by the runtime system as the result of an error, rather than bya procedure.

Figure 162: Example Syntax for Handling Predefined Exceptions

2005/Q4 © 2005 SAP AG. All rights reserved. 389

Page 400: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

In the above calculation, if the value range for data type I is exceeded, the runtimesystem raises the exception CX_SY_ARITHMETIC_OVERFLOW. This exception ishandled in the implemented CATCH block. The reference to the appropriate instanceis stored in the data object REF_EXC. The handler can then access the instance�sexception text using the functional method GET_TEXT. The text is stored in the dataobject 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 thatany string can 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 specifythe message type message_type.

If the value range for data type I (information) is not exceeded, no exception is raisedand the TRY block is processed completely. The processing block then continuesexecuting after the keyword ENDTRY.

The class CX_SY_ARITHMETIC_OVERFLOW is a subclass of the classesCX_SY_ARITHMETIC_ERROR, CX_DYNAMIC_CHECK, and CX_ROOT. Thusthe exception raised above can also be handled if you enter one of these classes afterthe CATCH statement.

Caution: This is a demonstration example that has been deliberately keptsimple. Normally, you would define the RESULT variable with numericaltype F to avoid a runtime error. You could then define the size of the resultvalue before using MOVE to convert to an integer variable if required.

As with the (obsolete) use of CATCH SYSTEM-EXCEPTIONS, this is also aboutcatching runtime errors that cannot be entirely excluded. A typical example of thiscan be found in widening cast assignments.

The ABAP keyword documentation for each statement lists the classes whoseexceptions may occur when that statement is executed. The following will show youhow to create your own global exception classes.

390 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 401: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

368Define Global Exception Classes

1. In the Class Builder, create a global class as described in the SAP Library. Whenyou enter its name, use the prefix CX_. Choose the option Exception Classas the Class Type.

Note: Do not change the default entry for Inherits from superclassunless you are fully aware of the consequences of doing so.

Figure 163: Creating Global Exception Classes

2. Give your exception class additional attributes if necessary (for example, forgeneric extensions to exception texts).

If these attributes are public, the Class Builder generates an appropriate instanceconstructor so that values can be set for these attributes when the exceptionis raised. The import parameters are generated with the same names as theattributes.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 391

Page 402: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

3. Save as many exception texts as you need. When you do so, you can insert yourattributes as parameters in the static text in the form &<attribute_name>&.

Note: For the first text you create yourself, always use a predefinedstatic constant as an ID. It always has the same name as the exceptionclass itself. If no text is specified explicitly when the exception is raised,the text with this ID is used instead.

For all other texts, define other IDs. The Class Builder then generates identicallynamed static constants automatically. When the exception is raised, you pass oneof these constants to the import parameter TEXTID to specify the appropriatetext for the exception instance.

Figure 164: Define Variable Exception Texts

Note: The exception texts of global exception classes are stored in theirtranslations in the Open Text Repository (OTR) . Note that several textscan be assigned to a single class. You assign a text to an exceptionusing the TEXTID attribute, which contains the globally unique IDof the text object in the OTR in an instance at runtime. The methodGET_TEXT then exports this text, replaces any text parameters with thecontents of the relevant attributes as necessary, and returns the text asa character string.

4. Activate your exception class.

392 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 403: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

Demonstration: Defining a Global Exception Class

PurposeYou should make clear how much the system supports developers. When using globalclasses they need only add the missing elements that fit their needs. In other words:You can�t go wrong.

You should also demonstrate how the features of the Class Builder are adaptedautomatically when you create an exception class.

System DataSystem: will be assignedClient: will be assignedUser ID: will be assignedPassword: will be assignedSet up instructions: No special settings required if you are using a standardSAP Web AS 6.20 training system1. Copy the SAPBC401_EXCT_HANDLE_EXCEP template program.

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 localclass LCL_PLANE and show the resulting unsatisfactory list display.

3. Create an exception class. Derive it from superclass CX_STATIC_CHECK.

4. Create a read-only public instance attribute for the plane type. Name theattribute PLANETYPE.

5. Enter a text for the predefined ID, such as: Airplane type ... isunknown..

Insert the airplane type generically using the public instance attribute.

6. Define other public static constants as IDs for another exception text. Suggestedname: CX_BC401_EXCD_PLANETYPE_F.

7. Define another text for this second ID, such as: Airplane type... isa cargo plane.

Insert the airplane type generically using the public instance attribute.

8. Activate the exception class

2005/Q4 © 2005 SAP AG. All rights reserved. 393

Page 404: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

9. Sample object in the package BC401:global class CX_BC401_EXCD_PLANETYPE

Propagating and Handling an ExceptionExceptions that occur in procedures do not necessarily need to be handled where theyoccur; they can be propagated to the caller of the procedure. The caller can thenhandle the exception itself or propagate it to its own caller, and so on. The highestlevels in which an exception can be propagated are processing blocks without localdata areas, that is, event blocks or dialog modules. The exceptions propagated by thecalled procedures must be dealt with there, as must any exceptions raised within thisprocessing block itself. Otherwise, a runtime error occurs.

To propagate an exception from a procedure, you generally use the RAISINGaddition when you are defining the procedure interface. In methods of local classesand subroutines, specify the RAISING addition directly when you are defining theprocedure:

METHODS meth_name ... RAISING cx_... cx_... or

FORM subr_name ... RAISING cx_... cx_....

After RAISING, list the exception classes whose instances are to be propagated. Inmethods of global classes, the exception classes whose instances are to be propagatedare entered in the exception table of the method in the Class Builder. You also needto set the Exception Class flag for each exception table. The process is similar forfunction modules. To set the indicator in the Function Builder, choose the Exceptionstab. A global method or function module can only raise class-based or conventionalexceptions.

394 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 405: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

Figure 165: 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 constantsdefined as additional text IDs in the exception class can also be used to supply thevalue. When the exception is raised, the appropriate text for that exception instanceis raised. After the exception has been caught, you can display the text using thefunctional method GET_TEXT.

If the caller does not catch the exception, it can be passed upwards to the next-levelcaller. Before control is passed to the next-level caller, the optional CLEANUP blockmay be executed. You then use this block to run the appropriate statements.

Demonstration: Raising, Propagating, and Handling anException

PurposeHere you should demonstrate that an actual instance of the exception class isgenerated, which the regular object-oriented ABAP Objects syntax elements thenaccess.

You also show the extended features of the ABAP Debugger as they relate to theclass-based exception concept. By displaying the reference contents, you should beable to emphasize the object-oriented approach of the new exception concept evenmore.

2005/Q4 © 2005 SAP AG. All rights reserved. 395

Page 406: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

System DataSystem: will be assignedClient: will be assignedUser ID: will be assignedPassword: will be assignedSet up instructions: No special settings required if you are using a standardSAP Web AS 6.20 training system1. Extend the signature of the method GET_ATTRIBUTES of the local class

LCL_PLANE copied in the previous demonstration program, so that itpropagates an instance of the global exception class.

2. Raise an exception within the method for both situations as follows:

� optional: If the key is wrong (sy-subrc = 4), set the standard text (textid = classname=>classname).

� For a cargo plane, (seatsmax_b = 0) set the additional text (textid = classname=>new_text_id).

In both cases, set the airplane type (planetype = me->type).

3. Handle the exception in the method DISPLAY_ATTRIBUTES of the local classLCL_CARRIER: Catch the exception when the method GET_ATTRIBUTES iscalled 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 listinstead of the unsatisfactory entries.

To do so, define a text variable with a suitable type locally. We suggest thename: L_EXC_TEXT.

5. Activate and execute the program.

6. Execute the program in debugging mode, thus demonstrating the features of theABAP Debugger when an exception is raised.

7. Sample object in package BC401:Executable program SAPBC401_EXCD_HANDLE_EX-CEP

396 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 407: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

Example: Raising, Propagating and Handling anException

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.

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

2005/Q4 © 2005 SAP AG. All rights reserved. 397

Page 408: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

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

...

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.

398 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 409: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

ENDMETHOD. "display_attributes

ENDCLASS. "lcl_carrier IMPLEMENTATION

The instance method GET_ATTRIBUTES of the local class LCL_PLANE displaysthe name and other attributes of the airplane. If the airplane type is not valid, raise andpropagate the exception you defined yourself : CX_BC401_EXCD_PLANETYPE. Inother words, there may be instances of airplanes in this scenario whose type is notvalid. For example, there may be no data for the airplane type in the table SAPLANEor the airplane may be a cargo plane. The exception class is written so that there is aseparate text available for each of these two situations. In one of the two cases, thedefault value is passed to the parameter TEXTID, while in the other an additionallydefined 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 ofthe class LCL_CARRIER. If the exception is raised, execution of the methodGET_ATTRIBUTES terminates and continues with the execution of the CATCHblock. Note that the program no longer executes the WRITE statements entered in theTRY block after the method call. The system copies the reference to the instance ofthe exception class to the local variable L_REF_EXC. The exported error text is setdynamically so that it contains context-sensitive information.

Hint: It would also have been possible to deal with the two errors by meansof two exception classes. You could then use different CATCH blocks to dealwith whichever of the two errors occurred. However, at this point we wantedto demonstrate how you would use different texts within one exception class.

Class-Based Exceptions in Debugging ModeIf an exception is raised, the name of the exception class is displayed in the ExceptionRaised field in debugging mode.

If this exception is caught using a CATCH block, this is displayed in the form of asuccess message. The pointer for the current statement then moves to this CATCHblock.

2005/Q4 © 2005 SAP AG. All rights reserved. 399

Page 410: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Figure 166: Class-Based Exceptions in Debugging Mode

Two buttons also appear. They allow you to display the values of the attributes of theexception instance and navigate to the point in the source code where the exceptionoccurred.

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 HierarchyThe following section explains consequences that arise from the choice of anexception class�s superclass. It also demonstrates how the exceptions in the runtimesystem are integrated into the inheritance hierarchy of the exception classes.

400 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 411: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

Figure 167: Integration of Standard Exceptions in the Runtime System

In subclasses of CX_STATIC_CHECK, the relevant exception must either behandled 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 ofCX_DYNAMIC_CHECK. You must either handle them or explicitly propagate themusing the RAISING addition. The difference is that this is not statically checked.No syntax warning is reported if the exception is neither handled nor propagated.If the exception is then raised, a runtime error occurs. Typical examples of thissituation are the predefined exceptions CX_SY_... for errors that occur in theruntime environment. These are usually subclasses of CX_DYNAMIC_CHECK.Forsubclasses of CX_NO_CHECK, the rule is that the corresponding exceptions cannotbe propagated explicitly using the RAISING addition. These exceptions can behandled. Otherwise, they are automatically propagated. Neither a syntax warning nora runtime error is caused directly where it is raised. Instead, all exceptions that are nothandled 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 predefinedexceptions with the prefix CX_SY_... for error situations in the runtime environmentare subclasses of CX_NO_CHECK.

. Nn w. u.

2005/Q4 © 2005 SAP AG. All rights reserved. 401

Page 412: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Mapping Exceptions to Each OtherFor the sake of clarity, you should understand that an exception can be propagatedthrough any number of call hierarchies before it is finally handled.

The following section shows how the raising of different exceptions can be interlinkedor chained. One exception can raise a second, and so on. Each instance should remainvalid, regardless of whether or not the associated CATCH block has already beenleft or not. In this respect, you must make sure that the previous exception instancecan always be accessed by means of at least one reference. The public instanceattribute PREVIOUS, inherited by all exception classes from CX_ROOT, provides aconvenient way of doing this.

Figure 168: Mapping Exceptions to Each Other

When raising the next exception, only one reference to the previous exceptioninstance must be passed to the new instance. You do this with the optional parameterPREVIOUS of the instance constructor � that is, using RAISE EXCEPTION. Inthis way, the new exception is mapped to the previous one. After the mappedexception has been caught, the instance attribute PREVIOUS contains a reference tothe previous exception instance, and so on. In this way, you can access each instancein the chain of exceptions. Therefore, you can follow the history of the raising ofthe exceptions in the program.

402 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 413: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

Demonstration: Mapping Other Exceptions to theOriginal Exception

PurposeYou should make clear how easy it is to get a reference to the previous exceptioninstance in a chain of exceptions using the public attribute PREVIOUS.

Caution: At this point, remind participants that chained exceptions must notbe confused with one exception that is passed up several call levels.

System DataSystem: will be assignedClient: will be assignedUser ID: will be assignedPassword: will be assignedSet up instructions: No special settings required if you are using a standardSAP Web AS 6.20 training system1. Copy the SAPBC401_EXCD_HANDLE_EXCEP sample program or the

previous demonstration program.

2. Activate and execute this copy.

Before the list is displayed, the user should receive a message informing him orher that at least one error situation could occur. Another information messageshould then display the text of the original exception. The list should then bedisplayed for the invalid airplane type, but not for those that follow it.

3. Create an exception class. Derive it from 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 classLCL_CARRIER in the demonstration program, so that it propagates an instanceof the global exception class.

6. Have the method raise an exception if the original exception is caught for theinvalid airplane type.

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 methodDISPLAY_ATTRIBUTES of the local class .LCL_CARRIER is called

2005/Q4 © 2005 SAP AG. All rights reserved. 403

Page 414: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

To do this, define a reference in the main program with the type of a globalexception class. We suggest the name REF_EXC.

8. If the exception occurs, export the dynamically specified text and display itas an information message.

To do so, define a text variable with a suitable type in the main program. Wesuggest the name: EXC_TEXT

Then export the reference to the original exception instance by accessing theappropriate attribute.

Use this reference to export the text from the original exception and display itas an information message.

To do so, define a text variable with a suitable type in the main program.Suggested name: PREVIOUS_TEXT

9. Activate and execute the program.

10. Execute the program in debugging mode, showing the content of the PREVIOUSattribute 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 ExceptionsAs in the previous example, the method GET_ATTRIBUTES has been definedand implemented in the local class LCL_PLANE. Another exception class,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

404 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 415: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

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.

...

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,

2005/Q4 © 2005 SAP AG. All rights reserved. 405

Page 416: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

previous_text TYPE string.

...

START-OF-SELECTION.

...

TRY.

CALL METHOD ref_carrier->display_attributes.

CATCH cx_bc401_excd_list INTO ref_exc.

exc_text = ref_exc->get_text( ).

MESSAGE exc_text TYPE ’I’.

previous_text = ref_exc->previous->get_text( ).

MESSAGE previous_text TYPE ’I’.

ENDTRY.

...

The exception for the invalid airplane type is caught in the instance methodDISPLAY_ATTRIBUTES of the class LCL_CARRIER. The exception text isdisplayed in the list. Another exception is then raised, since the list now containserrors. The reference to the first exception instance is passed to the second.

The exception for the list with the errors is now handled in the main program. First, theexception text is displayed as an information message. However, since the exceptionis mapped to a second exception for the invalid airplane type, the instance attributePREVIOUS contains a reference to the second exception. You use this reference toexport the text from the original exception and display it as an information message.

Since the method DISPLAY_ATTRIBUTES propagates its exception to the mainprogram, the system stops list processing within the DISPLAY_ATTRIBUTESmethod as soon as the first error occurs.

Hint: It would also be possible to propagate the original exception from themethod DISPLAY_ATTRIBUTES. We would not then have had to define twoexception classes explicitly. However, the point of this example is to showhow exceptions can be chained.

406 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 417: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

381 Exercise 21: Class-Based ExceptionsExercise Duration: 45 Minutes

Exercise ObjectivesAfter 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 ExampleYour airplane management program should use the class-based exception concept ifan invalid airplane type occurs. An error text should be displayed in the list, instead ofthe current default values.

System DataSystem: will be assignedClient: will be assignedUser ID: will be assignedPassword: will be assignedSet up instructions: No special settings required if you are using a standardSAP Web AS 6.20 system

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 thesyntax check determines if the relevant exception is handled after it is raised orif it is explicitly propagated.

2. Add an attribute for the airplane type (suggested name: PLANETYPE) andassign the type S_PLANETYPE to it.

3. Create a default error message that can be enhanced dynamically to includethe airplane type.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 407

Page 418: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Task 2:Raise your new exception if an error occurs.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe airplane management program, SAPBC401_EVES_MAIN_B.

2. Raise your exception within method ET_TECHNICAL_ATTRIBUTES of localclass LCL_AIRPLANE.

Ensure that the invalid airplane type is copied into the attribute of the exceptioninstance.

3. Make sure that the raised exception is explicitly propagated.

Task 3:Handle the raised exception.

1. Catch your exception in the DISPLAY_ATTRIBUTES method of local classLCL_AIRPLANE.

Define a local reference variable for this purpose (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.

Define a variable for this purpose (suggested name: EXC_TEXT) with datatype STRING.

408 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 419: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

Solution 21: Class-Based ExceptionsTask 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 thesyntax check determines if the relevant exception is handled after it is raised orif it is explicitly propagated.

a) Follow the processes as outlined in the relevant section of this lesson.

b) Model solution: CX_BC401_INVALID_PLANETYPE

2. Add an attribute for the airplane type (suggested name: PLANETYPE) andassign the type S_PLANETYPE to it.

a) Follow the processes as outlined in the relevant section of this lesson.

3. Create a default error message that can be enhanced dynamically to includethe airplane type.

a) Follow the processes as outlined in the relevant section of this lesson.

Task 2:Raise your new exception if an error occurs.

1. Complete your ZBC401_##_MAIN program or copy the model solution fromthe airplane management program, SAPBC401_EVES_MAIN_B.

a) Additional information is available in the SAP Library.

b) Model solution: SAPBC401_EXCS_RAISE_TRY

2. Raise your exception within method ET_TECHNICAL_ATTRIBUTES of localclass LCL_AIRPLANE.

Ensure that the invalid airplane type is copied into the attribute of the exceptioninstance.

a) Refer to

the source code extract from the model solution.

3. Make sure that the raised exception is explicitly propagated.

a) See the source code extract from the model solution.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 409

Page 420: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Task 3:Handle the raised exception.

1. Catch your exception in the DISPLAY_ATTRIBUTES method of local classLCL_AIRPLANE.

Define a local reference variable for this purpose (suggested name:R_EXCEPTION) and assign it to the CX_ROOT class.

a) See the source code extract from the model solution.

2. Read the error text in the exception instance and display it in the ABAP list.

Define a variable for this purpose (suggested name: EXC_TEXT) with datatype STRING.

a) See the source code extract from the model solution.

ResultSource code:

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

im_planetype TYPE saplane-planetype,

Continued on next page

410 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 421: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

display_attributes.

CLASS-METHODS: display_n_o_airplanes.

EVENTS: airplane_created.

PRIVATE SECTION.

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

METHODS: get_technical_attributes

IMPORTING im_type TYPE saplane-planetype

EXPORTING ex_weight TYPE s_plan_wei

ex_tankcap TYPE s_capacity

RAISING cx_bc401_invalid_planetype.

DATA: name TYPE string,

planetype TYPE saplane-planetype.

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.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 411

Page 422: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

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

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

Continued on next page

412 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 423: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

im_planetype TYPE saplane-planetype

im_cargo TYPE scplane-cargomax.

METHODS: display_attributes REDEFINITION.

PRIVATE SECTION.

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

DATA: max_cargo TYPE scplane-cargomax.

ENDCLASS. "lcl_cargo_plane DEFINITION

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

* CLASS lcl_cargo_plane IMPLEMENTATION

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

*

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

CLASS lcl_cargo_plane IMPLEMENTATION.

METHOD constructor.

CALL METHOD super->constructor

EXPORTING

im_name = im_name

im_planetype = im_planetype.

max_cargo = im_cargo.

ENDMETHOD. "constructor

METHOD display_attributes.

super->display_attributes( ).

WRITE: / ’Max Cargo = ’, max_cargo.

ULINE.

ENDMETHOD. "display_attributes

ENDCLASS. "lcl_cargo_plane IMPLEMENTATION

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

* CLASS lcl_passenger_plane DEFINITION

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

*

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

CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..

PUBLIC SECTION.

METHODS: constructor IMPORTING im_name TYPE string

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 413

Page 424: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

im_planetype TYPE saplane-planetype

im_seats TYPE sflight-seatsmax.

METHODS: display_attributes REDEFINITION.

PRIVATE SECTION.

DATA: max_seats TYPE sflight-seatsmax.

ENDCLASS. "lcl_passenger_plane DEFINITION

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

* CLASS lcl_passenger_plane IMPLEMENTATION

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

*

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

CLASS lcl_passenger_plane IMPLEMENTATION.

METHOD constructor.

CALL METHOD super->constructor

EXPORTING

im_name = im_name

im_planetype = im_planetype.

max_seats = im_seats.

ENDMETHOD. "constructor

METHOD display_attributes.

super->display_attributes( ).

WRITE: / ’Max Seats = ’, max_seats.

ULINE.

ENDMETHOD. "display_attributes

ENDCLASS. "lcl_passenger_plane IMPLEMENTATION

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

* CLASS lcl_carrier DEFINITION

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

*

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

CLASS lcl_carrier DEFINITION.

PUBLIC SECTION.

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

INTERFACES lif_partners.

METHODS: constructor IMPORTING im_name TYPE string,

get_name RETURNING value(ex_name) TYPE string,

Continued on next page

414 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 425: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

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

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 415

Page 426: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

METHOD get_name.

ex_name = name.

ENDMETHOD. "get_name

ENDCLASS. "lcl_carrier IMPLEMENTATION

416 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 427: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

391 Exercise 22: (Optional): MappingExceptions to Each OtherExercise Duration: 45 Minutes

Exercise ObjectivesAfter 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 ExampleIf your airplane management program encounters an exception and displays an error onthe list, another exception should be raised. The second exception should refer to thefirst exception so that both instances can be evaluated when the exception is handled.

System DataSystem: will be assignedClient: will be assignedUser ID: will be assignedPassword: will be assignedSet up instructions: No special settings required if you are using a standardSAP Web AS 6.20 system

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 model solution fromthe previous exercise, SAPBC401_EXCS_RAISE_TRY.

2. To make your program easier to maintain, create another include program foryour exception class and include it in your main program (suggested name:ZBC401_##_EXCEPTION).

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 417

Page 428: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

3. Define a local exception class in your new include program. The exception isneeded in case exception handling takes place when the list is output (suggestedname: LCX_LIST_ERROR).

Hint: Your local exception class should derive from the superclassCX_STATIC_CHECK.

4. Add a public instance method to your local exception class. This method returnsa special text appropriate to the error that may occur: for example, �The listcontains an error.� (Suggested 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 classLCL_AIRPLANE when the exception for the invalid airplane type is beinghandled.

Transfer the reference to the original exception instance to the exception instancethat is to be created.

2. Extend the signature of the DISPLAY_ATTRIBUTES method so that your newexception is explicitly propagated.

Task 3:Handle your new exception and evaluate the information of both the new and theoriginal exception instance.

1. Catch your new exception in the DISPLAY_AIRPLANES method of localclass LCL_CARRIER. Define a local reference variable for the purpose with asuitable type (suggested name: R_EXC).

2. Use this reference to export the text of your new exception. Define a text variablefor this purpose with an appropriate type (suggested name: EXC_TEXT).

If an exception occurs, display the text of your new exception as well the oldone, 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.

418 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 429: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

Solution 22: (Optional): Mapping Exceptionsto Each OtherTask 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 model solution fromthe previous exercise, SAPBC401_EXCS_RAISE_TRY.

a) Additional information is available in the SAP Library.

b) Model solution: SAPBC401_EXCS_RAISE_TRY_OPT

2. To make your program easier to maintain, create another include program foryour exception class and include it in your main program (suggested name:ZBC401_##_EXCEPTION).

a) Additional information is available in the SAP Library.

3. Define a local exception class in your new include program. The exception isneeded in case exception handling takes place when the list is output (suggestedname: LCX_LIST_ERROR).

Hint: Your local exception class should derive from the superclassCX_STATIC_CHECK.

a) See the source code extract from the model solution.

4. Add a public instance method to your local exception class. This method returnsa special text appropriate to the error that may occur: for example, �The listcontains an error.� (Suggested 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 classLCL_AIRPLANE when the exception for the invalid airplane type is beinghandled.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 419

Page 430: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Transfer the reference to the original exception instance to the exception instancethat is to be created.

a) See the source code extract from the model solution.

2. Extend the signature of the DISPLAY_ATTRIBUTES method so that your newexception 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 theoriginal exception instance.

1. Catch your new exception in the DISPLAY_AIRPLANES method of localclass LCL_CARRIER. Define a local reference variable for the purpose with asuitable type (suggested name: R_EXC).

a) See the source code extract from the model solution.

2. Use this reference to export the text of your new exception. Define a text variablefor this purpose with an appropriate type (suggested name: EXC_TEXT).

If an exception occurs, display the text of your new exception as well the oldone, in the form of an information message.

a) See the source code extract from the model solution.

3. Use the same variables to export the text of the original exception.

Enter this text in form of an information message.

a) See the source code extract from the model solution.

ResultSource code:

SAPBC401_EXCS_RAISE_TRY_OPT

REPORT sapbc401_excs_raise_try_opt.

TYPES: ty_fuel TYPE p DECIMALS 2,

ty_cargo TYPE p DECIMALS 2.

TYPE-POOLS icon.

Continued on next page

420 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 431: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

INCLUDE bc401_excs_raise_try_opt_exc.

INCLUDE bc401_excs_raise_try_opt_cl1.

INCLUDE bc401_excs_raise_try_opt_cl2.

DATA: r_vehicle TYPE REF TO lcl_vehicle,

r_truck TYPE REF TO lcl_truck,

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.

ENDCLASS. "lcx_list_error DEFINITION

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

* CLASS lcx_list_error IMPLEMENTATION

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 421

Page 432: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

*

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

CLASS lcx_list_error IMPLEMENTATION.

METHOD get_exc_text.

result = ’The list contains an error.’(err).

ENDMETHOD. "get_text

ENDCLASS. "lcx_list_error IMPLEMENTATION

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

EXPORTING ex_weight TYPE s_plan_wei

Continued on next page

422 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 433: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

ex_tankcap TYPE s_capacity

RAISING cx_bc401_invalid_planetype.

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.

...

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.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 423

Page 434: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

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

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.

Continued on next page

424 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 435: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

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.

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.

...

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 425

Page 436: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

ENDMETHOD. "constructor

METHOD get_name.

...

ENDMETHOD. "get_name

ENDCLASS. "lcl_carrier IMPLEMENTATION

426 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 437: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Exception Handling in ABAP Objects

Lesson Summary

You should now be able to:� Create exception classes� Raise 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 to each other in ABAP Objects programs

Related InformationFor more information, refer to the SAP Library and the key word documentationfor the individual statements.

2005/Q4 © 2005 SAP AG. All rights reserved. 427

Page 438: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Lesson:402

RTTS (Run Time Type Service)Lesson Duration: 120 Minutes

Lesson OverviewAs of SAP Web AS 6.10, ABAP Objects enables you to query type attributes atruntime using standard SAP classes. This concept (Run Time Type Identification[RTTI]) has now been enhanced for SAP Web AS 6.40 to enable you to create RunTime Type Creation [RTTC] types dynamically at runtime. The combination of bothconcepts forms the (Run Time Type Services [RTTS]).

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Query type attributes at runtime� Create types dynamically

ABAP Objects is a programming language that contains both procedural andobject-oriented features. The procedural parts of ABAP Objects must always be usedin classes, that is, in object-oriented contexts.

However, certain concepts (for example, Run Time Type Identification, BusinessAdd Ins, 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 theobject-oriented and the procedural aspects of ABAP Objects.

You can use this lesson to illustrate these concepts again.

The RTTS concept (RTTI and RTTC) completes the topic by subsequently solving anumber of problems that were initially left open.

Business ExampleAn airline wants to identify all its cargo planes.

428 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 439: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

RTTI/Type Analysis at RuntimeIn ABAP Objects, there is a class-based concept called Run Time Type Information(RTTI) that you can use to determine type attributes at runtime. This concept includesall ABAP types, and thus covers all of the functions of the now obsolete statementsDESCRIBE FIELD and DESCRIBE TABLE.

There is a description class for each type with special attributes for special typeattributes.

Figure 169: Dynamic Type Analysis for RTTI Classes

The class hierarchy of the description classes corresponds to the hierarchy of the typesof ABAP Objects. In addition, the description classes for complex types, references,classes, and interfaces have special methods that are used to specify references tosubtypes. You can use these methods to navigate through a compound type to allits subtypes.

To obtain a reference to a description object of a type, you must use the static methodsof the class CL_ABAP_TYPEDESCR or the navigation methods of the specialdescription 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 thedescription object contain information on the attributes of the type.

2005/Q4 © 2005 SAP AG. All rights reserved. 429

Page 440: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Figure 170: RTTI: Methods and Attributes of the Root Class

Dynamic Data Type Analysis: Application Example

In the following application example, the attributes of a structure are to be identifiedusing RTTI. The subclass CL_ABAP_STRUCTDESCR is used for this purpose.

430 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 441: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

Figure 171: RTTI: Querying Structure Attributes

Since you need the attributes of a structure, you must first define a reference to theappropriate description class. Instances of this class have a COMPONENTS attributethat you use to describe the individual components of the relevant structure. Thisattribute is an internal table. Therefore, you also need to define a work area witha compatible line type.

The functional method call returns the reference to the description instance of thetransferred structure. Note: You would also have been able to create the WA structuredynamically. In this example, it is static as usual.

The abstract class CL_ABAP_TYPEDESCR contains the static methodDESCRIBE_BY_DATA. Its RETURNING parameter is typed as a reference to thissuperclass. However, since the actual parameter R_DESCR is typed on the subclassCL_ABAP_STRUCTDESCR, the object needs to be assigned using a widening cast.

You can then access the attributes of the description instance in any form. In thisexample, the component names are displayed as the column headers (for the sake ofclarity, we have omitted the formatting options).

2005/Q4 © 2005 SAP AG. All rights reserved. 431

Page 442: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

If you have enough time, we recommend that you demonstrate extracts fromSAPBC401_DYND_DATADECL_RTTI and SAPBC401_DYND_RTTI_OBJECT,ideally to develop source code together with the participants.

Dynamic Object Type Analysis: Application Example

In the following example, the attributes of an object are to be analyzed. Demonstratethe reference SENDER of the handler method ADD_VEHICLE for the classLCL_RENTAL as your example.

Figure 172: RTTI: Querying Object-Type Attributes

As an example, you should enhance the existing appli-cation with the travel agency and its business partner.In the previous example, we specified that an instance of theLCL_RENTAL vehicle rental class reacts to an event by including the vehicleinstance that triggered the event in the separate VEHICLE LIST 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 onlyinterested in buses.

432 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 443: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

The reference to the triggering vehicle instance is contained in the SENDER parameterof the aforementioned event handler method. Its dynamic object type is to be analyzedto determine whether the vehicle in question is a bus or a truck.

A functional RTTI method call returns the reference to the description instance ofthe transferred vehicle instance.

The abstract class CL_ABAP_TYPEDESCR has this DESCRIBE_BY_OBJECT_REFmethod. Its returning parameter is typed as a reference to this superclass.However, since the actual parameter R_DESCR is typed on the subclassCL_ABAP_CLASSDESCR, the object needs to be assigned using a widening cast.

You can then access the attributes of the description instance in any way. Thefunctional method GET_RELATIVE_NAME supplies the class name.

Note: You could also fulfill the same purpose without using RTTI classes.For example, you could use a widening cast assignment from SENDER toa reference variable that has a LCL_BUS static type. This would result in aruntime error for vehicle instances that are not buses. The system could thencatch this runtime error. Therefore, a runtime error not being triggered wouldbe the criterion for including a vehicle in the vehicle list.

RTTC/Type Creation at RuntimeIn SAP Web AS 6.40, RTTC was added to the RTTI type classes to facilitate thecreation of types at runtime.

The properties of the types are implemented by type-object attributes. This means thateach type has a type object whose attributes describe the properties of the type.

2005/Q4 © 2005 SAP AG. All rights reserved. 433

Page 444: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Figure 173: RTTC: Dynamic Type Creation

The class hierarchy of the type classes corresponds to the hierarchy of types in theABAP type system. Type objects can be created by the type class methods. Toobtain references to type objects, you can call specific static methods for the classCL_ABAP_TYPEDESCR or methods of the special type classes (GET_I, GET_C,CREATE).

434 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 445: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

Figure 174: RTTC: Type Objects for the Type Description

You can use RTTC to create basic data types. However, you can also use it to createmore complex data types such as structures or internal tables.

2005/Q4 © 2005 SAP AG. All rights reserved. 435

Page 446: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Figure 175: RTTC: Creating a Table Type

With the CREATE method, the class CL_ABAP_TABLEDESCR enables you tocreate an internal table type at runtime. The parameter P_LINE_TYPE is an importantformal parameter of this static method. This parameter describes the line type using areference to the CL_ABAP_STRUCTDESCR. In the example provided here, SPFLIis used as the line type. The method DESCRIBE_BY_NAME instantiates a suitableobject for this (the ABAP_TRUE parameter from the sample program originates froma type pool that is used internally in the RTTC classes).

The question that now arises is what you should technically do with the table typethat has just been created. For instance, you could use it as an example of creating aninternal table at runtime:

...

DATA r_itab TYPE REF TO data,

r_tableType TYPE REF TO cl_abap_tabledescr.

...

* Creation of internal tabletype with static method

* CREATE of RTTS-class cl_abap_tabledescr

...

CREATE DATA r_itab TYPE HANDLE r_tabletype.

436 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 447: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

Using the HANDLE addition, the CREATE DATA statement in the example createsan internal table whose type is described by an RTTS type object. A reference variablefrom the static type of the CL_ABAP_TABLEDESCR class that refers to a type objectis specified for the HANDLE. The type object may have been created on the existingdata objects using the RTTS methods or by dynamically defining a new data type.

Since this topic is complex and some people who are new to the subject matter usuallyfind it overwhelming, also make sure that you refer to the corresponding relevant areasrelating to RTTI and RTTC in the documentation so that the participants know thatthey can always refer to it themselves at a later stage. Ideally, the instructor shouldfirst show how the participants can access the documentation.

Also make sure that you clearly communicate in advance that this topic will not becovered completely in this course. It is only an overview of the subject matter. Informthe participants that the complete topic will be covered in a separate course.

If you have enough time, you can run a demo for the participants and also carry outthe second optional exercise. Dynamically creating data objects at runtime is a newarea for many participants and the second exercise will impress the participants withthe options available with ABAP-OO. If you have a tight schedule, however, werecommend that you theoretically discuss the new RTTS features for 6.40.

2005/Q4 © 2005 SAP AG. All rights reserved. 437

Page 448: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

438 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 449: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

411 Exercise 23: RTTI: Querying ObjectAttributesExercise Duration: 30 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Query attributes of objects at runtime using RTTI

Business ExampleIn the program for the travel agency model, the airline (LCL_CARRIER) wants todetermine the highest cargo value of its cargo airplanes.

Task:Determine the highest cargo value for all cargo airplanes entered in your application.The cargo airplanes are entered in the class LCL_CARRIER.

1. You can either use the copy template SAPBC401_CASS_MAIN_C or changeyour previous program. A prerequisite for this is the exercise you completed forthe widening cast for cargo airplanes (method GET_HIGHEST_CARGO).

If you want to use the copy template, call your ZBC401_##_RTTI_1 program.

Model solution: SAPBC401_DYNS_RTTS_1

2. RTTI should now solve the method GET_HIGHEST_CARGO created in one ofthe earlier exercises for calculating the highest cargo value.

Therefore, use RTTI instead of the TRY-ENDTRY procedure.

This specifically means that you now no longer need to catch the runtime errorfor a widening cast because the type of reference variable can be determined inadvance using an appropriate RTTI call.

2005/Q4 © 2005 SAP AG. All rights reserved. 439

Page 450: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Solution 23: RTTI: Querying ObjectAttributesTask:Determine the highest cargo value for all cargo airplanes entered in your application.The cargo airplanes are entered in the class LCL_CARRIER.

1. You can either use the copy template SAPBC401_CASS_MAIN_C or changeyour previous program. A prerequisite for this is the exercise you completed forthe widening cast for cargo airplanes (method GET_HIGHEST_CARGO).

If you want to use the copy template, call your ZBC401_##_RTTI_1 program.

Model solution: SAPBC401_DYNS_RTTS_1

a) Copy the copy template in the usual manner or continue to work withyour old program.

2. RTTI should now solve the method GET_HIGHEST_CARGO created in one ofthe earlier exercises for calculating the highest cargo value.

Therefore, use RTTI instead of the TRY-ENDTRY procedure.

Continued on next page

440 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 451: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

This specifically means that you now no longer need to catch the runtime errorfor a widening cast because the type of reference variable can be determined inadvance using an appropriate RTTI call.

a) See the source code extract from the model solution.

Result

SAPBC401_DYNS_RTTS_1

REPORT sapbc401_dyns_rtts_1.

INCLUDE sapbc401_dyns_c1.*...

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

*& Include SAPBC401_DYNS_C1 *

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

*...

CLASS lcl_carrier IMPLEMENTATION.

METHOD get_highest_cargo . "*** determine the highest cargo value

DATA: r_cargo TYPE REF TO lcl_cargo_plane.

DATA: r_plane TYPE REF TO lcl_airplane.

DATA: cargo TYPE scplane-cargomax.

DATA: r_exc TYPE REF TO cx_root.

DATA: r_descr TYPE REF TO cl_abap_classdescr.

LOOP AT airplane_list INTO r_plane.

r_descr ?=

cl_abap_typedescr=>describe_by_object_ref( r_plane ).

IF r_descr->get_relative_name( ) = ’LCL_CARGO_PLANE’.

r_cargo ?= r_plane.

IF r_cargo->get_cargo( ) > re_cargo.

re_cargo = r_cargo->get_cargo( ).

ENDIF.

ENDIF.

ENDLOOP.

*...

2005/Q4 © 2005 SAP AG. All rights reserved. 441

Page 452: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

442 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 453: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

415 Exercise 24: (Optional): RTTC: CreatingTypes at RuntimeExercise Duration: 30 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Create and use an internal table type at runtime

Business ExampleYou want to add an RTTC call, used for creating a type, to a current program. Theprogram in question also demonstrates dynamic programming, which means that itreacts dynamically to line types entered by the user.

Task:Create types at runtime using RTTC

1. Use one of the copy templates where you must fill in the blanks, such as,SAPBC401_DYNT_RTTS_2a, or where you do not have to fill in the blanks,such as SAPBC401_DYNT_RTTS_2b.

The target program is ZBC401_##_DYNS_RTTS_2.

2. At runtime, use RTTC to create a table type dynamically to display the data of aDB table selected by the user (this is a data browser function).

Define the required reference variables for this and use the corresponding RTTCfunctions to create this table type.

Based on this type, you should then create an internal table dynamically atruntime and display it using an ALV Grid Control. The template to be copiedalready contains the relevant lines for this display.

2005/Q4 © 2005 SAP AG. All rights reserved. 443

Page 454: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

Solution 24: (Optional): RTTC: CreatingTypes at RuntimeTask:Create types at runtime using RTTC

1. Use one of the copy templates where you must fill in the blanks, such as,SAPBC401_DYNT_RTTS_2a, or where you do not have to fill in the blanks,such as SAPBC401_DYNT_RTTS_2b.

The target program is ZBC401_##_DYNS_RTTS_2.

a)

Model solution: SAPBC401_DYNS_RTTS_2

2. At runtime, use RTTC to create a table type dynamically to display the data of aDB table selected by the user (this is a data browser function).

Define the required reference variables for this and use the corresponding RTTCfunctions to create this table type.

Based on this type, you should then create an internal table dynamically atruntime and display it using an ALV Grid Control. The template to be copiedalready contains the relevant lines for this display.

a) See the source code extract from the model solution.

Result

SAPBC401_DYNS_RTTS_2

REPORT sapbc401_dyns_RTTS_2.

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.

DATA: r_linetype TYPE REF TO cl_abap_structdescr,

Continued on next page

444 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 455: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

r_tabletype TYPE REF TO cl_abap_tabledescr,

key TYPE abap_keydescr_tab.

PARAMETERS pa_tab TYPE dd02l-tabname DEFAULT ’SPFLI’.

START-OF-SELECTION.

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

*** create a tabletype with RTTC technique***************

*** call static method CREATE of specific RTTC-class ***

r_linetype ?= cl_abap_typedescr=>describe_by_name( pa_tab ).

r_tabletype = cl_abap_tabledescr=>create(

p_line_type = r_linetype ).

*** new technique with RTTC-type creation **************

*** dynamic creation of internal table data object ****

CREATE DATA ref_itab TYPE HANDLE r_tabletype.

* old technique without type creation ******************

* 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

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

* initialize command input field for screen

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

MODULE clear_ok_code OUTPUT.

CLEAR ok_code.

ENDMODULE. " clear_ok_code OUTPUT

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 445

Page 456: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

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

*& Module STATUS_0100 OUTPUT

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

* set user interface

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

MODULE status_0100 OUTPUT.

SET PF-STATUS ’ST100’.

SET TITLEBAR ’T100’.

ENDMODULE. " STATUS_0100 OUTPUT

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

*& Module init_controls_0100 OUTPUT

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

* initialize controls

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

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

Continued on next page

446 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 457: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

OTHERS = 5

.

IF sy-subrc <> 0.

MESSAGE a702(bc401).

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

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

* handle interface exit commands

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

MODULE leave_program INPUT.

CLEAR popans.

CALL FUNCTION ’POPUP_TO_CONFIRM_STEP’

EXPORTING

textline1 = text-dml

textline2 = text-rcn

titel = text-cnc

cancel_display = ’ ’

IMPORTING

answer = popans.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 447

Page 458: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

CASE popans.

WHEN ’J’.

LEAVE PROGRAM.

WHEN ’N’.

CLEAR ok_code.

ENDCASE.

ENDMODULE. " leave_programm INPUT

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

*& Module USER_COMMAND_0100 INPUT

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

* handle other interface commands

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

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.

IF popans = ’J’.

LEAVE TO SCREEN 0.

ENDIF.

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

Continued on next page

448 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 459: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

LEAVE PROGRAM.

ENDIF.

WHEN OTHERS.

ENDCASE.

ENDMODULE. " USER_COMMAND_0100 INPUT

CALL SCREEN 100.

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

*& Module clear_ok_code OUTPUT

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

* text

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

MODULE clear_ok_code OUTPUT.

CLEAR ok_code.

ENDMODULE. " clear_ok_code OUTPUT

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

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 449

Page 460: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

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

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.

Continued on next page

450 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 461: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

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.

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 451

Page 462: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 5: Exception Handling and RTTS TAW10_3

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

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.

452 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 463: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: RTTS (Run Time Type Service)

Lesson Summary

You should now be able to:� Query type attributes at runtime� Create types dynamically

2005/Q4 © 2005 SAP AG. All rights reserved. 453

Page 464: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit Summary TAW10_3

Unit SummaryYou should now be able to:� Create exception classes� Raise 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 to each other in ABAP Objects programs� Query type attributes at runtime� Create types dynamically

454 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 465: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Test Your Knowledge

427Test Your Knowledge

1. The new exception concept replaces the old one. Thus, all old source codesections must be rewritten. As of SAP Web AS 6.20, function modules from theSAP standard system automatically raise object-oriented exceptions.Determine whether this statement is true or false.□ True□ False

2. Unlike the old exceptions, those embodying the new concept can also be raisedfrom subroutines and propagated.Determine whether this statement is true or false.□ True□ False

3. The new exception classes can only be defined globally. This ensures centralmaintenance and reuse.Determine whether this statement is true or false.□ True□ False

4. When you define an exception class, the superclass you choose specifies whetheror not its exceptions must be caught explicitly with a TRY-CATCH-ENDTRYblock and, if so, how the system reacts if the exception is not caught.Determine whether this statement is true or false.□ True□ False

2005/Q4 © 2005 SAP AG. All rights reserved. 455

Page 466: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Test Your Knowledge TAW10_3

428Answers

1. The new exception concept replaces the old one. Thus, all old source codesections must be rewritten. As of SAP Web AS 6.20, function modules from theSAP standard system automatically raise object-oriented exceptions.

Answer: False

2. Unlike the old exceptions, those embodying the new concept can also be raisedfrom subroutines and propagated.

Answer: True

3. The new exception classes can only be defined globally. This ensures centralmaintenance and reuse.

Answer: False

4. When you define an exception class, the superclass you choose specifies whetheror not its exceptions must be caught explicitly with a TRY-CATCH-ENDTRYblock and, if so, how the system reacts if the exception is not caught.

Answer: True

456 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 467: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6429 Shared Objects

For more information, see the introductory instructor notes in the lesson.

Unit OverviewThis unit focuses on a data-storage mechanism that enables you to store data on anapplication server that can be accessed by all users, hence the term Shared Objects.

Unit ObjectivesAfter completing this unit, you will be able to:

� Explain how classes are created for shared objects� Explain how you can use shared objects to implement applications� Access shared objects from within an ABAP program

Unit ContentsLesson: Shared Objects .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .458

Exercise 25: Using Shared Objects.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .481

2005/Q4 © 2005 SAP AG. All rights reserved. 457

Page 468: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Lesson:430

Shared ObjectsLesson Duration: 60 Minutes

Lesson OverviewStarting in SAP Web AS 6.40, you can save data as shared objects in shared memory.In this lesson, we will examine this concept and its implementation.

The advantage of this technique is that data can be saved as objects. Programs canaccess this data quickly, independently of the user session. This technique wasdeveloped with the primary objective of saving catalog information and shoppingcarts. An attribute of catalogs is that they are read often, but only changed rarely. Inthe case of the shopping cart, the data is written by one application and then read byanother program at a different time (in a different user session). Here as well, thistechnique delivers considerably better performance than saving the data persistently inthe database.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Explain how classes are created for shared objects� Explain how you can use shared objects to implement applications� Access shared objects from within an ABAP program

Shared objects are new in Release 6.40. Therefore, they will probably not be relevantfor all the course participants. Ask about their expectations before you start this lesson.If time is short, you can abbreviate the lesson presentation and/or omit the exercise.

Business ExampleMr. Jones is a software developer at a major corporation that develops proprietarybusiness applications in ABAP. He is asked to develop a flexible new application forflight bookings. One requirement of the application is that many employees must beable to access the same customer data simultaneously, without having to read this datafrom the database each time. Mr. Jones knows that shared objects can be used to makedata in main memory accessible across session boundaries. He therefore uses sharedobjects to develop his flight booking application.

458 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 469: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

Introducing Shared ObjectsStarting in SAP Web AS 6.40, you can save data as shared objects in shared memory,across different programs and even different user sessions. Accordingly, you cancreate applications in which users write data to this area. Other users can then readthis data later.

We can imagine many different potential uses for shared objects:

� Saving a catalog

An �author� writes the catalog to the shared objects area � many users can thenaccess this catalog at the same time.

� Saving a shopping cart

The buyer fills the shopping cart and the seller reads it later.

Shared MemoryShared memory is a memory area on an application server that can be accessed by allthe ABAP programs running on that server.

Figure 176: Memory Model of an Application Server

Before shared objects were introduced, ABAP statements had to use the EXPORT andIMPORT statements with the SHARED BUFFER and SHARED MEMORY additions toaccess this memory area. Instances of classes "lived" exclusively in the internal session

2005/Q4 © 2005 SAP AG. All rights reserved. 459

Page 470: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

of an ABAP program. With the introduction of shared objects in SAP Web AS 6.40,shared memory has been enhanced with Shared Objects Memory, where the sharedobjects can be saved. Shared objects are saved in so-called areas of shared memory.

Note: At the present time, instances of classes can be saved. It is not (yet)possible to save any data objects as shared objects. However, data objects(aside from reference variables) can be saved as attributes of classes.

Figure 177: Accessing Shared Objects

Properties of Shared Objects

� Cross-program buffering of data that is read often, but rarely written

(Recommendation: Once per day to once per hour)

� Concurrent read accesses are supported� Access is controlled by a lock mechanism� Data is saved as attributes of objects� Memory bottlenecks result in runtime errors and have to be caught

460 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 471: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

The write accesses should be seldom because writing data to the shared objects area isperformance-intensive. Specifically, you want to optimize runtime, which would belost if write access were more frequent.

Note: SAP also uses shared objects in SAP Web AS 6.40. For example, thistechnique is used to navigate in the ABAP Workbench. In addition to savingmemory (around 3 MB per user logon), navigation during the first access isfaster by up to a factor of 100.

A prerequisite for saving an object in shared memory is that the class of that object isdefined with the SHARED MEMORY ENABLED addition of the CLASS statement,or that the Shared Memory Enabled attribute is selected in the Class Builder.

Areas and Area Instances

Figure 178: Areas and Area Instances

An area is the template for area instances in shared memory. One area can spawnseveral area instances, which differ by name. In addition, an area instance can haveseveral versions (�area instance versions�), which differ in their version IDs. In thesimplest case, without version management, an area instance consists of a singlearea instance version.

2005/Q4 © 2005 SAP AG. All rights reserved. 461

Page 472: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Area Classes and Area Handles

Figure 179: Creating an Area

You define an area in transaction SHMA. This creates a global, final area class of thesame name. This is a subclass of CL_SHM_AREA. In an ABAP program, the area isaccessed exclusively using methods of the generated area class.

Hint: Because the area and area class have the same name, it makes sense toname the area according to the naming conventions for classes � ZCL_*, forexample, in the customer namespace.

You can use static methods (�Attach� methods) of an area class to attach an ABAPprogram (or its internal session, where the ABAP program is processed) to an areainstance in shared memory. When you attach an ABAP program, an instance of thearea class is created as an area handle.

The above diagram also shows another class, which is called the area root class. Youcan create any number of objects in an area instance, depending on your specificprogram. You access these objects uniformly through the instance of the area rootclass.

Note: We will limit ourselves to two classes in a specific example.

462 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 473: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

Developing an Example Application

Figure 180: Example Application

In this lesson, we will develop a simple catalog application as an example. We wantto use shared objects to create a catalog of flight dates, where the users can selectany flight quickly.

2005/Q4 © 2005 SAP AG. All rights reserved. 463

Page 474: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Figure 181: Accessing Areas

The diagram again illustrates the fact that any programs can access objects in theshared objects memory. In this case, two applications, which run in different usersessions, access objects in the same area. Therefore, we will need several things forthe example application:

� Creating an area� Developing a program to create an area instance� Developing a program to read data from the area

Creating an AreaShared objects are saved in areas of shared memory. You use transaction SHMA tocreate and manage areas and their attributes.

464 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 475: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

Figure 182: Area Management

Hint: Please note that you have to call transaction code SHMA directly inSAP Web AS 6.40, because it has not been added to the menu tree yet.

Call transaction code SHMA and enter the name of the area. The usual namespacerules apply, which means the area name has to start with Y or Z in the customersystem. Namespaces containing slashes are also supported.

Hint: Note that a global, final area class with the same name as the area isalso created as a subclass of CL_SHM_AREA. Therefore, it makes sense tochoose the area name wisely, as shown in our example.

In an ABAP program, the area will be accessed later exclusively using methods ofthe generated area class.

2005/Q4 © 2005 SAP AG. All rights reserved. 465

Page 476: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Figure 183: Maintaining Areas

After you press the Create, Change, or Display button, the maintenancescreen for areas appears.

Each area is linked with a global area root class, whose attributes can containproprietary data and references to other shared memory-enabled classes. You have toassign the area root class to an area when you maintain it. If an area instance version isnot empty, it has to contain at least an instance of the area root class as its root object,which is used to reference other objects. When you generate the area class, a ROOTattribute is generated and typed with the static type of the area root class.

Other Important Terms for Creating an AreaClient-dependent area

Areas, and thus the objects within an area, do not have a client ID by default.You can specify an area as client-dependent, however. In client-dependent areas,the methods of the area class for accessing an area instance refer to the activeclient by default. You can use the optional importing parameter CLIENT toaccess another client explicitly.

466 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 477: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

Transactional areaAn area instance version of a transactional area is not active immediately afteryou remove a change lock with the DETACH_COMMIT method; it is not activeuntil the next database commit.This is particularly helpful in implementing shopping carts in the shared objectsmemory.

Setting Up an Area InstanceIn the last section, we defined an area. We also created the classes that will beinstantiated in this area. In this section, we will examine the statements that we canuse to create an area instance. We will continue to use the example introduced above.

Figure 184: Before Creating an Area Instance

When you create an area, a global final class with the same name is also created. Toset up an area or access an existing area, you need a reference variable that is typedwith the generated area class. This reference serves as a handle for accessing the area.

2005/Q4 © 2005 SAP AG. All rights reserved. 467

Page 478: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Figure 185: Creating an Area Instance

When you instantiate the area class, an instance of the area is created in sharedmemory. The program has a handle for this instance of the area; all future operationsare performed using this handle.

468 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 479: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

Figure 186: Generating Objects in Shared Memory

Once the area instance has been created, the objects can be created in the shared objectsmemory. To do so, use the AREA HANDLE addition for the CREATE OBJECTstatement. This tells the system the area instance where the objects shall be created.

2005/Q4 © 2005 SAP AG. All rights reserved. 469

Page 480: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Figure 187: Generating Objects in Shared Memory II

In the above diagram, both objects are instantiated from within the program.Alternatively, you can instantiate the root object from within the program. The otherobjects in this area instance can then be created from the constructor of the root object.

You do not have to assign the references in this case.

470 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 481: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

Figure 188: Setting the Root Object

To be able to address the objects created in the area instance, you have to assignthe root object to the ROOT attribute of the area handle. To do so, you use theSET_ROOT method of the area handle.

As a consequence, any program of any application can access this area. To do so,the application merely has to fetch a reference to the area instance, and can thenimmediately access the objects contained in that area instance.

2005/Q4 © 2005 SAP AG. All rights reserved. 471

Page 482: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Figure 189: Releasing the Write Lock

Read access of an area instance is not possible until the write lock has been released.To do so, use the DETACH_COMMIT method, which inherits the area class fromclass CL_SHM_AREA.

Accessing an Area InstanceOnce an area instance has been set up, any other users and applications can access it.The reading programs have to implement the following steps:

472 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 483: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

Figure 190: Accessing an Existing Object in Shared Memory

The reading programs first needs a reference variable that is typed with the area class.This reference variable serves as a handle for the area instance that is being accessed.

The program also has to obtain the handle for the area instance. This is performedusing method ATTACH_FOR_READ, which class CL_SHM_AREA provides. Thissets a read lock that prevents the area instance from being erased during the access.

The objects in this area instance can now be accessed, always using the area handle.

2005/Q4 © 2005 SAP AG. All rights reserved. 473

Page 484: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Figure 191: Cancelling the Read Lock

Once the read activity is complete, the application releases the read lock. MethodDETACH of the area handle is available for this purpose. The read lock is also releasedautomatically when the internal session is closed.

States of Area Instance VersionsWhen you create an area, you can specify that several versions of an area instance areallowed. What exactly do these area instance versions mean? To answer this question,we will examine an example in the next section.

474 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 485: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

Active Version

Figure 192: Setting a Read Lock on the Active Version

This is the normal state: An area instance has been set up. Once the setup is complete(using method DETACH_COMMIT) and the system sends a database commit, thearea instance version is active.

2005/Q4 © 2005 SAP AG. All rights reserved. 475

Page 486: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Version Being Set Up

Figure 193: Version Being Set Up

If the Number of Versions attribute of the area is set appropriately, additional versionsof the area instance can exist in addition to the active version.

When a new catalog is being set up, several temporary versions of the same areainstance exist concurrently. As soon as an application sets a change lock for an areainstance, a �version being set up� is created and exists in parallel to the active version.

476 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 487: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

Outdated Version

Figure 194: Write Complete � Previous Version Is Outdated

If the setup of the new version is completed during a read access of the currentlyactive version, the version being set up becomes active. The previously active versionis given the attribute Outdated.

2005/Q4 © 2005 SAP AG. All rights reserved. 477

Page 488: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Figure 195: New Read Locks for the New Active Version

The read locks for the outdated version remain until the read operations are complete.In contrast, new read locks for the area instance are always set for the active version.Therefore, two different readers may get two different read results in this case.

478 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 489: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

Expired Version

Figure 196: No More Read Locks for Outdated Version: Version Expired

When the last existing read block for an outdated version is removed, the versionexpires. It is then deleted by the garbage collector. You cannot set any locks forexpired versions, nor are they used to determine the number of versions (the latter isimportant if the number of area instance versions has been restricted).

2005/Q4 © 2005 SAP AG. All rights reserved. 479

Page 490: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Figure 197: New Read Locks for Active Version

New read locks are always set for the active version. There can only be one activeversion for each area instance. Depending on the maximum number of versions,several outdated versions for which read blocks are still set may exist in parallel.

480 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 491: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

453 Exercise 25: Using Shared ObjectsExercise Duration: 50 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Create a shared objects area� Write data to a shared objects area� Read data from a shared objects area

Business ExampleYou want to run an Internet shop based on an SAP system. To give your Internetcustomers the fastest possible access to your catalog, you save it in the shared objectsmemory.

You will need a �write program� to manage and describe the catalog and develop atest application to read the data..

System DataSystem: Will be assignedClient: Will be assignedUser ID: Will be assignedPassword: Will be assignedSet up instructions: No special settings required in the standard training system

Task 1:Create a catalog with flight information in the shared objects memory. To do so,you need an area in the shared objects memory; you want to manage the catalogin a separate class.

1. Create an area named ZCL_BC402_##_AREA using transaction SHMA. Thisarea should have the following attributes:

Client-specific AreaWith VersioningDisplacement not Possible

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 481

Page 492: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

The system automatically prompts you to specify a root class. Create an arearoot class with name ZCL_BC402_##_ROOT.

2. Implement the area root class. It should merely contain a reference to the catalogclass that you will create in the next exercise.

Task 2:You need a global class to save the catalog data. This class requires a method forwriting the catalog data and another method for retrieving the data. It also requires aglobal attribute: an internal table that saves the catalog data.

1. Create a global class with name ZCL_BC402_##_CATALOG. Note that thisclass has to be shared memory-enabled.

2. Create an internal table as a global attribute of the class. The line type of theinternal table should correspond to structure SDYN_CONN.

Suggested name: GT_CATALOG

3. Create a method to fill the catalog.

Suggested name: FILL_CATALOG

This method requires an importing parameter that will be given the internaltable with data.

Implement the method.

4. Create a second method to satisfy the flight date queries.

Suggested name: GET_FLIGHTS

This method requires one importing parameter each for the departure anddestination cities, as well as two additional parameters for the earliest and latestpossible flight dates.

The method also needs an exporting parameter that returns the matching flights.

Implement the method.

Task 3:You need a program to set up the area in the shared objects memory. This programis also supposed to read the catalog data from the database and pass it on to theappropriate class.

1. Create a program with type �Executable Program�.

Name of program: ZBC402_##_WRITE_CATALOGContinued on next page

482 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 493: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

2. You need three reference variables: one each for the area handle, the area rootclass, and the catalog class.

3. Create an area, an instance of the catalog class, and an instance of the area rootclass. Set up the area.

Use the Shared Objects Monitor (transaction code SHMM) to monitor the setupof the area and the set locks.

Read the necessary catalog data from tables SPFLI and SFLIGHT.

4. Don't forget to delete the write lock after the data is written successfully.

Task 4:Implement a reading program to read data from the area you just created. Forsimplicity's sake, output this data in the SAP List Viewer.

Hint: Alternatively, you can also develop a BSP application that requeststhe catalog data.

1. Create a program.

Name of program: ZBC402_##_READ_CATALOG

2. Define a selection screen in which the user can enter the departure anddestination cities. The user should also be able to enter an earliest and latestpossible flight date.

3. Make sure the data is read from the catalog object. Output the data in the SAPList Viewer (simplest call).

2005/Q4 © 2005 SAP AG. All rights reserved. 483

Page 494: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Solution 25: Using Shared ObjectsTask 1:Create a catalog with flight information in the shared objects memory. To do so,you need an area in the shared objects memory; you want to manage the catalogin a separate class.

1. Create an area named ZCL_BC402_##_AREA using transaction SHMA. Thisarea should have the following attributes:

Client-specific AreaWith VersioningDisplacement not Possible

The system automatically prompts you to specify a root class. Create an arearoot class with name ZCL_BC402_##_ROOT.

a) Follow the instructor's demonstration.

2. Implement the area root class. It should merely contain a reference to the catalogclass that you will create in the next exercise.

a) Refer to the model solution for details.

Task 2:You need a global class to save the catalog data. This class requires a method forwriting the catalog data and another method for retrieving the data. It also requires aglobal attribute: an internal table that saves the catalog data.

1. Create a global class with name ZCL_BC402_##_CATALOG. Note that thisclass has to be shared memory-enabled.

a) Create the class in the Class Builder. Refer to the model solution for details.

2. Create an internal table as a global attribute of the class. The line type of theinternal table should correspond to structure SDYN_CONN.

Suggested name: GT_CATALOG

a) Refer to the model solution for details.

3. Create a method to fill the catalog.

Suggested name: FILL_CATALOG

Continued on next page

484 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 495: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

This method requires an importing parameter that will be given the internaltable with data.

Implement the method.

a) Refer to the model solution for details.

4. Create a second method to satisfy the flight date queries.

Suggested name: GET_FLIGHTS

This method requires one importing parameter each for the departure anddestination cities, as well as two additional parameters for the earliest and latestpossible flight dates.

The method also needs an exporting parameter that returns the matching flights.

Implement the method.

a) Refer to the model solution for details.

Task 3:You need a program to set up the area in the shared objects memory. This programis also supposed to read the catalog data from the database and pass it on to theappropriate class.

1. Create a program with type �Executable Program�.

Name of program: ZBC402_##_WRITE_CATALOG

a) Refer to the model solution for details.

2. You need three reference variables: one each for the area handle, the area rootclass, and the catalog class.

a) .

3. Create an area, an instance of the catalog class, and an instance of the area rootclass. Set up the area.

Use the Shared Objects Monitor (transaction code SHMM) to monitor the setupof the area and the set locks.

Read the necessary catalog data from tables SPFLI and SFLIGHT.

a) Refer to the model solution for details.

4. Don't forget to delete the write lock after the data is written successfully.

a) Refer to the model solution for details.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 485

Page 496: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Task 4:Implement a reading program to read data from the area you just created. Forsimplicity's sake, output this data in the SAP List Viewer.

Hint: Alternatively, you can also develop a BSP application that requeststhe catalog data.

1. Create a program.

Name of program: ZBC402_##_READ_CATALOG

a) Refer to the model solution for details.

2. Define a selection screen in which the user can enter the departure anddestination cities. The user should also be able to enter an earliest and latestpossible flight date.

a) Refer to the model solution for details.

3. Make sure the data is read from the catalog object. Output the data in the SAPList Viewer (simplest call).

a) Refer to the model solution for details.

Result

Catalog Class: Public Section

class CL_BC402_SHOBS_CATALOG definition

public

final

create public

shared memory enabled .

*"* public components of class CL_BC402_SHOBS_CATALOG

*"* do not include other source files here!!!

public section.

methods FILL_CATALOG

importing

!IT_CATALOG type BC402_T_SDYNCONN .

methods GET_FLIGHTS

importing

Continued on next page

486 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 497: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

!IV_FROM_CITY type S_FROM_CIT

!IV_TO_CITY type S_TO_CITY

!IV_EARLIEST type S_DATE

!IV_LATEST type S_DATE

exporting

!ET_FLIGHTS type BC402_T_SDYNCONN .

Catalog Class: Method Implementations

METHOD fill_catalog.

gt_catalog = it_catalog.

ENDMETHOD.

METHOD get_flights.

FIELD-SYMBOLS:

<fs> TYPE sdyn_conn.

LOOP AT gt_catalog ASSIGNING <fs>

WHERE cityfrom = iv_from_city AND

cityto = iv_to_city AND

fldate > iv_earliest AND

fldate < iv_latest.

APPEND <fs> TO et_flights.

ENDLOOP.

ENDMETHOD.

Program to Write the Data

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

*& Report SAPBC402_SHOS_WRITE_CATALOG

*&

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

*&

*&

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 487

Page 498: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

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

REPORT sapbc402_shos_write_catalog.

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

DATA:

gr_handle TYPE REF TO cl_bc402_shobs_area,

gr_root TYPE REF TO cl_bc402_shobs_root,

gr_catalog TYPE REF TO cl_bc402_shobs_catalog,

gt_flights TYPE bc402_t_sdynconn.

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

START-OF-SELECTION.

*TRY.

gr_handle = cl_bc402_shobs_area=>attach_for_write(

* CLIENT =

* INST_NAME = CL_SHM_AREA=>DEFAULT_INSTANCE

* ATTACH_MODE = CL_SHM_AREA=>ATTACH_MODE_DEFAULT

* WAIT_TIME = 0

).

* CATCH CX_SHM_EXCLUSIVE_LOCK_ACTIVE .

* CATCH CX_SHM_VERSION_LIMIT_EXCEEDED .

* CATCH CX_SHM_CHANGE_LOCK_ACTIVE .

* CATCH CX_SHM_PARAMETER_ERROR .

*ENDTRY.

CREATE OBJECT gr_root AREA HANDLE gr_handle.

CREATE OBJECT gr_catalog AREA HANDLE gr_handle.

gr_root->gr_catalog = gr_catalog.

* TRY.

gr_handle->set_root( root = gr_root ).

* CATCH CX_SHM_INITIAL_REFERENCE .

* CATCH CX_SHM_WRONG_HANDLE .

* ENDTRY.

SELECT *

FROM spfli JOIN sflight

ON spfli~carrid = sflight~carrid AND

Continued on next page

488 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 499: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

spfli~connid = sflight~connid

INTO CORRESPONDING FIELDS OF TABLE gt_flights.

gr_handle->root->gr_catalog->fill_catalog(

it_catalog = gt_flights ).

*TRY.

gr_handle->detach_commit(

).

* CATCH CX_SHM_WRONG_HANDLE .

* CATCH CX_SHM_ALREADY_DETACHED .

* CATCH CX_SHM_COMPLETION_ERROR .

* CATCH CX_SHM_SECONDARY_COMMIT .

*ENDTRY.

Program to Read the Data

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

*& Report SAPBC402_SHOS_READ_CATALOG

*&

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

*&

*&

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

REPORT sapbc402_shos_read_catalog.

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

DATA:

gr_handle TYPE REF TO cl_bc402_shobs_area,

gt_flights TYPE bc402_t_sdynconn,

gs_flights LIKE LINE OF gt_flights,

gv_startdate TYPE sydatum,

gv_enddate TYPE sydatum,

gr_salv TYPE REF TO cl_salv_table.

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

PARAMETERS:

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 489

Page 500: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

pa_from TYPE spfli-cityfrom,

pa_to TYPE spfli-cityto.

SELECT-OPTIONS:

so_date FOR sy-datum NO-EXTENSION.

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

AT SELECTION-SCREEN.

READ TABLE so_date INDEX 1.

IF so_date IS INITIAL.

so_date-low = sy-datum.

so_date-high = sy-datum + 365.

ENDIF.

gv_startdate = sy-datum.

gv_enddate = sy-datum + 365.

IF so_date-low > sy-datum.

gv_startdate = sy-datum.

ENDIF.

IF so_date-high < gv_enddate.

gv_enddate = so_date-high.

ENDIF.

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

START-OF-SELECTION.

TRY.

gr_handle = cl_bc402_shobs_area=>attach_for_read( ).

CATCH cx_shm_inconsistent .

CATCH cx_shm_no_active_version .

CATCH cx_shm_read_lock_active .

CATCH cx_shm_exclusive_lock_active .

CATCH cx_shm_parameter_error .

CATCH cx_shm_change_lock_active .

ENDTRY.

gr_handle->root->gr_catalog->get_flights(

EXPORTING

iv_from_city = pa_from

iv_to_city = pa_to

Continued on next page

490 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 501: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Shared Objects

iv_earliest = gv_startdate

iv_latest = gv_enddate

IMPORTING

et_flights = gt_flights

).

TRY.

gr_handle->detach( ).

CATCH cx_shm_wrong_handle .

CATCH cx_shm_already_detached .

ENDTRY.

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

*TRY.

cl_salv_table=>factory(

EXPORTING

list_display = if_salv_c_bool_sap=>false

* R_CONTAINER =

* CONTAINER_NAME =

IMPORTING

r_salv_table = gr_salv

CHANGING

t_table = gt_flights

).

* CATCH CX_SALV_MSG .

*ENDTRY.

gr_salv->display( ).

Facilitated DiscussionReinforcement

Discussion QuestionsUse the following questions to engage the participants in the discussion. Feel free touse your own additional questions.

Can you think of sensible ways to use shared objects in your system?

Which options exist for using shared objects?

2005/Q4 © 2005 SAP AG. All rights reserved. 491

Page 502: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 6: Shared Objects TAW10_3

Lesson Summary

You should now be able to:� Explain how classes are created for shared objects� Explain how you can use shared objects to implement applications� Access shared objects from within an ABAP program

492 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 503: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Unit Summary

Unit SummaryYou should now be able to:� Explain how classes are created for shared objects� Explain how you can use shared objects to implement applications� Access shared objects from within an ABAP program

2005/Q4 © 2005 SAP AG. All rights reserved. 493

Page 504: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit Summary TAW10_3

494 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 505: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7467 Case Study

For more information, see the introductory instructor notes in the lesson.

Unit OverviewThe following case study calls on your previously acquired knowledge and byperforming a comprehensive exercise (cass study), you will further strengthen yourexisting knowledge.

Unit ObjectivesAfter completing this unit, you will be able to:

� Explain the concepts relating to object-oriented programming with ABAPObjects and apply these in a small, simple application

� Explain some of the new ABAP Objects concepts (such as ABAP Unit andshared objects) that are available as of SAP Web AS 6.40

Unit ContentsLesson: Case Study and Preview ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .496

Exercise 26: Create a UML Class Diagram.... . . . . . . . . . . . . . . . . . . . . . . . . . . . . .507Exercise 27: Develop a Solution for a Test Case .. . . . . . . . . . . . . . . . . . . . . . . . . 511

2005/Q4 © 2005 SAP AG. All rights reserved. 495

Page 506: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

Lesson:468

Case Study and PreviewLesson Duration: 30 Hours

Lesson OverviewIn this lesson, you will consolidate and apply the knowledge you have gained in thiscourse. You will do this in the best way possible by applying the ABAP Objectstechniques to the case study presented here.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Explain the concepts relating to object-oriented programming with ABAPObjects and apply these in a small, simple application

� Explain some of the new ABAP Objects concepts (such as ABAP Unit andshared objects) that are available as of SAP Web AS 6.40

If possible, you should allow the participants to spend enough time on the case studyso that they leave the course with a �sense of achievement�. Nothing will motivatethem more than being able to successfully develop the program in the case study.If you do not have enough time to complete the exercise (approximately 3-4 hours),you can set it as homework (this approach was well received in the First Teach of thecourse). If you do this, explain to the participants that they can check their workagainst the model solution provided in the folder.

Hint: To explain what is involved, demonstrate the solution once and explainthe exact function of each button.

Give a very brief overview of the 6.40 features of ABAP Unit and SharedObjects and refer the participants to the relevant specialized course.The participants need to absorb all of the new knowledge they have gained duringthe first week of the course and you do not want to overwhelm them with more newinformation.

Business ExampleA customer wants to book a flight through a travel agency, but the flight is alreadybooked. However, the customer is given the option of registering for the flight andbeing put on the waiting list.

496 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 507: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

Case StudyThe ABAP Objects program to be created here should provide the user (for example,the travel agent) with a screen containing functions for managing customers usingflight waiting lists. It should be possible to maintain a waiting list for each flight (rowfrom table SFLIGHT with the keys CARRID, CONNID, FLDATE).

Note: The model shown here is one possible solution to the waiting listrequirements described. You are also free to use your own UML classdiagram, which will produce a different solution.

Figure 198: Case Study: Requirements I

All waiting lists are to be stored in a waiting list buffer called WAIT_LIST(which is technically an internal table). In addition to the flight data, the waitinglists are to contain a list of all customers who have registered for this flight.The functions of this application are shown in the following figure.

2005/Q4 © 2005 SAP AG. All rights reserved. 497

Page 508: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

Figure 199: Case Study: Requirements II

The screen and functions shown here are to be created in accordance with therequirement specifications. The screen layout and flow logic are already available:you have to implement the actual flow, that is, the �intelligence� of the programusing object-oriented techniques.

The individual buttons are to have the following functions:

DisplayDisplays the waiting list for the specified flight (CARRID, CONNID, FLDATE)

CreateCreates the waiting list for the specified flight (CARRID, CONNID, FLDATE)

DeleteDeletes the waiting list for the specified flight (CARRID, CONNID, FLDATE)

AddAdds the customer selected on the right of the screen to the flight waiting listselected on the left

Delete (customer)Deletes the customer selected on the right of the screen from the flight displayedon the left

498 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 509: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

PositionDisplays the selected customer�s position on the waiting list

Customer Type (optional)Shows whether the selected customer is a private customer or a businesscustomer (you will find the relevant information in the CUSTTYPE field oftable SCUSTOM).

Display Customers Moved Up (optional)Displays all customers from the list who were successfully moved up from thewaiting list to get a seat on the flight

Status Log (optional)Displays the number of customers from the list whowere successful in getting a seat on a flight.

2005/Q4 © 2005 SAP AG. All rights reserved. 499

Page 510: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

SAP Web AS 6.40 is a prerequisite for the following topics. You must mention thisfact at this point.

You can use program SAPBC401_PRJD_SHAREDOBJECT as a demo of sharedobjects.

Preview of New Topics: Shared ObjectsAs of SAP Web AS 6.40, you can buffer data across project using shared objects.

Uses of Shared Objects

� Storing a shopping basket

The shopper fills the basket, which is then read by the salesperson later.

� Storing a catalog

Many users access the data at the same time.

Before the introduction of shared objects, ABAP programs could only access thismemory area using the EXPORT and IMPORT statements with the additionsSHARED BUFFER or SHARED MEMORY and instances of classes existed onlyin the internal mode of an ABAP program. With the introduction of shared objects,the shared memory is extended to include the shared objects memory, in whichshared objects can be stored.

Note: The storage of class instances is currently supported. It is not yetpossible to store any data object directly as a shared object; however, dataobjects other than reference variables can be stored as attributes of classes.

500 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 511: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

Figure 200: Shared Objects: Basics

Prerequisites for Shared Objects

� Cross-program buffering of data with a small num-ber of write accesses but a large number of read accesses(recommendation: Between once a day and once each hour).

� Simultaneous read accesses are supported.� Access is regulated by a lock mechanism.� Data objects that are referenced using data references cannot be stored directly.� Memory bottlenecks result in runtime errors and have to be caught.

Shared objects are stored in areas of the shared memory. You create and manageareas and their attributes in transaction SHMA. A prerequisite for storing an object inthe shared memory is that the class of the object must be defined with the additionSHARED MEMORY ENABLED of the CLASS statement, or the shared memoryenabled�� attribute must be selected in the Class Builder.

2005/Q4 © 2005 SAP AG. All rights reserved. 501

Page 512: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

Figure 201: Shared Objects: Areas and Handles

Each area is linked with a global area root class whose attributes may contain its owndata and references to other shared-memory-enabled classes. An area is a template forarea instances in the shared memory. Several area instances with different names canbe created for one area.

When you define an area with transaction SHMA, a global and final area class withthe same name is created for the area as a subclass of CL_SHM_AREA.

In an ABAP program, an area is accessed exclusively using the methods of thegenerated area class. There are static methods for attaching an ABAP program (or itsinternal mode) to area instances in the shared memory (Attach methods).

502 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 513: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

Figure 202: Shared Objects: Example I

With attachment, an instance of the area class is generated as an area handle and alock is set at the same time. The ABAP program can use the area handle to accessthe attached area instance versions and thus also the shared objects stored there.The area handle also contains the methods for releasing the attachment or the lock(Detach methods).

2005/Q4 © 2005 SAP AG. All rights reserved. 503

Page 514: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

Figure 203: Shared Objects: Example II

Note: For more details and information, refer to the SAP Library or attend therelevant ABAP course for advanced developers.

Preview of New Topics: ABAP UnitAs of SAP Web AS 6.40, you can create test classes with the ABAP Unit tool.

ABAP Unit is a test tool integrated into the ABAP runtime environment. It is used tocheck the functionality of the code units of a program (module tests). Individual testsare implemented in various ABAP programs as test methods of local test classes. Thetests of several ABAP programs can be grouped together in test items.

504 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 515: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

Figure 204: Overview of ABAP Unit

� The tests are programmed in ABAP Objects.� The test function is contained in the test methods of test classes.� These test classes are contained locally in the program that is to be tested. This

means that there are no transport or versioning problems.� If an error occurs, the rest of the test procedure can be controlled.� The test code has no effect on production operation.� ABAP Unit does not affect performance in the production system.

Note: For more details and information, refer to the SAP Library or attend therelevant ABAP course for advanced developers.

2005/Q4 © 2005 SAP AG. All rights reserved. 505

Page 516: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

506 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 517: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

477 Exercise 26: Create a UML Class DiagramExercise Duration: 20 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Create one possible UML class diagram to meet a technical specification

Business ExampleA travel agency wants to offer its customers an additional service. If customerswant to book a flight that is already fully booked, they can have their names put ona waiting list for this flight. If a seat becomes free at a later date, a customer fromthe waiting list can be placed on the flight. This customer's name is then removedfrom the waiting list.

Task: Create a UML Class DiagramYou can use the following suggestions but you can also choose a model of your own,which you can then use for an alternate implementation later. If you do not wish to dothis, follow the instructions below to create a class diagram.

1. The waiting list should be the central class in the model. Use LCL_WAITLISTas the class name (ZCL_##_WAITLIST if you are using the Class Builder).

The class should have the public attributes CARRID, CONNID, FLDATE andthe private attribute CUSTOMER_LIST.

The following public methods should be defined in the UML:

CONSTRUCTOR, ADD, DELETE, GET_POS, GET_FIRST andGET_WAIT_LIST.

Hint: It would actually be more in line with the encapsulation concept todefine all of the attributes here as private and then access these attributesof the waiting list with external methods. We suggest that you define theattributes as public here to save time and effort, but this is your choice!

2. Customers form another class. Use LCL_CUSTOMER as the class name(ZCL_##_CUSTOMER if you are using the Class Builder).

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 507

Page 518: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

This class should have the public attribute ID and the private attributes NAME,STREET, CITY and APP_DATE.

The following public methods should be defined in the UML: CONSTRUCTORand GET_ATTRIBUTES

3. As a straightforward solution, you could simply define the buffer for thewaiting lists in the main program as a normal internal table. However, youwant to use one class in this case and therefore the singleton concept is used.Define the buffer for the waiting lists as singleton class LCL_BUFFER(ZCL_##_BUFFER if you are using the Class Builder).

The class should have the attribute BUFFER_LIST: the private, static attributeN_O_ENTRIES and a private, static reference to itself.

The following public methods should be defined in the UML:

CLASS_CONSTRUCTOR (as a static method) and DISPLAY_N_O_ENTRIES

Hint: It would actually be more in line with the encapsulation conceptto define the BUFFER_LIST attribute as private in this case and thenaccess this attribute with methods from the main program. In this case,we suggest that you define this attribute as public and then access itexternally and directly to save time and effort, but this is your choice!

If you follow the model solution for the class diagram, you must usemethods.

4. Define the relationships between these classes and assign the cardinalities(multiplicity).

You also have the option of mapping the navigation options.

508 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 519: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

Solution 26: Create a UML Class DiagramTask: Create a UML Class DiagramYou can use the following suggestions but you can also choose a model of your own,which you can then use for an alternate implementation later. If you do not wish to dothis, follow the instructions below to create a class diagram.

1. The waiting list should be the central class in the model. Use LCL_WAITLISTas the class name (ZCL_##_WAITLIST if you are using the Class Builder).

The class should have the public attributes CARRID, CONNID, FLDATE andthe private attribute CUSTOMER_LIST.

The following public methods should be defined in the UML:

CONSTRUCTOR, ADD, DELETE, GET_POS, GET_FIRST andGET_WAIT_LIST.

Hint: It would actually be more in line with the encapsulation concept todefine all of the attributes here as private and then access these attributesof the waiting list with external methods. We suggest that you define theattributes as public here to save time and effort, but this is your choice!

a) Refer to the model solution.

2. Customers form another class. Use LCL_CUSTOMER as the class name(ZCL_##_CUSTOMER if you are using the Class Builder).

This class should have the public attribute ID and the private attributes NAME,STREET, CITY and APP_DATE.

The following public methods should be defined in the UML: CONSTRUCTORand GET_ATTRIBUTES

a) Refer to the model solution.

3. As a straightforward solution, you could simply define the buffer for thewaiting lists in the main program as a normal internal table. However, youwant to use one class in this case and therefore the singleton concept is used.Define the buffer for the waiting lists as singleton class LCL_BUFFER(ZCL_##_BUFFER if you are using the Class Builder).

The class should have the attribute BUFFER_LIST: the private, static attributeN_O_ENTRIES and a private, static reference to itself.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 509

Page 520: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

The following public methods should be defined in the UML:

CLASS_CONSTRUCTOR (as a static method) and DISPLAY_N_O_ENTRIES

Hint: It would actually be more in line with the encapsulation conceptto define the BUFFER_LIST attribute as private in this case and thenaccess this attribute with methods from the main program. In this case,we suggest that you define this attribute as public and then access itexternally and directly to save time and effort, but this is your choice!

If you follow the model solution for the class diagram, you must usemethods.

a) Refer to the model solution.

4. Define the relationships between these classes and assign the cardinalities(multiplicity).

You also have the option of mapping the navigation options.

a) Refer to the model solution.

Figure 205: Waiting List: UML Class Diagram

510 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 521: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

481 Exercise 27: Develop a Solution for a TestCaseExercise Duration: 300 Minutes

Exercise ObjectivesAfter completing this exercise, you will be able to:� Use ABAP Objects to develop a solution for a test case� Apply some of the techniques you have learned in this course

Business ExampleA customer wants to book a flight through a travel agency but the flight is alreadyfully booked. However, the customer is offered the option of registering for thewaiting list for this flight.

Task:Convert the definitions from your class diagram into a program.

If you want to use the suggestions proposed in this unit, follow the instructionsbelow. If you have created your own alternate UML class diagram, you can ignorethese instructions.

1. Use program SAPBC401_PRJT_WAITLIST as a template. Your programshould be called ZBC401_##_PRJS_WAITLIST.

Copy all Include programs from the template and rename them. You shouldalways use the target names specified with your group number (suggested name:ZBC401_##_PRJS_INC_xxx ).

2. The copied template already contains the parameters for the application to becreated. Familiarize yourself with the program structure.

This program contains a screen on which buttons for all of the required functionsare already provided. However, with the exception of the icons in the standardtoolbar, these functions still have to be implemented.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 511

Page 522: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

For the meaning of the individual buttons, refer to the screen shown in the figureand the explanatory text in your course notes.

Note: If you have no experience with dynamic screens or dialogprogramming with ABAP, speak to your course instructor.

Hint: The display of the customer data on the waiting list (functioncode SHOW) is not part of this exercise. Therefore, to save time, youcan use function module BC401_DISPLAY_DATA. Later, when youare implementing this function, you should familiarize yourself withits interface and use it for display. If you have enough time, you canalso use the ALV Grid Control.

Note: To simplify the scenario, avoid persistent storage of the waitinglist. In other words, the data is not to be saved to the database.

Note: The focus of this exercise is on the creation of a viable model forwhich the existing components should be examined. The main point ofthe exercise is not to implement the program in detail.

512 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 523: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

Solution 27: Develop a Solution for a TestCaseTask:Convert the definitions from your class diagram into a program.

If you want to use the suggestions proposed in this unit, follow the instructionsbelow. If you have created your own alternate UML class diagram, you can ignorethese instructions.

1. Use program SAPBC401_PRJT_WAITLIST as a template. Your programshould be called ZBC401_##_PRJS_WAITLIST.

Copy all Include programs from the template and rename them. You shouldalways use the target names specified with your group number (suggested name:ZBC401_##_PRJS_INC_xxx ).

a) Carry out this step in the usual manner.

2. The copied template already contains the parameters for the application to becreated. Familiarize yourself with the program structure.

This program contains a screen on which buttons for all of the required functionsare already provided. However, with the exception of the icons in the standardtoolbar, these functions still have to be implemented.

For the meaning of the individual buttons, refer to the screen shown in the figureand the explanatory text in your course notes.

Note: If you have no experience with dynamic screens or dialogprogramming with ABAP, speak to your course instructor.

Hint: The display of the customer data on the waiting list (functioncode SHOW) is not part of this exercise. Therefore, to save time, youcan use function module BC401_DISPLAY_DATA. Later, when you

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 513

Page 524: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

are implementing this function, you should familiarize yourself withits interface and use it for display. If you have enough time, you canalso use the ALV Grid Control.

Note: To simplify the scenario, avoid persistent storage of the waitinglist. In other words, the data is not to be saved to the database.

Note: The focus of this exercise is on the creation of a viable model forwhich the existing components should be examined. The main point ofthe exercise is not to implement the program in detail.

a) The model solution provided here encapsulates the buffer with the waitinglists in class LCL_BUFFER. The waiting lists in the buffer can be accessedwith public methods.

It is also possible to create the buffer in the main program directlyas a non-encapsulated internal table. Due to time restrictions, this isrecommended, but the decision is up to the you.

Result

REPORT sapbc401_prjs_waitlist_1

REPORT sapbc401_prjs_waitlist_1.

INCLUDE sapbc401_prjs_inc_1.

DATA ok_code LIKE sy-ucomm.

TABLES: sdyn_conn, scustom.

TYPES: ty_wait_list TYPE STANDARD TABLE OF REF TO lcl_waitlist.

DATA: r_buffer TYPE REF TO lcl_buffer,

r_customer TYPE REF TO lcl_customer,

r_waitlist TYPE REF TO lcl_waitlist,

r_exc TYPE REF TO cx_root.

DATA: wa_sflight TYPE sflight.

LOAD-OF-PROGRAM.

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

Continued on next page

514 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 525: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

*** Instantiate the Buffer which is a singleton !

r_buffer = lcl_buffer=>get_buffer_ref( ).

*** some dynpro initializations ***************

sdyn_conn-carrid = ’LH’.

sdyn_conn-connid = ’0400’.

sdyn_conn-fldate = ’20040710’.

scustom-id = ’00003392’.

START-OF-SELECTION.

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

CALL SCREEN 100.

INCLUDE sapbc401_prjs_waitlist_o01.

Include SAPBC401_PRJS_WAITLIST_I01

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

***INCLUDE BC401_CSS1_WAITLIST_I01 .

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

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

*& Module check_and_create_cust INPUT

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

* text

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

MODULE check_and_create_cust INPUT.

SELECT SINGLE name street city FROM scustom

INTO CORRESPONDING FIELDS OF scustom

WHERE id = scustom-id.

IF sy-subrc <> 0.

CLEAR: scustom-name, scustom-city.

MESSAGE e916(BC401) WITH scustom-id.

* Customernumber & does not exist. Please correct !

ENDIF.

ENDMODULE. " check_and_create_cust INPUT

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 515

Page 526: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

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

*& Module user_command_0100 INPUT

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

* text

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

MODULE user_command_0100 INPUT.

DATA: text TYPE string.

DATA: n_o_lines TYPE i.

DATA: save_ok TYPE sy-ucomm.

CLEAR r_waitlist.

save_ok = ok_code.

CLEAR ok_code.

CASE save_ok.

WHEN ’BACK’.

LEAVE TO SCREEN 0.

WHEN ’CREATE’. "##########################################

TRY.

r_buffer->create_wait_list( EXPORTING

im_carrid = sdyn_conn-carrid

im_connid = sdyn_conn-connid

im_fldate = sdyn_conn-fldate ).

MESSAGE s905(BC401)

WITH sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate.

CATCH cx_wait_list INTO r_exc.

text = r_exc->get_text( ).

MESSAGE s901(BC401) WITH sdyn_conn-carrid sdyn_conn-connid.

ENDTRY.

WHEN ’SHOW’. "##########################################

DATA: it_customer_list TYPE STANDARD TABLE OF bc401_typd_cust.

DATA: wa_cust LIKE LINE OF it_customer_list.

DATA: r_customer_list TYPE TABLE OF REF TO lcl_customer.

DATA: r_cust TYPE REF TO lcl_customer.

r_waitlist = r_buffer->get_wait_list(

im_carrid = sdyn_conn-carrid

im_connid = sdyn_conn-connid

im_fldate = sdyn_conn-fldate ).

IF r_waitlist IS BOUND.

Continued on next page

516 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 527: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

r_waitlist->get_wait_list( IMPORTING

ex_wait_list = r_customer_list ).

n_o_lines = LINES( r_customer_list ).

IF n_o_lines > 0.

CLEAR it_customer_list.

LOOP AT r_customer_list INTO r_cust.

r_cust->get_attributes( IMPORTING ex_cust = wa_cust ).

INSERT wa_cust INTO TABLE it_customer_list.

ENDLOOP.

" show dynpro with all customers and their data

CALL FUNCTION ’BC401_DISPLAY_DATA’

EXPORTING

im_list = it_customer_list.

ELSE.

MESSAGE s903(BC401)

WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

* The waitinglist for flight &1 &2 &3 has no entries !

ENDIF.

ELSE.

MESSAGE s902(BC401) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

* There is no waitinglist for flight Flug &1 &2 &3 !

ENDIF.

WHEN ’DELETE’. "##########################################

TRY.

r_buffer->delete_wait_list( EXPORTING

im_carrid = sdyn_conn-carrid

im_connid = sdyn_conn-connid

im_fldate = sdyn_conn-fldate ).

MESSAGE s906(BC401) WITH

sdyn_conn-carrid sdyn_conn-connid sdyn_conn-fldate.

* Waitinglist for flight &1 &2 &3 has been deleted succesfully !

CATCH cx_wait_list INTO r_exc.

text = r_exc->get_text( ).

MESSAGE text TYPE ’S’.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 517

Page 528: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

ENDTRY.

WHEN ’FIRST’. "##########################################

r_waitlist = r_buffer->get_wait_list( im_carrid = sdyn_conn-carrid

im_connid = sdyn_conn-connid

im_fldate = sdyn_conn-fldate ).

IF r_waitlist IS BOUND.

TRY.

r_waitlist->get_first( ).

MESSAGE s907(BC401)

WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

* The first customer on waitinglist &1 &2 &3

* has been deleted.

CATCH cx_wait_list INTO r_exc.

text = r_exc->get_text( ).

MESSAGE text TYPE ’I’.

ENDTRY.

ELSE.

MESSAGE s902(BC401) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

* There is no waitinglist for flight &1 &2 &3 !

ENDIF.

WHEN ’ADD’. "##########################################

IF scustom-id IS INITIAL.

MESSAGE s908(BC401).

* Please enter a correct customernumber !

EXIT.

ENDIF.

r_waitlist = r_buffer->get_wait_list( im_carrid = sdyn_conn-carrid

im_connid = sdyn_conn-connid

im_fldate = sdyn_conn-fldate ).

IF r_waitlist IS BOUND.

TRY.

CREATE OBJECT r_customer EXPORTING im_id = scustom-id

im_name = scustom-name

im_street = scustom-street

im_city = scustom-city

im_app_date = sy-datum.

Continued on next page

518 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 529: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

r_waitlist->add( r_customer ).

MESSAGE s910(BC401)

WITH scustom-id sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

* Customer &1 was appended to waitinglist for flight &2 &3 &4

CATCH cx_wait_list INTO r_exc. "wann könnte das passieren ???

text = r_exc->get_text( ).

MESSAGE text TYPE ’I’.

ENDTRY.

ELSE.

MESSAGE s902(BC401) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

* There is no waitinglist for flight &1 &2 &3 !

ENDIF.

WHEN ’DEL’. "##########################################

IF scustom-id IS INITIAL.

MESSAGE s908(BC401).

* Please select a valid customernumber !

EXIT.

ENDIF.

r_waitlist = r_buffer->get_wait_list( im_carrid = sdyn_conn-carrid

im_connid = sdyn_conn-connid

im_fldate = sdyn_conn-fldate ).

IF r_waitlist IS BOUND.

IF NOT r_customer IS BOUND.

MESSAGE s911(BC401).

ELSE.

TRY.

r_waitlist->delete( r_customer ).

MESSAGE s912(BC401)

WITH scustom-id sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

* Customer &1 was deleted from waitinglist for flight &2 &3 &4 !

CATCH cx_wait_list INTO r_exc.

text = r_exc->get_text( ).

MESSAGE text TYPE ’I’.

ENDTRY.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 519

Page 530: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

ENDIF.

ELSE.

MESSAGE s902(BC401) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

* There is no waitinglist for flight &1 &2 &3 !

ENDIF.

WHEN ’POS’. "##########################################

DATA pos LIKE sy-tabix.

DATA flight TYPE string.

DATA fldate(10) TYPE c.

IF scustom-id IS INITIAL.

MESSAGE s908(BC401).

* Please enter a valid customernumber !

EXIT.

ENDIF.

r_waitlist = r_buffer->get_wait_list( im_carrid = sdyn_conn-carrid

im_connid = sdyn_conn-connid

im_fldate = sdyn_conn-fldate ).

IF r_waitlist IS BOUND.

TRY.

CREATE OBJECT r_customer EXPORTING im_id = scustom-id

im_name = scustom-name

im_street = scustom-street

im_city = scustom-city

im_app_date = sy-datum.

r_waitlist->get_pos( EXPORTING im_customer = r_customer

IMPORTING ex_pos = pos ).

WRITE sdyn_conn-fldate TO fldate.

CONCATENATE sdyn_conn-carrid sdyn_conn-connid fldate

INTO flight SEPARATED BY space.

MESSAGE i913(BC401) WITH scustom-id flight pos.

* Customer &1 is held on list for flight &2 at position &3

CATCH cx_wait_list INTO r_exc.

text = r_exc->get_text( ).

MESSAGE text TYPE ’I’.

ENDTRY.

ELSE.

MESSAGE s902(BC401) WITH sdyn_conn-carrid sdyn_conn-connid

sdyn_conn-fldate.

Continued on next page

520 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 531: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

* There is no waitinglist for flight &1 &2 &3 !

ENDIF.

ENDCASE.

ENDMODULE. " user_command_0100 INPUT

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

*& Module check_flight INPUT

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

* text

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

MODULE check_flight INPUT.

SELECT SINGLE * FROM sflight INTO wa_sflight

WHERE carrid = sdyn_conn-carrid

AND connid = sdyn_conn-connid

AND fldate = sdyn_conn-fldate.

IF sy-subrc <> 0.

MESSAGE e904(BC401).

* Please select a valid flight !

ENDIF.

ENDMODULE. " check_flight INPUT

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

*& Module exit INPUT

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

* text

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

MODULE exit INPUT.

CASE ok_code.

WHEN ’CANCEL’.

CLEAR: scustom, sdyn_conn.

LEAVE TO SCREEN 100.

WHEN ’EXIT’.

LEAVE PROGRAM.

ENDCASE.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 521

Page 532: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

ENDMODULE. " exit INPUT

Include SAPBC401_PRJS_WAITLIST_O01

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

*& Include SAPBC401_PRJS_WAITLIST_O01

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

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

*& Module STATUS_0100 OUTPUT

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

MODULE status_0100 OUTPUT.

SET PF-STATUS ’DYNPRO_100’.

SET TITLEBAR ’TITLE_100’.

ENDMODULE. " STATUS_0100 OUTPUT

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

*& Module clear_ok_code OUTPUT

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

* text

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

MODULE clear_ok_code OUTPUT.

CLEAR ok_code.

ENDMODULE. " clear_ok_code OUTPUT

Include SAPBC401_PRJS_INC_1

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

*& Include SAPBC401_PRJS_INC_1

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

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

* CLASS lcl_customer DEFINITION

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

CLASS lcl_customer DEFINITION.

Continued on next page

522 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 533: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

PUBLIC SECTION.

METHODS constructor IMPORTING im_id TYPE s_customer

im_name TYPE s_custname

im_street TYPE s_street

im_city TYPE city

im_app_date TYPE d.

METHODS get_attributes EXPORTING ex_cust TYPE bc401_typd_cust.

DATA: id TYPE s_customer READ-ONLY.

PRIVATE SECTION.

DATA: name TYPE s_custname,

street TYPE s_street,

city TYPE city,

app_date TYPE d.

ENDCLASS. "lcl_customer DEFINITION

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

* CLASS lcl_customer IMPLEMENTATION

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

CLASS lcl_customer IMPLEMENTATION.

METHOD constructor.

id = im_id.

name = im_name.

street = im_street.

city = im_city.

app_date = im_app_date.

ENDMETHOD. "constructor

METHOD get_attributes.

ex_cust-id = id.

ex_cust-name = name.

ex_cust-street = street.

ex_cust-city = city.

ex_cust-app_date = app_date.

ENDMETHOD. "get_attributes

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 523

Page 534: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

ENDCLASS. "lcl_customer IMPLEMENTATION

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

* CLASS lcl_waitlist DEFINITION

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

CLASS lcl_waitlist DEFINITION.

PUBLIC SECTION.

TYPES ty_customer_list TYPE

STANDARD TABLE OF REF TO lcl_customer WITH DEFAULT KEY.

METHODS constructor IMPORTING im_carrid TYPE sflight-carrid

im_connid TYPE sflight-connid

im_fldate TYPE sflight-fldate.

METHODS add IMPORTING im_customer TYPE REF TO lcl_customer

RAISING cx_wait_list.

METHODS delete IMPORTING im_customer TYPE REF TO lcl_customer

RAISING cx_wait_list.

METHODS get_pos IMPORTING im_customer TYPE REF TO lcl_customer

EXPORTING ex_pos LIKE sy-tabix

RAISING cx_wait_list.

METHODS get_wait_list EXPORTING ex_wait_list

TYPE ty_customer_list.

METHODS get_first RAISING cx_wait_list.

DATA:

carrid TYPE sflight-carrid READ-ONLY,

connid TYPE sflight-connid READ-ONLY,

fldate TYPE sflight-fldate READ-ONLY.

PRIVATE SECTION.

DATA: customer_list TYPE ty_customer_list.

ENDCLASS. "lcl_waitlist DEFINITION

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

* CLASS lcl_waitlist IMPLEMENTATION

Continued on next page

524 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 535: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

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

CLASS lcl_waitlist IMPLEMENTATION.

METHOD constructor.

carrid = im_carrid.

connid = im_connid.

fldate = im_fldate.

ENDMETHOD. "constructor

METHOD get_wait_list. "----------------------------

ex_wait_list = customer_list.

ENDMETHOD. "get_wait_list

METHOD add. "--------------------------------------

READ TABLE customer_list WITH KEY

table_line->id = im_customer->id TRANSPORTING NO FIELDS.

*** customer is not in wait_list

IF sy-subrc <> 0.

INSERT im_customer INTO TABLE customer_list.

ELSE.

*** customer is already in wait_list for this flight !!!

RAISE EXCEPTION TYPE cx_wait_list

EXPORTING

textid = cx_wait_list=>cx_wait_list_customer_there

customer = im_customer->id

carrid = carrid

connid = connid

fldate = fldate.

ENDIF.

ENDMETHOD. "add

METHOD get_first. "--------------------------------

DATA r_cust TYPE REF TO lcl_customer.

READ TABLE customer_list INTO r_cust INDEX 1.

IF sy-subrc <> 0.

RAISE EXCEPTION TYPE cx_wait_list

EXPORTING

textid = cx_wait_list=>cx_wait_list_no_entry

carrid = carrid

connid = connid

fldate = fldate.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 525

Page 536: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

ELSE.

DELETE customer_list INDEX 1.

ENDIF.

ENDMETHOD. "get_first

METHOD delete. "---------------------------------

DELETE customer_list

WHERE table_line->id = im_customer->id.

IF sy-subrc <> 0.

RAISE EXCEPTION TYPE cx_wait_list

EXPORTING

textid = cx_wait_list=>cx_wait_list_customer_notthere

customer = im_customer->id

carrid = carrid

connid = connid

fldate = fldate.

ENDIF.

ENDMETHOD. "delete

METHOD get_pos. "---------------------------------

READ TABLE customer_list

WITH KEY table_line->id = im_customer->id

TRANSPORTING NO FIELDS.

IF sy-subrc = 0.

ex_pos = sy-tabix.

ELSE.

RAISE EXCEPTION TYPE cx_wait_list

EXPORTING

textid = cx_wait_list=>cx_wait_list_customer_notthere

customer = im_customer->id

carrid = carrid

connid = connid

fldate = fldate.

ENDIF.

ENDMETHOD. "get_pos

ENDCLASS. "lcl_waitlist IMPLEMENTATION

Continued on next page

526 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 537: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

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

* CLASS lcl_buffer DEFINITION

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

* implemented as SINGLETON, should exist only once ! *

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

CLASS lcl_buffer DEFINITION CREATE PRIVATE.

PUBLIC SECTION.

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

CLASS-METHODS: class_constructor.

CLASS-METHODS: get_buffer_ref RETURNING value(re_buffer)

TYPE REF TO lcl_buffer.

METHODS: create_wait_list IMPORTING im_carrid TYPE s_carr_id

im_connid TYPE s_conn_id

im_fldate TYPE sflight-fldate

RETURNING value(re_waitlist)

TYPE REF TO lcl_waitlist

RAISING cx_wait_list.

METHODS: get_wait_list IMPORTING im_carrid TYPE s_carr_id

im_connid TYPE s_conn_id

im_fldate TYPE sflight-fldate

RETURNING value(re_waitlist)

TYPE REF TO lcl_waitlist.

METHODS: delete_wait_list IMPORTING im_carrid TYPE s_carr_id

im_connid TYPE s_conn_id

im_fldate TYPE sflight-fldate

RAISING cx_wait_list.

METHODS: delete_all_wait_lists.

PRIVATE SECTION.

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

CLASS-DATA: r_buffer TYPE REF TO lcl_buffer.

DATA: wait_list TYPE STANDARD TABLE OF

REF TO lcl_waitlist.

ENDCLASS. "lcl_buffer DEFINITION

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

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 527

Page 538: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

* CLASS lcl_buffer IMPLEMENTATION

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

CLASS lcl_buffer IMPLEMENTATION.

METHOD class_constructor.

CREATE OBJECT r_buffer.

ENDMETHOD. "class_constructor

METHOD get_buffer_ref.

re_buffer = r_buffer.

ENDMETHOD. "get_buffer_ref

METHOD create_wait_list. "----------------------------

DATA: r_waitlist TYPE REF TO lcl_waitlist.

r_waitlist = get_wait_list( im_carrid = im_carrid

im_connid = im_connid

im_fldate = im_fldate ).

IF NOT r_waitlist IS BOUND.

CREATE OBJECT r_waitlist EXPORTING im_carrid = im_carrid

im_connid = im_connid

im_fldate = im_fldate.

INSERT r_waitlist INTO TABLE wait_list.

ELSE.

RAISE EXCEPTION TYPE cx_wait_list

EXPORTING

carrid = im_carrid

connid = im_connid

fldate = im_fldate

textid = cx_wait_list=>cx_wait_list_exists.

ENDIF.

ENDMETHOD. "create_wait_list

METHOD get_wait_list. "----------------------------

READ TABLE wait_list INTO re_waitlist WITH KEY

table_line->carrid = im_carrid

table_line->connid = im_connid

table_line->fldate = im_fldate.

ENDMETHOD. "get_wait_list

METHOD delete_wait_list. "----------------------------

DATA: r_waitlist TYPE REF TO lcl_waitlist.

r_waitlist = get_wait_list( im_carrid = im_carrid

Continued on next page

528 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 539: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

im_connid = im_connid

im_fldate = im_fldate ).

IF NOT r_waitlist IS BOUND.

RAISE EXCEPTION TYPE cx_wait_list

EXPORTING

carrid = im_carrid

connid = im_connid

fldate = im_fldate.

ELSE.

DELETE wait_list

WHERE table_line->carrid = im_carrid

AND table_line->connid = im_connid

AND table_line->fldate = im_fldate.

ENDIF.

ENDMETHOD. "delete_wait_list

METHOD delete_all_wait_lists. "----------------------------

CLEAR wait_list.

" ATTENTION: in our case, this also deletes all customer-objects.

" --> COMPOSITION in class-diagram ?

ENDMETHOD. "delete_all_wait_lists

ENDCLASS. "lcl_buffer IMPLEMENTATION

Flow Logic of Screen 100

PROCESS BEFORE OUTPUT.

MODULE status_0100.

MODULE clear_ok_code.

PROCESS AFTER INPUT.

MODULE exit AT EXIT-COMMAND.

CHAIN.

FIELD: sdyn_conn-carrid,

sdyn_conn-connid,

sdyn_conn-fldate.

Continued on next page

2005/Q4 © 2005 SAP AG. All rights reserved. 529

Page 540: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 7: Case Study TAW10_3

MODULE check_flight.

ENDCHAIN.

CHAIN.

FIELD: scustom-id,

scustom-name,

scustom-city.

MODULE check_and_create_cust. " ON CHAIN-REQUEST.

ENDCHAIN.

MODULE user_command_0100.

530 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 541: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Case Study and Preview

Lesson Summary

You should now be able to:� Explain the concepts relating to object-oriented programming with ABAP

Objects and apply these in a small, simple application� Explain some of the new ABAP Objects concepts (such as ABAP Unit and

shared objects) that are available as of SAP Web AS 6.40

2005/Q4 © 2005 SAP AG. All rights reserved. 531

Page 542: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit Summary TAW10_3

Unit SummaryYou should now be able to:� Explain the concepts relating to object-oriented programming with ABAP

Objects and apply these in a small, simple application� Explain some of the new ABAP Objects concepts (such as ABAP Unit and

shared objects) that are available as of SAP Web AS 6.40

532 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 543: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 8503 ABAP Certification

Unit OverviewThis unit contains a certification description and lists the topics tested in thecertification test.

Unit ObjectivesAfter completing this unit, you will be able to:

� Name all topics about which questions are asked in the ABAP Certification test.

Unit ContentsLesson: Description of Certification ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .534

2005/Q4 © 2005 SAP AG. All rights reserved. 533

Page 544: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 8: ABAP Certification TAW10_3

Lesson:504

Description of CertificationLesson Duration: 1 Minutes

Lesson OverviewThis lesson lists all topics about which questions are asked in SAP ConsultantCertification Development Consultant SAP NetWeaver 2004 � ApplicationDevelopment Focus ABAP. It also includes a weighting that indicates how manyquestions are asked that relate to a particular area.

Lesson ObjectivesAfter completing this lesson, you will be able to:

� Name all topics about which questions are asked in the ABAP Certification test.

Business ExampleSuppose you want to do the ABAP Certification and you want to find out exactly whatyou need to know for the test.

SAP Consultant Certification Development ConsultantSAP NetWeaver 2004 � Application Development FocusABAPSoftware component: SAP Web Application Server 6.40

The Certification is part of the course TAW12, which is offered separately at manySAP locations.

Certification ID (booking code): C_TAW12_04

Duration of certification: 3 hours

Number of certification questions: 80

Prerequisite certificates for participating in this certification test: none

534 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 545: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Description of Certification

Courses for preparing for the certification test: TAW10 (ABAP WorkbenchFundamentals), TAW12 (ABAP Workbench Concepts)

Please note that auxiliary materials are not permitted during the certification test (noaccess to the online documentation and no access to an SAP system).

The certfication test for Development Consultant SAP NetWeaver 2004 - ApplicationDevelopment Focus ABAP verifies the participant's knowledge of SAP NetWeaver inthe field of the Application Development Focus ABAP consultant profile. Participantscan use this certificate to prove their basic knowledge in this consultant profile and toimplement this knowledge in projects.

The certification test contains questions from the following content areas:

List of Topics

1. SAP Technology (+)

� SAP Systems (mySAP Business Suite and SAP NetWeaver)� Technical Structure of an SAP Web Application Server

2. ABAP Workbench Fundamentals (++)

� Data Types and Data Objects (Declaration)� Internal Tables� Data Retrieval (Authorization Check)� Subroutines� Function Groups and Function Modules� Programs Calls and Data Storage Management

3. Advanced ABAP (++)

� ABAP Runtime� ABAP Types and Data Objects (Use)� Open SQL (Efficient Programming)� Dynamic Programming

2005/Q4 © 2005 SAP AG. All rights reserved. 535

Page 546: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 8: ABAP Certification TAW10_3

4. ABAP Objects (++)

� Classes and Objects� Inheritance� Polymorphism (Casting)� Interfaces� Events� Global Classes and Interfaces� Exception Handling� Shared Objects

5. ABAP Dictionary (++)

� Database Tables� Performance with Table Accesses� Consistency Through Input Check (Foreign Key Dependency)� Dependencies with ABAP Dictionary Objects� Views� Search Help

6. Techniques of List Processing (++)

� Outputting Data in Lists� Selektion Screen� Logical Databases� Interactive Lists� Creating Lists Using ALV Grid Control:

� Simple Lists� Field Catalog� Layout� Event Handling

536 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 547: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Description of Certification

7. Dialog Programming (++)

� Screen (Fundamentals)� Program Interface (GUI Title, GUI Status)� Screen Elements for Output (Text Fields, Status Icons, and Group Boxes)� Input/Output Screen Elements� Subscreen and Tabstrip Control� Table Control� Context Menu� Lists in Dialog Programming

8. Database Updates (+)

� Database Updates with Open SQL� LUW�s and Client/Server Architecture� SAP Lock Concept� Organizing Database Updates� Complex LUW Processing� Number Assignment� Creating Change Documents

9. Enhancements and Modifications (+)

� Changing the SAP Standard� Personalization� Enhancing Dictionary Elements� Enhancements Using Customer Exits� Business Transaction Events� Business Add-Ins� Modifications

Percentage of questions for each topic:

+ = 1 - 10%

++ = 11 - 20%

+++ = over 20%

2005/Q4 © 2005 SAP AG. All rights reserved. 537

Page 548: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 8: ABAP Certification TAW10_3

Information subject to change. Copyright © SAP AG 2005.

538 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 549: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Lesson: Description of Certification

Facilitated DiscussionOpportunity to discuss open issues.

Discussion QuestionsUse the following questions to engage the participants in the discussion. Feel free touse your own additional questions.

2005/Q4 © 2005 SAP AG. All rights reserved. 539

Page 550: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Unit 8: ABAP Certification TAW10_3

Lesson Summary

You should now be able to:� Name all topics about which questions are asked in the ABAP Certification test.

540 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 551: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Unit Summary

Unit SummaryYou should now be able to:� Name all topics about which questions are asked in the ABAP Certification test.

2005/Q4 © 2005 SAP AG. All rights reserved. 541

Page 552: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Course Summary TAW10_3

Course SummaryYou should now be able to:

� Describe the data structure of SAP systems� Use the ABAP Workbench tools� Create lists using classic reports� Create and call function groups and function modules� Work with the ABAP Dictionary� Program in a performance-sensitive manner� Describe the concepts behind object-oriented programming� Create lists using ALV Grid Control

542 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 553: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

IndexAabstraction, 20ACTIVATION, 199aggregation, 27, 58alias name, 158�159, 168ALV Grid Control, 257, 324association, 24binary and recursive, 24

attribute, 43KERNEL_ERRID, 388PREVIOUS, 402private, 45public, 45static, 47

BBusiness Add-Ins, 263CCALL METHOD, 60�61EXCEPTIONS, 49EXPORTING, 49IMPORTING, 49

cardinality, 24CHANGING, 49class, 19CL_ABAP_CLASSDE-SCR, 433CL_ABAP_STRUCTDE-SCR, 431CL_ABAP_TYPEDESCR,429, 431, 433CL_GUI_ALV_GRID, 258CL_GUI_CUSTOM_CON-TAINER, 258definition, 43

definition part, 43ClassCL_GUI_ALV_GRID, 325CL_GUI_CUSTOM_CON-TAINER, 325

CLASS, 238definition, 43INHERITING FROM, 112PRIVATE SECTION, 46PUBLIC SECTION, 46

class attribute, 47Class Builderdisplay settings, 250�251editing class components,245

class diagram, 23CLASS EVENTS, 196class method, 52CLASS_CONSTRUCTOR, 67CLASS-METHODS, 51component interface, 167composition, 27compound interface, 167constructor, 65, 115static, 67

CONSTRUCTOR, 65container control, 258Container control, 325CREATE OBJECT, 55DDATATYPE REF TO, 54

DEFAULT, 49DEFINITION, 43definition part, 43

2005/Q4 © 2005 SAP AG. All rights reserved. 543

Page 554: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Index TAW10_3

delegation, 31delegation principle, 13DESCRIBE FIELD, 429DESCRIBE TABLE, 429destructor, 65downcast, 127, 165Eencapsulation, 7, 45Enjoy Demo Center, 262, 327eventstatic, 193

Event control, 14event handler method, 194EVENTS, 196exceptionclass-based, 386definition, 386mapping, 402propagate, 388propagation, 394

exception chain, 386, 402exception class, 386CX_DYNAMIC_CHECK,387, 401CX_NO_CHECK, 387, 401CX_ROOT, 387, 402CX_STATIC_CHECK, 387,401CX_SY_ARITH-METIC_ERROR, 390CX_SY_ARITH-METIC_OVERFLOW,390CX_SY_MOVE_CAST_ER-ROR, 128, 165CX_SY_ZERODIVIDE,388global, 386inheritance hierarchy, 401local, 386superclass, 401

exception handling, 386

CATCH, 388CLEANUP, 389, 395static check, 401syntax check, 401TRY, ENDTRY, 388

exception instance, 386exception texts, 388Ffunction groupdata management, 7

GGarbage Collector, 56generalization, 28, 110global classprint, 245test, 245

Hhandler table, 200IindicatorOO transaction model, 270

information hiding, 45Inheritance, 14instance, 19instance attribute, 47instance constructor, 65, 115instance event, 193instance method, 51instantiationclass, 53

interfaceclass, 45compound, 167method, 49

INTERFACE, 158interface resolution operator,158�159

INTERFACES, 158IS INITIAL, 56

544 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 555: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

TAW10_3 Index

MME, 68MESSAGE, 390methodcall, 60�61definition, 49DESCRIBE_BY_DATA,431DESCRIBE_BY_OB-JECT_REF, 433functional, 62GET_RELATIVE_NAME,433GET_SOURCE_POSI-TION, 387GET_TEXT, 387, 390, 392,395parameter, 49private, 51public, 51redefinition, 113REFRESH_TABLE_DIS-PLAY, 259SET_TA-BLE_FOR_FIRST_DIS-PLAY, 259signature, 49static, 51

MethodREFRESH_TABLE_DIS-PLAY, 327SET_TA-BLE_FOR_FIRST_DIS-PLAY, 326

METHODS, 51FOR EVENT, 197

MOVE, 55, 164widening cast assignmentoperator, 127

multiple inheritance, 112multiple instantiation, 11multiplicity, 24

Nnamespaceclass, 51

narrowing cast, 161Narrowing cast, 120null reference, 54Oobjectbehavior, 22classification, 18identity, 19status, 19, 22

object diagram, 29object link, 24Object Management Group(OMG), 21

OMG, 21OO transaction, 269OO transaction model, 270OPTIONAL, 49Ppackage, 22polymorphism, 14, 124, 162PRIVATE SECTION, 46programming modelobject-oriented, 11procedural, 5

PROTECTED SECTION, 116PUBLIC SECTION, 46RRAISE EVENT, 196RAISING, 394READ-ONLY, 44, 46redefinition, 113Refactoring Assistant, 254referenceindependent, 56

reference variable, 54registration, 198, 200RETURNING, 49

2005/Q4 © 2005 SAP AG. All rights reserved. 545

Page 556: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

Index TAW10_3

role, 24role design pattern, 130RTTC, 433RTTI, 429Run Time Type Creation, 433runtime errorBCD_ZERODIVIDE, 388catchable, 387

Runtime Type Identification(RTTI), 429

SSAP Control Framework, 257,323

self-reference, 68SENDER, 197sequence diagram, 30SET HANDLER, 199ACTIVATION, 199FOR ALL INSTANCES,199

signature, 49specialization, 28, 110static attribute, 47static constructor, 67static method, 51

subclass, 110SUPER, 113superclass, 110TTABLE_LINE, 58text ID, 395transaction code, 269transaction service, 269typedynamic, 120static, 120

TYPE REF TO, 54UUML, 21Unified Modeling Language, 21upcast, 120, 161Vvisibility sectionprotected, 116

Wwidening cast, 127, 165widening cast assignmentoperator, 127, 164

546 © 2005 SAP AG. All rights reserved. 2005/Q4

Page 557: Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones  · 2013-01-27Parte 3 - Notas y trucos SAP (Bitacora) | Trucos y anotaciones para el día a día con Sap

FeedbackSAP AG has made every effort in the preparation of this course to ensure the accuracyand completeness of the materials. If you have any corrections or suggestions forimprovement, please record them in the appropriate place in the course evaluation.

2005/Q4 © 2005 SAP AG. All rights reserved. 547