Uploaded by Kosmas Gossis

TAW10 3

advertisement
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
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 the
express permission of SAP AG. The information contained herein may be changed without prior notice.
Some software products marketed by SAP AG and its distributors contain proprietary software
components of other software vendors.
Trademarks
•
Microsoft®, WINDOWS®, NT®, EXCEL®, Word®, PowerPoint® and SQL Server® are
registered trademarks of Microsoft Corporation.
•
IBM®, DB2®, OS/2®, DB2/6000®, Parallel Sysplex®, MVS/ESA®, RS/6000®, AIX®, S/390®,
AS/400®, OS/390®, and OS/400® are registered trademarks of IBM Corporation.
•
ORACLE® is a registered trademark of ORACLE Corporation.
•
INFORMIX®-OnLine for SAP and INFORMIX® Dynamic ServerTM are registered trademarks
of Informix Software Incorporated.
•
UNIX®, X/Open®, OSF/1®, and Motif® are registered trademarks of the Open Group.
•
Citrix®, the Citrix logo, ICA®, Program Neighborhood®, MetaFrame®, WinFrame®,
VideoFrame®, MultiWin® and other Citrix product names referenced herein are trademarks of
Citrix Systems, Inc.
•
HTML, DHTML, XML, XHTML are trademarks or registered trademarks of W3C®, World Wide
Web Consortium, Massachusetts Institute of Technology.
•
JAVA® is a registered trademark of Sun Microsystems, Inc.
•
JAVASCRIPT® is a registered trademark of Sun Microsystems, Inc., used under license for
technology invented and implemented by Netscape.
•
SAP, SAP Logo, R/2, RIVA, R/3, SAP ArchiveLink, SAP Business Workflow, WebFlow, SAP
EarlyWatch, BAPI, SAPPHIRE, Management Cockpit, mySAP.com Logo and mySAP.com are
trademarks or registered trademarks of SAP AG in Germany and in several other countries all
over the world. All other products mentioned are trademarks or registered trademarks of their
respective companies.
Disclaimer
THESE MATERIALS ARE PROVIDED BY SAP ON AN "AS IS" BASIS, AND SAP EXPRESSLY
DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR APPLIED, INCLUDING WITHOUT
LIMITATION WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, WITH RESPECT TO THESE MATERIALS AND THE SERVICE, INFORMATION, TEXT,
GRAPHICS, LINKS, OR ANY OTHER MATERIALS AND PRODUCTS CONTAINED HEREIN. IN
NO EVENT SHALL SAP BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL,
CONSEQUENTIAL, OR PUNITIVE DAMAGES OF ANY KIND WHATSOEVER, INCLUDING
WITHOUT LIMITATION LOST REVENUES OR LOST PROFITS, WHICH MAY RESULT FROM
THE USE OF THESE MATERIALS OR INCLUDED SOFTWARE COMPONENTS.
About This Handbook
This handbook is intended to complement the instructor-led presentation of this
course, and serve as a source of reference. It is not suitable for self-study.
Typographic Conventions
American English is the standard used in this handbook. The following typographic
conventions are also used.
Type Style
Description
Example text
Words or characters that appear on the screen. These
include field names, screen titles, pushbuttons as well as
menu names, paths, and options.
Also used for cross-references to other documentation
both internal (in this documentation) and external (in
other locations, such as SAPNet).
2005/Q4
Example text
Emphasized words or phrases in body text, titles of
graphics, and tables
EXAMPLE TEXT
Names of elements in the system. These include report
names, program names, transaction codes, table names,
and individual key words of a programming language,
when surrounded by body text, for example SELECT
and INCLUDE.
Example text
Screen output. This includes file and directory names
and their paths, messages, names of variables and
parameters, and passages of the source text of a program.
Example text
Exact user entry. These are words and characters that
you enter in the system exactly as they appear in the
documentation.
<Example text>
Variable user entry. Pointed brackets indicate that you
replace these words and characters with appropriate
entries.
© 2005 SAP AG. All rights reserved.
iii
About This Handbook
TAW10_3
Icons in Body Text
The following icons are used in this handbook.
Icon
Meaning
For more information, tips, or background
Note or further explanation of previous point
Exception or caution
Procedures
Indicates that the item is displayed in the instructor’s
presentation.
iv
© 2005 SAP AG. All rights reserved.
2005/Q4
Contents
Course Overview ............................................................................. vii
Course Goals.................................................................................vii
Course Objectives ........................................................................... ix
Unit 1: Introduction to Object-Oriented Programming ................................1
The Object-Oriented Programming Model ................................................ 3
Analysis and Design with UML............................................................ 18
Fundamental Object-Oriented Syntax Elements ....................................... 41
Unit 2: Object-Oriented Concepts and Programming Techniques ...............107
Inheritance and Casting................................................................... 109
Interfaces and Casting .................................................................... 153
Events ....................................................................................... 193
Unit 3: Object-Oriented Repository Objects ..........................................235
Global Classes and Interfaces ........................................................... 237
Unit 4: ALV Grid Control ...................................................................321
ALV Grid Control - Simple Lists .......................................................... 323
ALV Grid Control - Field Catalog ........................................................ 337
ALV Grid Control - Layout ................................................................ 349
ALV Grid Control - Events ................................................................ 368
Unit 5: Exception Handling and RTTS ..................................................383
Exception Handling in ABAP Objects ................................................... 385
RTTS (Run Time Type Service) ......................................................... 428
Unit 6: Shared Objects .....................................................................457
Shared Objects ............................................................................ 458
Unit 7: Case Study ..........................................................................495
Case Study and Preview ................................................................. 496
2005/Q4
© 2005 SAP AG. All rights reserved.
v
Contents
TAW10_3
Unit 8: ABAP Certification.................................................................533
Description of Certification................................................................ 534
Index ............................................................................................543
vi
© 2005 SAP AG. All rights reserved.
2005/Q4
Course Overview
This training course, lasting three weeks, provides a comprehensive and detailed
introduction to the basics of ABAP/ABAP object-oriented programming and the
ABAP Workbench tools. This course also prepares you for certification as a
Development Consultant SAP NetWeaver - ABAP Workbench 2004.
Target Audience
This course is intended for the following audiences:
•
Development consultants and developers who are responsible for adapting and
developing ABAP/ABAP Objects programs
Course Prerequisites
Required Knowledge
•
•
Solid EDP basic knowledge
Good programming experience in a different programming language
Course Duration Details
Unit 1:
Introduction to Object-Oriented Programming
The Object-Oriented Programming Model
Analysis and Design with UML
Exercise 1: UML Class Diagrams
Fundamental Object-Oriented Syntax Elements
Exercise 2: Local Classes
Exercise 3: Objects
Exercise 4: Method Calls
Exercise 5: Constructors
Exercise 6: Private Methods
30 Minutes
30 Minutes
30 Minutes
200 Minutes
45 Minutes
20 Minutes
45 Minutes
45 Minutes
45 Minutes
Unit 2: Object-Oriented Concepts and Programming Techniques
160 Minutes
Inheritance and Casting
60 Minutes
Exercise 7: Class Hierarchies
20 Minutes
Exercise 8: Polymorphism
45 Minutes
Exercise 9: Aggregation and Generic Calls
120 Minutes
Interfaces and Casting
45 Minutes
Exercise 10: Interface Implementation
2005/Q4
© 2005 SAP AG. All rights reserved.
vii
Course Overview
TAW10_3
Exercise 11: Aggregation, Generic Calls, and
Polymorphism
Events
Exercise 12: Events in Superclasses
Exercise 13: (Optional): Events in Interfaces
Unit 3: Object-Oriented Repository Objects
Global Classes and Interfaces
Exercise 14: Global Classes
Exercise 15: Global Interfaces
Exercise 16: (Optional): Refactoring Assistant
Exercise 17: ALV Grid Control
Unit 4: ALV Grid Control
ALV Grid Control - Simple Lists
Exercise 18: ALV Grid Control - Simple Lists
ALV Grid Control - Field Catalog
ALV Grid Control - Layout
Exercise 19: ALV Grid Control - Field Catalog
and Layout
ALV Grid Control - Events
Exercise 20: ALV Grid Control - Events
Unit 5: Exception Handling and RTTS
Exception Handling in ABAP Objects
Exercise 21: Class-Based Exceptions
Exercise 22: (Optional): Mapping Exceptions to
Each Other
RTTS (Run Time Type Service)
Exercise 23: RTTI: Querying Object Attributes
Exercise 24: (Optional): RTTC: Creating Types
at Runtime
viii
45 Minutes
75 Minutes
40 Minutes
30 Minutes
180 Minutes
40 Minutes
30 Minutes
15 Minutes
45 Minutes
1 Minutes
Minutes
50 Minutes
80 Minutes
Minutes
1 Minutes
Minutes
90 Minutes
45 Minutes
45 Minutes
120 Minutes
30 Minutes
30 Minutes
Unit 6: Shared Objects
Shared Objects
Exercise 25: Using Shared Objects
60 Minutes
50 Minutes
Unit 7: Case Study
Case Study and Preview
Exercise 26: Create a UML Class Diagram
Exercise 27: Develop a Solution for a Test Case
30 Hours
20 Minutes
300 Minutes
Unit 8: ABAP Certification
Description of Certification
1 Minutes
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Course Overview
Course Goals
This course will prepare you to:
•
•
•
Work with the ABAP Workbench tools
Write your own simple ABAP programs
Program object-oriented ABAP Objects
Course Objectives
After 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 Information
The information in this course pertains to the following SAP Software Components
and releases:
•
•
SAP Web AS 6.20
SAP Web AS 6.40
Work in progress
2005/Q4
© 2005 SAP AG. All rights reserved.
ix
Course Overview
x
TAW10_3
© 2005 SAP AG. All rights reserved.
2005/Q4
Unit 1
Introduction to Object-Oriented
Programming
1
For more information, see the introductory instructor notes in the lesson.
Unit Overview
This unit covers the basics of object-oriented programing with ABAP Objects and
provides an insight into data modeling using Unified Modeling Language.
Unit Objectives
After completing this unit, you will be able to:
•
•
•
•
•
•
•
•
•
•
Explain the differences between procedural and object-oriented programming
models
List the advantages of the object-oriented programming model
Name the most important diagram types in UML
Create simple class diagrams
Create simple object diagrams
Describe sequence diagrams
Define classes
Generate and delete objects
Access attributes
Call methods
Unit Contents
Lesson: The Object-Oriented Programming Model ............................... 3
2005/Q4
© 2005 SAP AG. All rights reserved.
1
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Lesson: Analysis and Design with UML .......................................... 18
Exercise 1: UML Class Diagrams ............................................. 33
Lesson: Fundamental Object-Oriented Syntax Elements ...................... 41
Exercise 2: Local Classes ...................................................... 71
Exercise 3: Objects ............................................................. 77
Exercise 4: Method Calls ....................................................... 81
Exercise 5: Constructors ....................................................... 87
Exercise 6: Private Methods ................................................... 93
2
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson:
3
Lesson: The Object-Oriented Programming Model
The Object-Oriented Programming Model
Lesson Duration: 30 Minutes
Lesson Overview
Based on your existing knowledge of procedural programming with ABAP, we will
explain the object-oriented approach and encourage you to use it. The main emphasis
will be on explanation. At this stage, it is important that you understand the subject
and 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 the
object-oriented approach. Before you can make a qualified decision, you need to
know object-oriented concepts and their advantages and disadvantages.
Even if this sort of decision is made within your team or by your development
manager, you should be able to contribute to the discussion.
Lesson Objectives
After completing this lesson, you will be able to:
•
•
Explain the differences between procedural and object-oriented programming
models
List the advantages of the object-oriented programming model
Finding the best way to handle this lesson depends on the individual group
of participants. Experience shows that participants often have some previous
knowledge of procedural programming, particularly the contents of the previous
course BC400. Sometimes, for no apparent reason, these participants hesitate to use
object-orientation. Try to overcome this hesitation.
Therefore, it would be counterproductive to put too much emphasis on the last section.
The attributes that are described there need to be dealt with gradually in the specific
lessons. The final section is more suitable for participants with object-oriented
experience in other programming languages. You can assure these participants that
they will soon be re-introduced to some familiar concepts.
It is important to clarify that the object-oriented programming model does not extend
the range of problems that can be solved algorithmically. Object orientation is just
another programming approach. It can solve exactly the same number of problems as
other approaches.
2005/Q4
© 2005 SAP AG. All rights reserved.
3
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Business Example
You need to explain the basics of the object-oriented programming model and its
advantages to your development project manager.
Moving from the Procedural to the Object-Oriented
Programming Model
Object-oriented programming was developed at approximately the same time as
logical and procedural programming models, for example, the programming language
Simula 67. In the past, COBOL and the procedural programming model as expressed
in 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 programming
than object-oriented programming. Therefore, this introduction to object-oriented
programming 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 developed
relatively independently as an in-house programming language, although it was
influenced by other programming languages like COBOL and Pascal. ABAP/4
was then extended to form ABAP Objects. Therefore, ABAP Objects unites
object-oriented and procedural elements in one programming language.
4
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: The Object-Oriented Programming Model
For the object-oriented part, only those object-oriented concepts that had proved
their worth for enterprise application development in other languages, such as Java,
C++, and Smalltalk, were adopted. ABAP Objects, like ABAP/4, also contains some
unique, very advantageous concepts.
You should repeat these points whenever they are relevant throughout the entire
course and illustrate them with specific syntax examples to ensure that they are not
merely 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 the
programming model itself does not support consistent access to some related parts of
the data.
2005/Q4
© 2005 SAP AG. All rights reserved.
5
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 be
encapsulated. On the main program level, however, there is no special protection for
the 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
TAW10_3
Lesson: The Object-Oriented Programming Model
Every time a function module is called in a main program, its function group is loaded
into the internal session. The function group remains active until the main program
is finished. The main program and the function groups that were called in it are all
stored in separate memory areas. Even if their data objects have the same names,
they are not shared.
Only function modules of the function groups can be called from the main program.
In turn, the function modules can access the other components – particularly the
global data – of the function groups. In other words, it is not possible to access the
function group’s global data directly from the main program.
Encapsulation also incorporates the idea that the implementation of a service can be
hidden from the system’s other components, so that these cannot and do not make
assumptions about the internal status of the modularization unit. This way, the design
of these other components is not dependent on a specific implementation of the other
modularization units.
Therefore, a function group is a unit of data and functions that manages this
data. Encapsulated access to data and services – a concept of the object-oriented
programming model – can therefore be supported in the procedural part of ABAP
Objects. This meant that BAPIs could be implemented as function modules and
Business Objects could be implemented as function groups.
It may be helpful to mention some other characteristics of function modules here, such
as remote capability or optional parallelization. In doing so, you risk being drawn
away from the core subject matter, but you will be able to emphasize the power and
versatility of even the procedural part of ABAP Objects.
It can also help participants to understand that object-orientation is just another
programming method and does not necessarily lead to more technical possibilities.
2005/Q4
© 2005 SAP AG. All rights reserved.
7
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 user
or client with the services INC_SPEED, DEC_SPEED, and GET_SPEED. These
services are the function group’s interface and access the global data object SPEED,
which belongs to the whole function group.
Figure 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
TAW10_3
Lesson: The Object-Oriented Programming Model
We feel that the best way to learn about the new aspects is to highlight the differences
from the old characteristics. Multiple instantiation is a new characteristic that could be
suitable for this purpose. Some other object-oriented concepts also exist in procedural
languages or they are easy to imagine.
However, this is not the case for inheritance. It is more difficult, and therefore less
suitable for defining the limits of the object-oriented approach.
Figure 7: Several Instances of One Function Group
It is not possible for the main program to work with several vehicles without extra
programming and administrative effort. Most importantly, one specific vehicle could
no 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
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
The possibility of creating several runtime instances in a capsule for each program
context is one of the key characteristics of object-oriented programming.
In this example, four vehicles were created, all of which have different characteristic
instances. However, they all share the same data structure, the same range of
functions, and the ability to protect their data against access from the outside.
Figure 9: ABAP Main Memory and Encapsulation
Like the function groups, the objects are also stored in the same internal session as
the program that is being used. Also, all data areas are separated from each other and
are therefore protected.
10
© 2005 SAP AG. All rights reserved.
2005/Q4
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-oriented
programming allows you to create a direct abstraction of a real object. For this
purpose, the established concept of encapsulation was systematically extended.
The ABAP Objects Object-Oriented Programming Model
The object-oriented concepts of ABAP Objects are essentially the same as those of
other modern object-oriented languages such as C++ or Java. A small number of
concepts that did not prove to be successful in these other languages were not included
in ABAP Objects. On the other hand, ABAP Objects also has helpful language
elements that C++ and Java do not offer.
Some specific features of ABAP Objects only exist because of the guaranteed upward
compatibility of older ABAP language elements.
Major differences in comparison to other object-oriented languages are in the
development environment. You can use the ABAP Workbench’s entire range of
functions with ABAP Objects.
2005/Q4
© 2005 SAP AG. All rights reserved.
11
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 extension
of ABAP. All of the extensions, including the old procedural parts, are upwardly
compatible.
Type checks in the object-oriented contexts of ABAP Objects are stricter than those in
the procedural contexts.
In developing ABAP Objects, the ABAP language was cleaned up, in particular in the
object-oriented contexts. This means that obsolete statements lead to syntax errors.
However, it is also advisable to avoid obsolete statements in the purely procedural
environment, as this creates source texts that are safer and more flexible. Nevertheless,
as the language is upwardly compatible, it is not possible to entirely prevent the use
of 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-oriented
context.
It may be useful to mention the great advantages of SAP’s approach: The upward
compatibility saves developers from having to carry out a migration when a new
release is implemented. With a small number of exceptions, the Repository objects
from the first SAP R/3 Basis release can still be used without restrictions in SAP Web
AS 6.20. No competitor can match this.
12
© 2005 SAP AG. All rights reserved.
2005/Q4
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 to
another object, telling it to behave in a certain way, the first object can be seen as a
client and the other as a server.
To 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 to
other objects while requesting services at the same time.
In object-oriented programming, the services are distributed among the objects in
such a way as to avoid redundancies and so that each object offers exactly those
services that are within its area of responsibility. If 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 over
at least two objects: one is responsible for data retrieval and one for output. As long
as the data retrieval object does not change its protocol, its internal implementation
can be altered without any necessary changes to the output object. Alternately, the
data retrieval object could be replaced by a different object, providing that the new
object uses the same protocol. These exchanges can also take place at runtime.
2005/Q4
© 2005 SAP AG. All rights reserved.
13
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Figure 13: Additional Concepts of the Object-Oriented Programming Model
inheritance
Inheritance 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.
Polymorphism
Polymorphism is when instances of different classes respond differently to the
same messages.
Event control
Instead of sending messages directly to specific objects, objects can also trigger
events. Events can be triggered if it is not yet known at the time of development
if and how objects will react.
To summarize, the object-oriented programming model of ABAP Objects has the
following 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
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 easier
when changing between phases.
The features will only become apparent to the participants after they have completed
the relevant lessons. Make sure they understand that the claims made in this course
will be verified by their own experience.
In object-oriented programming, analysis and design decisions have an even greater
effect on implementation than they do in procedural programming. Therefore, you
should already structure and formally standardize the analysis and design phase. You
can use modeling languages to do this.
Figure 14: The Software Development Process
2005/Q4
© 2005 SAP AG. All rights reserved.
15
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Facilitated Discussion
Here you have an opportunity to discuss any open issues that may have arisen. In
most cases, however, we suggest moving swiftly forwards to the more practice-based
lessons.
Discussion Questions
Use the following questions to engage the participants in the discussion. Feel free to
use your own additional questions.
Use the questions as appropriate to find out what participants know.
16
© 2005 SAP AG. All rights reserved.
2005/Q4
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
Unit 1: Introduction to Object-Oriented Programming
Lesson:
15
TAW10_3
Analysis and Design with UML
Lesson Duration: 30 Minutes
Lesson Overview
This lesson will help you to develop an object-oriented solution to a business
application problem, from classifying your objects through to defining the
relationships between them.
We will be using parts of the Unified Modeling Language (UML) modeling standard
as a visual aid.
Lesson Objectives
After completing this lesson, you will be able to:
•
•
•
•
Name the most important diagram types in UML
Create simple class diagrams
Create simple object diagrams
Describe sequence diagrams
In this lesson, it is important to make clear distinctions between modeling
concepts and the related programming concepts. Example: When looking at a
class diagram, we often speak of “inheritance”, although we actually mean a
“generalization/specialization relationship”. This requires strict discipline, especially
from people who are new to the subject matter and may still be somewhat unsure. For
the moment, we are only dealing with modeling.
Business Example
You need to model a business application requirement before it is implemented.
Classification
With 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 very
similar. In other words, they can be described using the same characteristics and
they exhibit the same behaviors.
18
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Analysis and Design with UML
All characteristics and behaviors of these similar objects are now grouped into one
central class. This class is used to describe every object that derives from it. A
class, therefore, is a description of a quantity of objects that are typified by the same
characteristics and the same behaviors.
Figure 15: Classification of Objects
For example, the vehicle “make x, ... series n” is an object of class “car.” This object
is therefore a concrete instance of its class.
Consequently, an object has an identity, a status (number of characteristic instances),
and a behavior. Do not confuse the concepts of identity and status. Identity is an
attribute that distinguishes each object from all other objects of its class. Two different
objects can have identical attribute values and still not be identical.
For example,two coffee cups have the same height and diameter, have the same
handle, and are both white. Although their statuses are therefore completely identical,
they are clearly two different coffee cups.
Literature on the subject of object orientation often speaks of instances. An instance
simply means an object.
Note: In the literal sense of the word instance, the meaning is slightly more
specific. It means a concrete – that is, uniquely identifiable – instance of
a class.
In the following pages, we will make a distinction between instance and object.
2005/Q4
© 2005 SAP AG. All rights reserved.
19
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Figure 16: Classes as Abstraction Forms
In a software context, abstractions are simplified representations of complex
relationships in the real world. A real, existing object is abstracted to dimensions that
are relevant for simulating the required section of the real world.
This example concerns vehicles. Software for a vehicle enthusiast and software for a
scrap merchant contain different abstractions (classes) for these objects. Depending
on the type of abstraction, a class can contain very different aspects of the objects.
In reality, classification is the decisive step. Therefore, it requires extensive
considerations that would go far beyond the framework of this course. This must be
emphasized to the participants. At this point, you will need to keep questions to a
minimum and ask participants to be patient to keep up the necessary pace. As this is a
training situation, a certain starting situation has to be accepted as given.
20
© 2005 SAP AG. All rights reserved.
2005/Q4
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 summarized
here is an absolute prerequisite for successfully proceeding with the following lessons.
Modeling in UML
Unified Modeling Language (UML) is a globally standardized modeling language. It
is used for the specification, construction, visualization, and documentation of models
for software systems and enables uniform communication between users.
UML is an industry standard and was initally developed by the Object Management
Group (OMG) since September 1997. SAP uses UML as a company-wide standard
for object-oriented modeling.
You can find the UML specifications on the OMG homepage at http://www.omg.org
UML describes a number of different diagram types in order to represent different
views of a system. The following three diagram types are of particular significance
in this context:
Class diagrams
Show the classes and the relationships between them, that is, a static view of a
model.
Behavior diagrams
Pay particular attention to the sequence in which the objects relate to each other.
2005/Q4
© 2005 SAP AG. All rights reserved.
21
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Component diagrams
Show the organization and dependencies of components.
Later, we will need to find concrete methods for realizing the first two aspects in the
list in the programming language.
The third aspect, component diagrams, is realized in the Repository object package. In
other words, packages can be used to realize the structure of software components
within SAP Web Application Server (SAP Web AS) according to the structure's
specification 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 of
omitting the attribute and/or the method parts.
Attributes describe the data that can be stored in the objects of a class. They also
determine the status of an object.
Methods describe the functions that an object can perform. They therefore determine
the object's behavior.
22
© 2005 SAP AG. All rights reserved.
2005/Q4
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, the
example with car rental companies and cars could also have been described and
modeled differently. Don't forget to point this out to the participants!
A class diagram describes all static relationships between the classes. There are
two basic forms of static relationships:
Association
In this example, a customer books a car at a rental car company.
Generalization/specialization
In this example, a car, a bus, and a truck are all vehicles.
Note: As mentioned previously, classes can also be shown in class diagrams
with their attributes and methods. Here, these have been left out to improve
clarity.
2005/Q4
© 2005 SAP AG. All rights reserved.
23
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Figure 20: Association
An association describes a semantic relationship between classes. The specific
relationship between objects in these classes is known as an object link. Object links
are the instances of associations.
An association is usually a relationship between different classes (binary association).
However, an association can also be recursive; in this case, the class would have a
relationship with itself. In most cases, recursive associations are used to link two
different objects in one class. The discussion below assumes that the associations
are binary.
Each association has two roles: one for each direction of the association. Each role
can be described with an association name. Each role has a cardinality that shows how
many instances can participate in this relationship. The multiplicity is the number of
participating objects in one class that have a relationship to an object in the other
class. Like all other elements of the model, cardinalities are dependent on the concrete
situation that is being modeled.
24
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Analysis and Design with UML
In this example, you could also require a cardinality of “at least one” to indicate
that only a person who actually makes a booking becomes a customer of the rental
car company. On the other hand, the cardinality “any number” would allow for a
more general definition of a customer.
•
•
•
•
•
An association is represented by a line between the class symbols.
The cardinality (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 detailed
examples of associations to demonstrate the options for modeling with class
diagrams. However, recursive and multiple associations and association classes will
not 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 between
association, aggregation/composition and generalization/specialization. It is important
that the participants have understood this!
Figure 21: Association with Roles: Examples
2005/Q4
© 2005 SAP AG. All rights reserved.
25
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
In the example of multiple associations shown here, role names are used at the end of
the association lines to describe in greater detail the relationships between the classes
involved. A person could appear in the role of employee or of company director
for example.
In the recursive association shown here, the two roles of “child” and “parent” are
similarly defined using role names. Two instances of the LCL_PERSON class thus
have 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 represented
by a special class. The various characteristics of the relationship are described using
the attributes of the association class. A dotted line connects this additional class
to the association line.
26
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Analysis and Design with UML
Figure 23: Aggregation and Composition
Aggregation and composition are specializations of association. They show that an
object consists of other objects or contains other objects (composition part). The
relationship can be described with the words “consists of” or “is a part of”. For
example, a car consists of wheels, among other things.
Aggregation and composition are displayed as a line between two classes that is
labeled with a small rhombus. The rhombus indicates the aggregate, that is, the
composition. Otherwise the notation conventions are the same as for associations.
Composition is a specialization of aggregation. Composition means that the
contained object cannot exist without the aggregate (for example, a car reservation
cannot exist without the car rental). Therefore, the cardinality of the aggregate can
only be exactly one. The lifetime of the individual parts is linked to the lifetime of the
aggregate; parts are created either with or after the aggregate, and they are destroyed
either with or before the aggregate.
In UML notation, composition is denoted by a filled-in rhombus.
2005/Q4
© 2005 SAP AG. All rights reserved.
27
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. This
arrow always points to the more general class. The level of generalization increases in
the direction of the arrow. Trees can be built up using several of these relationships.
28
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Analysis and Design with UML
Figure 25: Object Diagram
An object diagram is a “snapshot” taken during program execution, which describes
the 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 only
useful for representing a complex class diagram.
Here you can use the optional exercise relating to object diagrams to underline the
difference between classes and objects.
The following sequence diagrams complete the unit on modeling. They will not be
mentioned again for the rest of the course!
2005/Q4
© 2005 SAP AG. All rights reserved.
29
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Figure 26: Sequence Diagram
Sequence diagrams are used to display certain processes or situations. Sequence
diagrams focus on the time sequence of the behavior:
•
•
Creating and deleting objects
Exchanging messages between objects
In UML notation, the object lifeline is represented by dotted vertical lines with a box
containing the object name at the top. An 'X' marks the end of the lifeline.
The control focus is shown as a vertical rectangle on the object lifeline. The control
focus shows the object's “active” period:
•
•
An object is active when actions are executed
An object is indirectly active if it is waiting for a subordinate procedure to end
Messages are shown as horizontal arrows between the object lines. The message is
written above the arrow in the form nachricht (parameter)
. There are various ways to represent the reply; in this example, it is shown as a
dotted returning arrow.
You can also include a description of the process and add comments to the object
lifeline as required.
30
© 2005 SAP AG. All rights reserved.
2005/Q4
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 the
request passes on the execution of the request to a delegate.
In this example, the driver (object DRIVER) sends the message GET_FUEL_LEVEL
to the vehicle (object CAR). The receipt of this message causes the car to send a
message to the tank (object TANK) to find out what the tank contains. In other words,
the car delegates this task to the tank. If necessary, the car formats the information
containing the current value of the tank contents before it passes it back to the driver.
2005/Q4
© 2005 SAP AG. All rights reserved.
31
Unit 1: Introduction to Object-Oriented Programming
32
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
TAW10_3
29
Lesson: Analysis and Design with UML
Exercise 1: UML Class Diagrams
Exercise Duration: 30 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Design simple UML class diagrams
•
Model basic object classifications
Business Example
Modeling simple airplane management.
Task 1: Model a UML Class Diagram
You 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 companies
LCL_AIRPLANE
for airplanes (general)
LCL_PASSENGER_PLANE
for passenger planes
LCL_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
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 to
practice (with your help) distinguishing between classes and objects. You should
therefore 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 if
it is correct.
Figure 28: Possible Object Diagrams? (1)
Continued on next page
34
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Analysis and Design with UML
Figure 29: Possible Object Diagrams? (2)
2005/Q4
© 2005 SAP AG. All rights reserved.
35
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Solution 1: UML Class Diagrams
Task 1: Model a UML Class Diagram
You 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 companies
LCL_AIRPLANE
for airplanes (general)
LCL_PASSENGER_PLANE
for passenger planes
LCL_CARGO_PLANE
for cargo planes
a)
2.
Include some appropriate attributes and methods for each class.
a)
3.
Use the model solution as a guide.
The general attributes and methods for the airplanes should be contained in
LCL_AIRPLANE. Continue using model solution as a guide.
Define relationships between your classes.
Choose suitable association types.
a)
A generalization/specialization relationship between LCL_AIRPLANE
and LCL_PASSENGER_PLANE or LCL_CARGO_PLANE seems to
be appropriate. An aggregation should exist between LCL_AIRPLANE
and LCL_CARRIER.
Use the model solution as a guide.
Continued on next page
36
© 2005 SAP AG. All rights reserved.
2005/Q4
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 of
the 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 to
practice (with your help) distinguishing between classes and objects. You should
therefore 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 if
it is correct.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
37
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
TAW10_3
Lesson: Analysis and Design with UML
Figure 32: Possible Object Diagrams? (2)
a)
2005/Q4
The object diagrams numbered 2, 4, 5, 6 and 8 are correct.
© 2005 SAP AG. All rights reserved.
39
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
TAW10_3
Lesson:
36
Lesson: Fundamental Object-Oriented Syntax Elements
Fundamental Object-Oriented Syntax Elements
Lesson Duration: 200 Minutes
Lesson Overview
In this lesson, you will put your models into practice. First, you need to learn the
fundamental object-oriented syntax elements.
You will receive a step-by-step introduction to the definition of local classes and their
basic uses, accompanied by several exercises.
Lesson Objectives
After completing this lesson, you will be able to:
•
•
•
•
Define classes
Generate and delete objects
Access attributes
Call methods
This is one of the most comprehensive lessons. It introduces many new concepts
and syntax elements in quick succession. It is very important that you proceed one
small step at a time.
We highly recommend running all demonstrations in the system. Otherwise, the
participants will not be able to complete the exercises.
The best approach is for you to create an empty program. First, define an empty local
class in the program and then build on it with each step.
However, remember to emphasize that the example you are implementing relates to
the graphics and the presentation in the lesson and that it differs from the program
the participants will use in the accompanying exercises.
This lesson is the key to understanding all further lessons about object-oriented
programming in ABAP Objects. Make sure there are no unanswered questions.
Business Example
You want to the implement classes, objects, and associations of your model in ABAP
Objects.
2005/Q4
© 2005 SAP AG. All rights reserved.
41
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Classes, Attributes, and Methods
The concept of classes is the foundation for all object-oriented thinking. This section
will explain and define the main components of a class.
Figure 33: Example of a Class
This above figure shows a vehicle as an example of a class. Using this example, we
will examine the individual concepts. The node on the left shows that the public
components of the class can be accessed “from outside”. On the other hand, private
attributes of the class should not be accessible “”.
Figure 34: Defining Classes
42
© 2005 SAP AG. All rights reserved.
2005/Q4
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 class
is 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 are
attributes, methods, events, constants, types, and implemented interfaces. Only
methods are implemented in the implementation part.
The CLASS statement cannot be nested, that is, you cannot define a class within a
class.
Note: However, you can define 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 attributes
can be one of three types: elementary, structured, or table-type. They can consist of
local or global data types or reference types.
Examples of attributes for the class LCL_VEHICLE are:
2005/Q4
MAKE
Vehicle make
MODEL
Type or model
SER_NO
Serial number
COLOR
Color
MAX_SEATS
Number of seats
R_MOTOR
Reference to class LCL_MOTOR
© 2005 SAP AG. All rights reserved.
43
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 only
use the LIKE reference for local data objects.
The READ-ONLY addition means that a public attribute that was declared with DATA
can be read from outside, but can only be changed by methods in the same class.
You can currently only use the READ-ONLY addition in the public visibility section
(PUBLIC SECTION) of a class declaration or in an interface definition.
With TYPE REF TO, an attribute can be typed as any reference. This will be
discussed in more detail later.
44
© 2005 SAP AG. All rights reserved.
2005/Q4
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 as
private attributes. The private components of the class cannot be addressed directly
from outside. They are not visible to the outside user.
Note: The friendship concept is an exception to this rule.
Attributes that an outside user can access directly are public attributes. The public
components of a class are sometimes collectively known as the class's interface.
Using the private visibility section is also known as information hiding or
encapsulation. In part, this is to protect the user of a class: Assume that the private
components of a class are changed at some point, 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 user
does not notice the change. Only the internal implementation was changed.
Conversely, if the public components of a class were incompatibly changed, every
outside user would have to take these changes into account. You should therefore use
public attributes very sparingly, or avoid making subsequent incompatible changes to
the public components of your classes altogether.
2005/Q4
© 2005 SAP AG. All rights reserved.
45
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 public
attributes 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 direct
value assignment) is taken into account to satisfy the encapsulation concept:
The signature of the public method clearly establishes which values must or can be
transferred, and what types are to be assigned to them. This relieves the outside
user of all responsibility. The method itself is only responsible for ensuring that all
private attributes are dealt with consistently.
For this example, imagine that the MAKE and MODEL attributes are public. The risk
would be too large, since a user might forget to supply one of the two attributes or
specify two inconsistent attributes. Instead, you could use a public method SET_TYPE
to ensure that values are specified for both attributes. A strict syntax check governs
method calls to check that all obligatory parameters are transferred. It would even
be possible for the method itself to perform a consistency check (to see if a certain
vehicle make produces the chosen model), and to raise an exception if an error occurs.
To save runtime, individual attributes are sometimes defined in the public visibility
section, but they must then be given the addition READ-ONLY.
46
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
Figure 39: Comparison of Instance Attributes with Static Attributes
There are two kinds of attributes:
Instance attributes
Instance attributes are attributes that exist once per object, that is, once per
runtime instance of the class. They are defined with the syntax element DATA.
Static attributes
Static attributes exist once for each class and are visible for all runtime instances
in that class. They are defined with the syntax element CLASS-DATA.
Static attributes usually contain information that applies to all instances, such as:
•
•
•
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 the
CLASS-DATA syntax element). In ABAP Objects, as in C++ and Java, the official
term is static attribute.
2005/Q4
© 2005 SAP AG. All rights reserved.
47
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 related
to the other program elements in the memory: It exists only once (in the loaded class)
regardless of the number of instances of LCL_VEHICLE. Therefore, you can say that
instances share their common attributes.
Caution: Here, an integer data object is defined in order to count the
instances. It is not possible to find out the number of created instances from
the system.
48
© 2005 SAP AG. All rights reserved.
2005/Q4
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 of
other elements.
Methods have a signature (interface parameters and exceptions) that enables them
to receive values when they are called and pass values back to the calling program.
Methods can have any number of IMPORTING, EXPORTING, and CHANGING
parameters. All parameters can be passed by value or reference.
One method return value can be defined using the RETURN parameter. It must
always be transferred as a value. In this case, you cannot then define the EXPORTING
and CHANGING parameters. You can also use the RETURNING parameter to define
functional methods. This will be discussed in more detail later.
All input parameters (IMPORTING and CHANGING parameters) can be defined as
optional parameters in the declaration using the OPTIONAL or DEFAULT additions.
These parameters then do not necessarily have to be transferred when the object
is called. If you use the OPTIONAL addition, the parameter remains initialized
according to type, whereas the DEFAULT addition allows you to enter a start value.
Like function modules, methods also support the return value SY-SUBRC, but only
if the signature exceptions were defined using EXCEPTIONS. As of SAP Web
AS 6.10, the RAISING addition can be used in its place to propagate class-based
exceptions. The caller then handles these class-based exceptions without evaluating
the SY-SUBRC return value.
2005/Q4
© 2005 SAP AG. All rights reserved.
49
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 the
methods are called from outside the class or only from within the class. Thus, private
methods only serve the purpose of internal modularization.
Figure 43: Accessing Private Methods
50
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
You define private methods in the PRIVATE SECTION of a class. You define public
attributes in the PUBLIC SECTION.
It is not possible to directly access private methods from outside. However, a private
method can be called by a public method.
In this example, INIT_TYPE is a private method that is called by the public method
SET_TYPE. The instruction to initialize the attributes could exist in other contexts as
well, so the definition of this private “auxiliary method” is useful.
Note: This is an introductory example. Later, you will learn more
programming techniques for evaluating formal parameters.
Namespace: Within a class, attribute names, method names, event names, constant
names, type names, and alias names all share the same namespace. As with
subroutines and function modules, there is an additional local namespace within
methods. This means that local declarations override those for the whole class.
Figure 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 components
can be accessed applies in the implementation part. This means that static methods
do not need instances, that is, they can be accessed directly through the class. This
will be discussed in more detail later. The methods are defined using the syntax
keyword CLASS-METHODS.
In this example, only the static attribute N_O_VEHICLES can be accessed within the
static method GET_N_O_VEHICLES. All other attributes of the class are instance
attributes and can only appear within instance methods.
2005/Q4
© 2005 SAP AG. All rights reserved.
51
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Technical literature often refers to static methods as “class methods” (compare with
the CLASS-METHODS syntax element). In ABAP Objects, as in C++ and Java, the
official 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 below
it. 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 for
visibility. Representation of visibility characteristics is optional and is normally only
used for models that are close to implementation.
Static components are marked with an underscore.
The method signature is represented as follows (optional):
•
•
52
The input and output parameters and the parameters to be changed are shown in
parentheses 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 the
event parameter, separated by a colon.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
Your demonstration program should now resemble the executable program
SAPBC401_VEHICLE_MAIN_A.
This is a good time to include the first exercise of this lesson.
Objects: Instances of Classes
You could use classes to write complete applications by only using static components.
However, the reasoning behind object-oriented programming is to create and work
with runtime instances of classes.
Figure 46: Overview of Class Instances
A class contains the generic description of an object and describes all characteristics
that all objects of the class have in common. During the program runtime, the class
is used to create discrete objects (instances) in the memory. This process is called
instantiation. If this is the first time the class is accessed, the class is also loaded
into the memory.
2005/Q4
© 2005 SAP AG. All rights reserved.
53
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Which values may be written into which attributes is irrelevant. Technically, the
object has an ID (in this case, 5) which is not accessible, however.
Example: Instantiation of class LCL_VEHICLE creates a vehicle object. The private
attributes still contain the technical initial values.
Figure 47: Definition of Reference Variables
DATA r_vehicle1 TYPE REF TO lcl_vehicle is used to define
a reference variable, which is thereby typed as a pointer to objects of type
lcl_vehicle. The null reference is the technical initial value of a reference
variable. (The pointer is pointing to nothing.)
54
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
Figure 48: Creating Objects
The statement CREATE OBJECT creates an object in the memory. Its attribute values
are then either initial or assigned according to the VALUE specification.
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
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Sometimes, experienced participants suggest using field symbols for this. If this
happens, it is a good opportunity to clarify the principal differences again.
It is important that you complete and discuss the exercises at the relevant stages
of 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, and
the successful completion of the exercises, are very important for the remainder of
the course!
Figure 50: Garbage Collector
Independent references are references that have not been defined within a class. The
Garbage Collector is a system routine that is automatically started whenever the
runtime system does not have more important tasks to carry out.
In this example, the reference to object (2)LCL_OBJECT is initialized. Afterwards,
no references point to this object. Therefore, the Garbage Collector deletes it.
Consequently, no references point to object (4)LCL_OBJECT anymore, so it is
deleted as well.
You can use the logical query IF r_obj IS INITIAL to determine whether
r_obj contains the null reference, in other words whether it does not point to any
object.
56
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
Do not spend more than 60 seconds discussing the Garbage Collector. Application
developers cannot influence it. Developers also do not have to work any differently
depending on whether the Garbage Collector is running.
Some experienced participants refuse to accept that they can no longer have access to
objects if those objects' addresses have been lost.
Caution: The query for IS BOUND would also be possible here, but only makes a
difference for data references. If you encounter a question on this, the answer is that in
the 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 to
this preview!
2005/Q4
© 2005 SAP AG. All rights reserved.
57
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
If you want to keep several objects from the same class in your program, you can
define an internal table that contains one column with the object references for this
class. These objects can be administered in the internal table with the usual statements
for internal tables such as APPEND, READ or LOOP.
To use logical conditions, the pseudo-component TABLE_LINE must be used when
you use single-column internal tables. To do this, however, the relevant attributes
need to be public.
Figure 52: Example of Aggregation
During an aggregation, the WHEEL objects must be able to exist on their own, in
other words independently of the vehicle. Independent references must therefore still
exist 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 in
this example, regardless of the existence of an object in the class LCL_VEHICLE.
References are transferred to objects in class LCL_VEHICLE to create the desired
association.
58
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
Your demonstration program should now resemble the executable program
SAPBC401_VEHICLE_MAIN_B.
Here, the next exercise would be suitable for the airplane objects referenced in the
internal table.
Accessing Attributes and Methods
In this section you learn how you can use classes and their instances. That is, you will
learn 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 object
providing the services. This message names the operation to be executed. The
implementation of this operation is known as a method. For the sake of simplicity,
method will henceforth be used as a synonym for operation and message. Therefore,
an object's behavior is determined by its method. A method's signature can also be
used to exchange values.
2005/Q4
© 2005 SAP AG. All rights reserved.
59
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
The example shows the shorter syntax for method calls (supported as of SAP Web
AS 6.10) in which the CALL-METHOD prefix is omitted.
Figure 54: Calling Instance Methods: Syntax
Instance methods are called with
CALL METHOD ref->method_name .... When calling an instance method
from within another instance method, you can omit the instance name ref. The
method is automatically executed for the current object.
A shorter syntax is also supported as of SAP Web AS 6.10. In this case, CALL
METHOD is omitted and the parameters are listed in parentheses. There must be no
space 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 the
actual parameter in the parentheses without any other additions. When you call a
method that only has import parameters, you can omit the EXPORTING addition.
The RECEIVING, IMPORTING, and CHANGING parameters are mutually
exclusive. Please see the section about functional methods for more details.
Otherwise, the same rules apply here as they do for calling a function module.
60
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
It is not worth making a big deal of the shorter syntax. It was introduced to
make ABAP Objects syntax resemble C++ and Java even more closely. However,
participants will also have to maintain older source code, so they need to know the
explicit syntax as well.
Figure 55: Calling Static Methods - Syntax
Static methods (also referred to as class methods) are called using
CALL METHOD classname=>method_name ....
Like static attributes, static methods are addressed with their class name, since they
do not need instances.
As with instance methods, when you are calling a static method from within the class,
you can omit the classname. Otherwise, the same rules apply here as for calling an
instance method.
It is time to do the exercise for the method calls. It is better to do the sub-exercise
on the functional methods separately, in other words afterwards. Otherwise, the
participants are bound to become confused and mix up all of the techniques.
2005/Q4
© 2005 SAP AG. All rights reserved.
61
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 method
calls. The former are possible from the beginning (that is, as of SAP R/3 4.6A). The
latter are only possible as of SAP Web AS 6.10.
62
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
The exercise step that handles functional methods should be performed on its own, in
other words, as a separate step.
Figure 57: Functional Methods: Examples
In the first of these examples, two calls of functional instance methods represent
the two addends of an addition.
The second example shows the call of a functional static method in the short form:
The NUMBER data object is the actual parameter for the method's RETURNING
parameter. The detailed syntax is as follows:
DATA number TYPE i.
...
CALL METHOD lcl_vehicle=>get_n_o_vehicles
RECEIVING re_count = number.
2005/Q4
© 2005 SAP AG. All rights reserved.
63
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. Instance
attributes are accessed with ref->instance_attribute.
Your demonstration program should now resemble the executable program
SAPBC401_VEHICLE_MAIN_C.
Constructors
There are two types of methods in ABAP Objects. They are generally not called
explicitly with CALL METHOD (or the relevant short form), rather they are called
implicitly. Constructors are the first type of method.
Some participants who have experiences with other object-oriented languages may
struggle at this point. In some of these languages, the constructor concept is used
differently 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
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 named
CONSTRUCTOR. This abbreviated term actually means the instance constructor.
The constructor is automatically called at runtime with the CREATE OBJECT
statement. Always consider the following points when you define constructors:
•
•
•
•
•
Each class can have no more than one (instance) constructor.
The constructor must be defined in the public area.
The constructor's signature can only have importing parameters and exceptions.
When exceptions are raised in the constructor, instances are not created, so
no main memory space is occupied.
Except for one exceptional case, you cannot normally call the constructor
explicitly.
Note: There is no destructor in ABAP Objects. That is, there is no instance
method that is automatically called from the memory immediately before
the object is deleted.
(The corresponding comments in the SAP Library and the menu paths outside
of the ABAP Workbench are only contained in internal system calls.)
2005/Q4
© 2005 SAP AG. All rights reserved.
65
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Unfortunately, they are not dynamically hidden. If they were, we would not need to
deal 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 program
SAPBC401_VEHICLE_MAIN_D.
66
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
Now you can perform the appropriate exercise for the constructors in this lesson. The
exercise 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 named
CLASS_CONSTRUCTOR. It is executed no more than once per program (and class).
The static constructor is called automatically before the class is first accessed, but
before any of the following actions are executed for the first time:
•
•
•
•
Creating an instance of this class (CREATE OBJECT)
Accessing a static attribute of this class
Calling a static method of this class
Registering an event handler method for an event in this class
Always consider the following points when you define static constructors:
•
•
•
•
2005/Q4
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 SAP AG. All rights reserved.
67
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
The exercise for the static constructor should be done here! It also has the advantage
that the participants finally get to grips with SQL accesses and learn that nothing
changes in terms of their SQL knowledge: How comforting!
You could make a careful comparison with the LOAD-OF-PROGRAM ABAP event
for function groups.
Self-Reference
In some cases, you need to have a self-reference available. In ABAP Objects,
self-references are always predefined, but they are only useful in certain contexts and
only there are they syntactically available.
Figure 62: Self-Reference
You can address an object itself by using the predefined reference variable ME within
its instance methods . Generally, you do not need to use the prefix
me-> in such cases, but you may use it to improve readability.
68
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
However, it is required when you want to show a distinction between local data
objects and instance attributes with the same name.
The following case shows another important use: When a foreign method is called,
a client object is to export a reference to itself. ME can then be used as an actual
parameter with EXPORTING or CHANGING.
Your demonstration program should now resemble the executable program
SAPBC401_VEHICLE_MAIN_E.
This is a good time to include the fifth exercise of this lesson. You MUST complete
this 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 exercise
in this lesson!
2005/Q4
© 2005 SAP AG. All rights reserved.
69
Unit 1: Introduction to Object-Oriented Programming
70
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
TAW10_3
63
Lesson: Fundamental Object-Oriented Syntax Elements
Exercise 2: Local Classes
Exercise Duration: 45 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Declare local classes
•
Define attributes
•
Define and implement methods
Business Example
You are a developer for an airline corporation that owns several airline carriers. Start
to develop an object-oriented program that can manage the airline carriers and their
airlines.
Task 1:
Create a new program.
1.
Create an executable program without a TOP include.
Program name: ZBC401_##_MAIN
(where ## is your two-digit group number). )
2.
Create an include program and include it in your ZBC401_##_MAIN main
program.
Program name: ZBC401_##_AIRPLANE
(where ## is your two-digit group number). )
Task 2:
Declare a class for airplanes.
1.
Within your include program, declare the local class LCL_AIRPLANE.
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
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
71
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 private
instance attributes.
Your signature should consist of two suitable import parameters that are defined
as 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 displaying
the private instance attributes.
Implement the method in such a way that the values of the two instance attributes
are output as an ABAP list. You can also output icons if the ICON type group is
loaded.
Hint: To do this, use the statement
TYPE-POOLS icon.
.
Note: Strictly speaking, to adhere to the delegation principle, the reading
of the attribute values and their output should not be implemented in the
same method. However, do it here anyway because of time constraints.
5.
Define the public static method DISPLAY_N_O_AIRPLANES to display the
private static attribute.
Implement the method in such a way that the value of the static attributes is
output in the ABAP list.
Note: So far, your class does not have a mechanism that ensures that the
instance counter is increased each time an object is created. It is up to
you to decide if you want to leave this out for now, or if you want to
temporarily control the incrementation using the SET_ATTRIBUTES
method.
72
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
Solution 2: Local Classes
Task 1:
Create a new program.
1.
Create an executable program without a TOP include.
Program name: ZBC401_##_MAIN
(where ## is your two-digit group number). )
a)
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
Model solution: SAPBC401_AIRS_MAIN_A
2.
Create an include program and include it in your ZBC401_##_MAIN main
program.
Program name: ZBC401_##_AIRPLANE
(where ## is your two-digit group number). )
a)
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
Model solution: SAPBC401_AIRS_A
b)
See the source code extract from the model solution.
Task 2:
Declare a class for airplanes.
1.
Within your include program, declare the local class LCL_AIRPLANE.
a)
2.
See the source code extract from the model solution.
Define the two private instance attributes
NAME (name of airplane), data type STRING
PLANETYPE (type of airplane), data type SAPLANE-PLANETYPE
and the private static attribute
N_O_AIRPLANES (instance counter), data type I.
a)
See the source code extract from the model solution.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
73
Unit 1: Introduction to Object-Oriented Programming
3.
TAW10_3
Define the public instance method SET_ATTRIBUTES for setting the private
instance attributes.
Your signature should consist of two suitable import parameters that are defined
as compatible with the two attributes.
Implement the method in such a way that the two instance attributes are set.
a)
4.
See the source code extract from the model solution.
Define the public instance method DISPLAY_ATTRIBUTES for displaying
the private instance attributes.
Implement the method in such a way that the values of the two instance attributes
are output as an ABAP list. You can also output icons if the ICON type group is
loaded.
Hint: To do this, use the statement
TYPE-POOLS icon.
.
Note: Strictly speaking, to adhere to the delegation principle, the reading
of the attribute values and their output should not be implemented in the
same method. However, do it here anyway because of time constraints.
a)
5.
See the source code extract from the model solution.
Define the public static method DISPLAY_N_O_AIRPLANES to display the
private static attribute.
Implement the method in such a way that the value of the static attributes is
output in the ABAP list.
Note: So far, your class does not have a mechanism that ensures that the
instance counter is increased each time an object is created. It is up to
you to decide if you want to leave this out for now, or if you want to
temporarily control the incrementation using the SET_ATTRIBUTES
method.
a)
See the source code extract from the model solution.
Result
Source code extract:
Continued on next page
74
© 2005 SAP AG. All rights reserved.
2005/Q4
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
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.
"set_attributes
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.
"display_attributes
ENDMETHOD.
METHOD display_n_o_airplanes.
WRITE: /, / ’Total number of planes’(ca1),
AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
ENDMETHOD.
ENDCLASS.
76
"display_n_o_airplanes
"lcl_airplane IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
69
Lesson: Fundamental Object-Oriented Syntax Elements
Exercise 3: Objects
Exercise Duration: 20 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Define reference variables
•
Instantiate objects
•
Process object references using an internal table
Business Example
Create instances of your airplane type and ensure that their addresses are not lost.
Task 1:
Define reference variables.
1.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise.
Define a reference variable for the instances of your class LCL_AIRPLANE.
2.
Define an internal table for buffering references to instances of the class
LCL_AIRPLANE.
Task 2:
Create airplane objects.
2005/Q4
1.
Create several instances of the local class LCL_AIRPLANE and buffer their
references into the internal table.
2.
Follow the execution of the program in the ABAP Debugger.
© 2005 SAP AG. All rights reserved.
77
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Solution 3: Objects
Task 1:
Define reference variables.
1.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise.
Define a reference variable for the instances of your class LCL_AIRPLANE.
2.
a)
Model solution: SAPBC401_AIRS_MAIN_B
b)
See the source code extract from the model solution.
Define an internal table for buffering references to instances of the class
LCL_AIRPLANE.
a)
See the source code extract from the model solution.
Task 2:
Create airplane objects.
1.
Create several instances of the local class LCL_AIRPLANE and buffer their
references into the internal table.
a)
See the source code extract from the model solution.
Continued on next page
78
© 2005 SAP AG. All rights reserved.
2005/Q4
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 to
the SAP Library.
Result
Source code extract:
SAPBC401_AIRS_MAIN_B
REPORT
sapbc401_airs_main_b.
TYPE-POOLS icon.
INCLUDE sapbc401_airs_a.
DATA: r_plane TYPE REF TO lcl_airplane,
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION.
*##############################
CREATE OBJECT r_plane.
APPEND r_plane TO plane_list.
CREATE OBJECT r_plane.
APPEND r_plane TO plane_list.
CREATE OBJECT r_plane.
APPEND r_plane TO plane_list.
2005/Q4
© 2005 SAP AG. All rights reserved.
79
Unit 1: Introduction to Object-Oriented Programming
80
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
TAW10_3
73
Lesson: Fundamental Object-Oriented Syntax Elements
Exercise 4: Method Calls
Exercise Duration: 45 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Call non-functional methods
•
Define functional methods
•
Call functional methods
Business Example
You need to fill the attributes of the “empty” airplane objects with suitable values.
Task 1:
Call the methods of your class.
1.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise.
Call the static method DISPLAY_N_O_AIRPLANES twice: Once before and
once after the instantiations.
Caution: For reasons explained in the first exercise, you may not notice
any effects at the moment.
2.
Use the SET_ATTRIBUTES method to set the attributes for all objects already
created. Choose a unique name for the airplanes. When you are assigning
airplane types, use the information in the SAPLANE table as a guide (for
example, '747-400'). Also use at least one invalid airplane type.
3.
Display the attribute values in the ABAP list using the DISPLAY_ATTRIBUTES
method.
Task 2:
Add a functional method to your class.
1.
In your class, define the public static functional method GET_N_O_AIRPLANES. The signature must only consist of the result parameter RE_COUNT,
which must be a whole number.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
81
Unit 1: Introduction to Object-Oriented Programming
2.
82
TAW10_3
Call this method instead of DISPLAY_N_O_AIRPLANES and output the value
in the ABAP list.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
Solution 4: Method Calls
Task 1:
Call the methods of your class.
1.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise.
Call the static method DISPLAY_N_O_AIRPLANES twice: Once before and
once after the instantiations.
Caution: For reasons explained in the first exercise, you may not notice
any effects at the moment.
2.
a)
Model solution: SAPBC401_AIRS_MAIN_C
b)
See the source code extract from the model solution.
Use the SET_ATTRIBUTES method to set the attributes for all objects already
created. Choose a unique name for the airplanes. When you are assigning
airplane types, use the information in the SAPLANE table as a guide (for
example, '747-400'). Also use at least one invalid airplane type.
a)
3.
See the source code extract from the model solution.
Display the attribute values in the ABAP list using the DISPLAY_ATTRIBUTES
method.
a)
See the source code extract from the model solution.
Task 2:
Add a functional method to your class.
1.
In your class, define the public static functional method GET_N_O_AIRPLANES. The signature must only consist of the result parameter RE_COUNT,
which must be a whole number.
a)
2.
See the source code extract from the model solution
Call this method instead of DISPLAY_N_O_AIRPLANES and output the value
in 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
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Result
Source 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
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
*&
Show functional static method get_n_o_airplanes
SAPBC401_AIRS_C
*
*
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
*
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
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.
ENDCLASS.
86
"get_n_o_airplanes
"lcl_airplane IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
79
Lesson: Fundamental Object-Oriented Syntax Elements
Exercise 5: Constructors
Exercise Duration: 45 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Define and implement instance constructors
•
Create instances of classes that contain an instance constructor
Business Example
Make your program more realistic: The airplane objects receive their attributes as
soon as they are created.
Task 1:
Define an instance constructor.
1.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise. (where ## is your two-digit group number). )
Define a reference variable with a suitable signature for the instances of your
class LCL_AIRPLANE.
Implement it so that the two instance attributes are set and the instance counter
N_O_AIRPLANES is increased by one.
2.
If you previously used the SET_ATTRIBUTES method to increase the instance
counter, remove the relevant statement from the method now.
Task 2:
Create airplane objects.
1.
Your CREATE OBJECT statements from the previous exercise should now be
syntactically incorrect. Adapt and correct them.
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
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_PLANETYPES
internal table is filled with all rows from the SAPLANE database table. You can
use the ARRAY FETCH technique for this purpose.
3.
88
Check that the static constructor is called correctly and that the internal table
is filled in the main program. Where is the static constructor called in the
main program?
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
Solution 5: Constructors
Task 1:
Define an instance constructor.
1.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise. (where ## is your two-digit group number). )
Define a reference variable with a suitable signature for the instances of your
class LCL_AIRPLANE.
Implement it so that the two instance attributes are set and the instance counter
N_O_AIRPLANES is increased by one.
2.
a)
Model solution: SAPBC401_AIRS_MAIN_D
b)
See the source code extract from the model solution.
If you previously used the SET_ATTRIBUTES method to increase the instance
counter, remove the relevant statement from the method now.
a)
See the source code extract from the model solution.
Task 2:
Create airplane objects.
1.
Your CREATE OBJECT statements from the previous exercise should now be
syntactically incorrect. Adapt and correct them.
a)
2.
If necessary, remove the calls of the SET_ATTRIBUTES method.
a)
3.
See the source code extract from the model solution.
See the source code extract from the model solution.
Follow the execution of the program in the ABAP Debugger.
a)
Carry out this step in the usual manner. Additional information on the
ABAP 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
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Use the PLANETYPE field as a key for the internal table.
a)
2.
See the source code extract from the model solution.
Define the static constructor in the LCL_AIRPLANE class.
Implement the constructor in such a way that the LIST_OF_PLANETYPES
internal table is filled with all rows from the SAPLANE database table. You can
use the ARRAY FETCH technique for this purpose.
a)
3.
See the source code extract from the model solution.
Check that the static constructor is called correctly and that the internal table is
filled in the main program. Where is the static constructor called in the main
program?
a)
Before the class is first accessed (before DISPLAY_N_O_AIRPLANES in
this case).
Result
Source 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
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
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.
"constructor
ENDMETHOD.
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.
ENDCLASS.
92
"display_n_o_airplanes
"lcl_airplane IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
85
Lesson: Fundamental Object-Oriented Syntax Elements
Exercise 6: Private Methods
Exercise Duration: 45 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Use the delegation principle
•
Structure and call private methods
•
Use the keyword ME
Business Example
You 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 from
the previous exercise.
Within your LCL_AIRPLANE class, define the private static method
GET_TECHNICAL_ATTRIBUTES.
The signature must consist of the import parameter for the airplane type and the
two export parameters for weight and tank capacity. Use the transparent table
SAPLANE as a guide for specifying the types of these formal parameters.
2.
Implement the method in such a way that the values for the export
parameters can be determined by single-record access to the internal table
LIST_OF_PLANETYPES. Program a single-record access that works
efficiently!
Note: If the table does not contain any values for the airplane type, it
should be ignored for the time being.
Strictly speaking, the correct unit of measure should also be selected
and exported. However, time constraints mean that you do not need
to do it in this exercise.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
93
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 main
program.
2.
Call the method GET_TECHNICAL_ATTRIBUTES from the method
DISPLAY_ATTRIBUTES to obtain additional technical data. Enter this
additional 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 from
the previous exercise.
If reading the airplane type in the method GET_TECHNICAL_ATTRIBUTES
is not successful (SY-SUBRC <> 0), the exception WRONG_PLANETYPE
should 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 Releases
for function modules and should be familiar.
At a later stage in this course, we will replace this older technique with a
modern technique of exception handling using exception classes.
2.
When you call the private method GET_TECHNICAL_ATTRIBUTES in the
calling method DISPLAY_ATTRIBUTES, this exception must now be declared
using the EXCEPTIONS addition.
Continued on next page
94
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
If an exception occurs in GET_TECHNICAL_ATTRIBUTES, you can check
this using the SY-SUBRC in the calling method. (Refer to the normal procedure
for function modules.)
In this exercise, the use of an incorrect airplane type when SY-SUBRC <> 0
should simply be documented with a WRITE statement.
2005/Q4
© 2005 SAP AG. All rights reserved.
95
Unit 1: Introduction to Object-Oriented Programming
TAW10_3
Solution 6: Private Methods
Task 1:
Declare another method.
1.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise.
Within your LCL_AIRPLANE class, define the private static method
GET_TECHNICAL_ATTRIBUTES.
The signature must consist of the import parameter for the airplane type and the
two export parameters for weight and tank capacity. Use the transparent table
SAPLANE as a guide for specifying the types of these formal parameters.
2.
a)
Model solution: SAPBC401_AIRS_MAIN_E
b)
See the source code extract from the model solution.
Implement the method in such a way that the values for the export
parameters can be determined by single-record access to the internal table
LIST_OF_PLANETYPES. Program a single-record access that works
efficiently!
Note: If the table does not contain any values for the airplane type, it
should be ignored for the time being.
Strictly speaking, the correct unit of measure should also be selected
and exported. However, time constraints mean that you do not need
to do it in this exercise.
a)
See the source code extract from the model solution.
Task 2:
Call the method.
1.
If possible, call the method GET_TECHNICAL_ATTRIBUTES from the main
program.
a)
If it is a private method, you cannot call it from the main program. This is
only possible for public methods.
Continued on next page
96
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
2.
Call the method GET_TECHNICAL_ATTRIBUTES from the method
DISPLAY_ATTRIBUTES to obtain additional technical data. Enter this
additional data in the calling method.
a)
3.
Follow the execution of the program in the ABAP Debugger.
a)
4.
See the source code extract from the model solution.
Carry out this step in the usual manner. Additional information on the
ABAP Debugger is available in the SAP Library.
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 an
import parameter. This method then accesses the class attribute
LIST_OF_PLANETYPES with ME->PLANETYPE.
•
Do not use the method at all
In the method display_attributes, you can access the class attribute
LIST_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 from
the previous exercise.
If reading the airplane type in the method GET_TECHNICAL_ATTRIBUTES
is not successful (SY-SUBRC <> 0), the exception WRONG_PLANETYPE
should 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 Releases
for function modules and should be familiar.
At a later stage in this course, we will replace this older technique with a
modern 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
Unit 1: Introduction to Object-Oriented Programming
2.
TAW10_3
When you call the private method GET_TECHNICAL_ATTRIBUTES in the
calling method DISPLAY_ATTRIBUTES, this exception must now be declared
using the EXCEPTIONS addition.
If an exception occurs in GET_TECHNICAL_ATTRIBUTES, you can check
this using the SY-SUBRC in the calling method. (Refer to the normal procedure
for function modules.)
In this exercise, the use of an incorrect airplane type when SY-SUBRC <> 0
should simply be documented with a WRITE statement.
a)
Refer to the model solution.
Result
Source 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
TAW10_3
Lesson: Fundamental Object-Oriented Syntax Elements
IMPORTING im_type
TYPE saplane-planetype
EXPORTING ex_weight
ex_tankcap
TYPE s_plan_wei
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
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.
ENDCLASS.
100
"get_technical_attributes
"lcl_airplane IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
2005/Q4
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 Information
Further information about this subject is available in the SAP Library and the ABAP
keyword documentation for the individual statements.
2005/Q4
© 2005 SAP AG. All rights reserved.
101
Unit Summary
TAW10_3
Unit Summary
You should now be able to:
•
Explain the differences between procedural and object-oriented programming
models
•
List the advantages of the object-oriented programming model
•
Name the most important diagram types in UML
•
Create 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
TAW10_3
95
Test Your Knowledge
Test Your Knowledge
1.
The object-oriented programming model was developed considerably later than
the procedural one. It offers more options for solving problems that previously
could not be solved with purely procedural programming languages.
Determine whether this statement is true or false.
□
□
2005/Q4
True
False
2.
What does multiple instantiation mean?
3.
What does encapsulation mean?
4.
In ABAP Objects, what is meant by the term class?
5.
What is the difference between a class's static components and its instance
components?
© 2005 SAP AG. All rights reserved.
103
Test Your Knowledge
104
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?
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
97
Test Your Knowledge
Answers
1.
The object-oriented programming model was developed considerably later than
the procedural one. It offers more options for solving problems that previously
could not be solved with purely procedural programming languages.
Answer: False
Refer to the relevant section of the lesson.
2.
What does multiple instantiation mean?
Answer: The ability to create and manage any number of runtime instances for
each program context
Refer to the relevant section of the lesson.
3.
What does encapsulation mean?
Answer: Gathering data and functions into reusable units from which users can
only call certain functions and cannot access the data directly.
Refer to the relevant section of the lesson.
4.
In ABAP Objects, what is meant by the term class?
Answer: A class is the technical description of identical objects. It can
contain attribute and method definitions and can generally also contain the
implementations of methods.
Refer to the relevant section of the lesson
5.
What is the difference between a class's static components and its instance
components?
Answer: You must access static components through the class. There are static
components for each program and class no more than once in the memory. An
object must be instantiated to access them.
You must access instance components via the objects of this class. Any number
of 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
Test Your Knowledge
6.
TAW10_3
In ABAP Objects, what is meant by the term constructor?
Answer: A class's constructor is a special method and is always named
CONSTRUCTOR. It is normally only called by the runtime system, whenever
an object of this class is created using CREATE OBJECT. Therefore, it is
referred to more specifically as the instance constructor.
Refer to the relevant section of the lesson.
7.
You are defining a class. Must you always also define a constructor?
Answer: No.
Refer to the relevant section of the lesson.
106
© 2005 SAP AG. All rights reserved.
2005/Q4
Unit 2
Object-Oriented Concepts and
Programming Techniques
99
For more information, see the introductory instructor notes in the lesson.
Unit Overview
In this unit you will learn about the fundamental concepts and programming
techniques of ABAP Objects and other object-oriented languages such as Java or C++.
Unit Objectives
After completing this unit, you will be able to:
•
•
•
•
•
•
•
•
•
•
•
•
•
•
2005/Q4
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 SAP AG. All rights reserved.
107
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 Contents
Lesson: Inheritance and Casting ................................................. 109
Exercise 7: Class Hierarchies ................................................ 131
Exercise 8: Polymorphism .................................................... 141
Exercise 9: Aggregation and Generic Calls................................. 145
Lesson: Interfaces and Casting ................................................... 153
Exercise 10: Interface Implementation ...................................... 171
Exercise 11: Aggregation, Generic Calls, and Polymorphism ............ 185
Lesson: Events...................................................................... 193
Exercise 12: Events in Superclasses ........................................ 203
Exercise 13: (Optional): Events in Interfaces .............................. 217
108
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson:
101
Lesson: Inheritance and Casting
Inheritance and Casting
Lesson Duration: 160 Minutes
Lesson Overview
In this lesson, you will learn how to create class hierarchies using ABAP Objects.
The first step will be to program the relevant relationship types that were devised
in the modeling process. Then you will learn to identify a number of interesting
programming possibilities provided by inheritance.
Lesson Objectives
After completing this lesson, you will be able to:
•
•
•
•
•
•
Define inheritance relationships between classes
Redefine methods
Create narrowing cast assignments
Create widening cast assignments
Explain the concept of polymorphism with reference to inheritance
Use cast assignments with inheritance to make generic calls
The last part of this lesson is definitely the most important: Inheritance must
always be used correctly. Inheritance relationships should not be defined between
semantically unrelated classes simply to achieve technical advantages (such as
centralized maintenance, polymorphism, extensibility). Instead, inheritance must
always derive from a generalization/specialization relationship that was recognized
as early as the modeling phase. This will allow you to benefit from the enhanced
programming 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 in
the course to refer to the parameters of a method. The term interface is used to mean
several different things. Avoid using it as of the following lesson to avoid confusion.
Business Example
You want to implement generalization/specialization relationships from your model
in ABAP Objects.
2005/Q4
© 2005 SAP AG. All rights reserved.
109
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
Creating Generalization/Specialization Relationships
Using Inheritance
Specialization (UML) is a relationship in which one class (the subclass) inherits all the
main characteristics of another class (the superclass). The subclass can also add new
components (attributes, methods, and so on) and replace the implementations with
inherited methods. When the implantation is replaced, the method name in the UML
diagram is renamed within the subclass.
Figure 63: Example of Generalization/Specialization
Specialization is an implementation relationship that emphasizes similarities
between the classes. In the example above, the similarities of classes LCL_CAR,
LCL_TRUCK, and LCL_BUS are extracted to a superclass: LCL_VEHICLE.
Therefore, the components they have in common are only defined and implemented in
the superclass. They also exist in all subclasses.
Specialization is often described as an “is a” relationship. In this example, you would
say “A truck is a (specific) vehicle.”
Reversing the point of view is referred to as generalization.
110
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
Figure 64: Characteristics of Generalization/Specialization
Generalization/specialization, if used properly, provides a significantly better structure
for your software because commonly used elements only need to be stored once
in a central location (in the superclass) and are then automatically available to all
subclasses. 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 whether
the inherited components from the superclass are sufficient for the subclass or if
they need to be extended. Generalization/specialization provides very strong links
between the superclass and the subclass.
When you develop additional subclasses, you often have to adapt the superclass as
well. Therefore, the creation of a subclass sometimes leads to additional requirements
for the superclass, for example, when a subclass requires certain protected components
or when the details of a superclass’s implementation are required to change the method
implementations in subclasses. The developer of a (super)class cannot normally
predict everything that the subclasses will later require from the superclass.
2005/Q4
© 2005 SAP AG. All rights reserved.
111
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 the
INHERITING FROM addition, followed by the superclass that is directly above the
subclass. Inheritance hierarchies of varying complexity arise when this superclass
inherits from another superclass above it. In contrast, there is no multiple inheritance
in ABAP Objects that is, only one superclass can be specified directly above a class.
However, you can use interfaces in ABAP Objects to simulate multiple inheritance.
Inheritance should be used to implement generalization and specialization
relationships. A superclass is a generalization of its subclasses. The subclasses are
in turn different specializations of their superclass. Thus, only additions or changes
are permitted in ABAP Objects, which means that you can never remove anything
from a superclass in a subclass.
Inheritance is a one-sided relationship. In other words, subclasses recognize their
direct superclasses but (super)classes do not recognize their subclasses. In the above
example, the subclass also contains the ESTIMATE_FUEL method. The subclass
also defines the GET_CARGO method.
112
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
Figure 66: Redefining Methods
Redefinition is when the implementation of an inherited instance method is changed
for the subclass without changing the signature. At the same time, the visibility
section for the superclass must remain the same. Redefinition is not possible without
the PRIVATE SECTION.
When you use the REDEFINITION addition, you must specify a new implementation
part for the inherited method. As the signature may not be changed, you do not need
to define the method parameters and exceptions again.
Within the redefined method’s implementation part, you can use the predefined prefix
super->... to access components in the superclass directly above where you
are working.You often need to do this when redefining a method to call the original
method of the superclass.
2005/Q4
© 2005 SAP AG. All rights reserved.
113
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 useful
in the case of the constructor. Either the superclass’s constructor can be used without
any need to change it, or the subclass can be expanded and other parameters will be
114
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
required in the constructor’s signature. In ABAP Objects, the constructor can only be
overwritten“” as part of inheritance. It can be overwritten in the sense that both the
signature and the implementation part can be adjusted in the subclass.
Hint: In this context, the concept of overloading is of relevance. With
overloading, a method has several definitions with different signatures and
different implementations. Overloading is not supported in ABAP Objects.
The constructor of the direct superclass must be called within the constructor of
the subclass. This is because of the specialization relationship: If a constructor was
defined in the superclass, it contains implementations that will always be executed
when an object is created in this superclass or its subclasses. However, this can only
be automatically ensured by the runtime system if the subclass’s constructor was not
changed. In most cases, supplying consistent private attributes from the superclass is
another prerequisite to calling the superclass constructor.
In contrast to instance constructors, the static constructor in the superclass is called
automatically. This means that the runtime system automatically ensures that the
static constructors of all its superclasses have already been executed before the static
constructor in a particular class is executed.
Figure 69: Rules for Calling the Constructor
2005/Q4
© 2005 SAP AG. All rights reserved.
115
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
If a subclass has not changed its instance constructor, the constructor is left unchanged
and is adopted from the superclass. The implementation is then executed from the
superclass.
Figure 70: Inheritance and Visibility
Inheritance provides an extension of the visibility concept: There are protected
components (PROTECTED SECTION). The visibility of these components lies
between public and private. Protected components are visible to all subclasses and
the class itself.
When defining local classes in ABAP Objects, you must follow the syntactical
sequence of PUBLIC SECTION, PROTECTED SECTION, PRIVATE SECTION.
116
© 2005 SAP AG. All rights reserved.
2005/Q4
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 related
to the component’s visibility. A subclass also receives the private components of its
superclass, however, these cannot be addressed in the syntax of the subclass. Private
components of superclasses can only be addressed indirectly using public or protected
methods from the superclass, which, in turn, can access the private attributes. These
restrictions are necessary to ensure that centralized maintenance is possible.
In the above example, it is possible to access the protected attribute TANK in
superclass LCL_VEHICLE directly from its subclass LCL_BUS. On the other hand,
the only way to access the MAKE and MODEL attributes from the subclasses of
LCL_VEHICLE is to use public methods.
Using the private visibility section, you can change superclasses without the need to
know the subclasses. As long as the changes you make do not affect the semantics,
you do not need to adapt the subclasses. This is because they only indirectly access
the private components from the superclass.
There is only one static component per program context.
Static components and inheritance
•
•
2005/Q4
A class that defines a public or protected static attribute shares this attribute
with all its subclasses.
Static methods cannot be redefined
© 2005 SAP AG. All rights reserved.
117
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
Your demonstration program should now look somewhat like the executable program
SAPBC401_VEHICLE_MAIN_F.
Once again, remind participants of the benefit of these steps: Centralized
maintenance of all general components of all vehicles!
At this point, we recommend having the participants do the first exercise of this lesson.
Narrowing Cast (Upcast)
Variables of the type “reference to superclass” can also refer to subclass instances at
runtime.
118
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
Some relationships cannot be portrayed well in static diagrams. At this point, we
recommend that you draw the following diagram by hand and hide the slides:
1.
2.
3.
4.
5.
6.
7.
Draw the reference variable R_TRUCK (as an example) on the left.
Write CREATE OBJECT r_truck ... above the reference variable.
Draw the object display of a truck on the right and connect it to the reference
variable.
Within this object, draw an area with a few inherited components.
Draw another reference variable R_VEHICLE some distance below the first one.
Write R_VEHICLE = R_TRUCK above the second reference variable and ask
the participants to tell you the contents of the second reference variable.
Now, it depends what you want to show with the diagram: From a technical
point of view, only an address is copied, so you can draw an arrow from
R_VEHICLE to the object.
You must ask which components are addressed with R_VEHICLE.
In contrast, in the following graphic we want to indicate the syntactic
restriction of the second reference variable. (The only reason why the inherited
components can be accessed using the second variable is because the static
type is critical for the syntax check.)
Figure 72: Narrowing Cast With Object References
2005/Q4
© 2005 SAP AG. All rights reserved.
119
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
If you assign a subclass reference to a superclass reference, this ensures that all
components that can be accessed syntactically after the cast assignment are actually
available in the instance. The subclass always contains at least the same components as
the superclass. After all, the name and the signature of redefined methods are identical.
The user can, therefore, address the subclass instance in the same way as the superclass
instance. However, 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 the
instance LCL_TRUCK can only be accessed using the reference R_VEHICLE.
If there are any restrictions regarding visibility, they are left unchanged. It is not
possible to access the specific components from the class LCL_TRUCK of the instance
(GET_CARGO in the above example) using the reference R_VEHICLE. The view is
thus usually narrowed (or at least unchanged). That is why we describe this type of
assignment of reference variables as narrowing cast. There is a switch from a view of
several components to a view of a few components. The term upcast is also common.
Figure 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 or
LCL_TRUCK. In the ABAP Debugger, the dynamic type is specified in the form
of the following object display.
120
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
object_id<\PROGRAM=program_name\CLASS=dynamic_type>
Note: Assignments between reference variables are possible whenever the
static target variables are more general or equal to the dynamic source
variables.
Your demonstration program should now contain something that looks like the
executable program SAPBC401_VEHICLE_MAIN_G. You should run your program
in debugging mode.
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 easy
to extend the vehicle management with new specific vehicles.
At this point, we recommend having the participants do the second exercise of this
lesson. Strictly speaking, the exercise assumes some knowledge that will not be
taught until the next paragraph, however this is unlikely to cause problems as many
participants have probably already programmed in the manner that is required here.
For these participants, this exercise is obsolete in any case.
2005/Q4
© 2005 SAP AG. All rights reserved.
121
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 user
who is not at all interested in the finer points of the instances of the subclasses but
who simply wants to address the shared components could use a superclass reference
for this access.
In the example shown here, a travel agency (LCL_RENTAL) needs to manage all
imaginable kinds of vehicles in one list. This leads to the question of what types
should be assigned to the internal table for the references to airplane instances. You
should also assume that the car rental company needs to be able to calculate only the
required amount of fuel for all its vehicles. Correspondingly, the ESTIMATE_FUEL
method is defined in the superclass LCL_VEHICLE and is redefined in all subclasses.
122
© 2005 SAP AG. All rights reserved.
2005/Q4
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 as
type superclass references (LCL_VEHICLE in the above example). The shared
components of the subclass objects can then be uniformly accessed. For this example,
the method ADD_VEHICLE is therefore needed. This copies the references to the
vehicle types in this internal table. Its import parameter is already typed as the
reference to the superclass.
Figure 76: Narrowing Cast and Generic Access in the Application Example
2005/Q4
© 2005 SAP AG. All rights reserved.
123
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
In the above example, the narrowing cast assignment occurs when the vehicle
reference is transferred to the formal parameter of the ADD_VEHICLE method. The
shared component is generically accessed within the loop around the internal table
containing all of the vehicle references. The ESTIMATE_FUEL method was inherited
from the LCL_VEHICLE superclass and may have been redefined.
Figure 77: Polymorphism: Generic Access Using the Superclass Reference
Which implementation is executed when ESTIMATE_FUEL is called now depends
on which object the superclass reference R_VEHICLE currently refers to. The
dynamic type, not the static type, of the reference variable is used to search for the
implementation of a method. Therefore, when r_vehicle->estimate_fuel
is called, the implementation is not executed from LCL_VEHICLE (static type of
R_VEHICLE) because the method was redefined in all vehicle classes.
When an instance receives a message to execute a particular method, the method that
implemented the class of this instance is executed. If the class has not been redefined
in the method, the implementation from the superclass is executed.
When objects from different classes react differently to the same method calls, this
is known as polymorphism. The possibility of polymorphism is one of the main
strengths of inheritance; a client can handle different classes uniformly, irrespective of
their implementation. The runtime system searches for the correct implementation of
a method on behalf of the client.
124
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
Polymorphism can be used to write programs that are highly generic, that is, they do
not need to be changed significantly if use cases are added. For instance, this would
make it very easy to add motorbikes to this example: You would simply define a new
subclass of LCL_VEHICLE which you could call LCL_MOTORBIKE. You would
also have to redefine the inherited method ESTIMATE_FUEL. Without needing any
more changes, your vehicle management system could then work with motorbikes and
calculate 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 polymorphism
through inheritance, this means that the source code is less self-explanatory and is
more susceptible to errors. For example, the syntax check can check that the function
model is called correctly, but not whether the internal table contains a valid function
module name for each vehicle.
Your demonstration program should now look somewhat like the executable program
SAPBC401_VEHICLE_MAIN_H.
2005/Q4
© 2005 SAP AG. All rights reserved.
125
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
At this point, we recommend having the participants do the third exercise of this
lesson.
Widening Cast (Downcast)
Variables of the type “reference to superclass” can also refer to subclass instances at
runtime. 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 hide
the slides:
1.
2.
3.
Draw another reference variable called R_TRUCK2 under R_VEHICLE.
Write R_TRUCK2 ?= R_VEHICLE above the third reference variable and
discuss with the participants the need to use “?”. Then ask the participants what
the content of the third reference variable is.
Draw an arrow from R_TRUCK2 to the object.
You must ask which components can be addressed with R_TRUCK2.
Figure 79: Widening Cast With Object References
126
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
If you want to assign a superclass reference to a subclass reference, you must use
the widening cast assignment operator
MOVE ... ?TO ... or its short form
?=
. Otherwise, you will get a message stating that it is not certain that all components
that can be accessed syntactically after the cast assignment are actually available in the
instance. As a rule, the subclass class contains more components than the superclass.
After assigning this type of reference back to a subclass reference to the implementing
class, clients are no longer limited to inherited components. In the example given
here, all components of the LCL_TRUCK instance can be accessed again after the
assignment using the reference R_TRUCK2.
The view is thus usually widened, or at least unchanged. That is why we describe this
type of assignment of reference variables as widening cast; there is a switch from a
view of a few components to a view of more components. The term downcast is
also common.
Figure 80: Specific Access After Widening Cast Assignments
A typical use for widening cast assignments is when specific components of instances
need to be addressed and their references are kept in variables that are typed on the
superclass. A user who is interested in the finer points of the instances of a subclass
cannot use the superclass reference for this access because it only allows access to
the shared components.
2005/Q4
© 2005 SAP AG. All rights reserved.
127
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
In this example, a car rental company (LCL_RENTAL) wants to determine the
maximum capacity of its trucks, but it stores all types of vehicle references in an
internal table that is typed as LCL_VEHICLE. Therefore, what happens if there is no
truck reference in the superclass reference R_VEHICLE at runtime but the widening
cast assignment operator tries to copy the reference to the now invalid reference
R_TRUCK?
Figure 81: Widening Cast Assignment and Exception Handling in the
Application 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 the
source variable (R_VEHICLE), namely when R_VEHICLE contains bus or sports car
references. That is why with this kind of cast, the runtime system checks, before the
assignment, whether the current content of the source variable corresponds to the type
requirements of the target variable. Otherwise, an exception that can be handled is
triggered, and the original value of the target variable remains the same.
The exception of the error class CX_SY_MOVE_CAST_ERROR can be identified
using TRY-ENDTRY and the CATCH statement. Another way to prevent this runtime
error would be to use runtime type identification (RTTI) classes. They can be used to
determine the dynamic type at runtime and to set a condition for the cast.
128
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
We recommend you do a separate demonstration to show the necessity of identifying
the exception. You can use the program SAPBC401_VEHICLE_MAIN_I as the
copy template for this.
Note: You must refer to the specific lesson about the exception concept. You
do not have enough time to discuss this topic now!
You can insert the optional exercise on the widening cast at this point. However, you
must provide a precise description of the tasks involved.
Using Inheritance
This final section does not examine whether or not inheritance should be used as a
programming technique over a number of alternatives. As early as the modeling
phase, you should be able to see whether there is a generalization/specialization
relationship between certain classes. If there is, you can use inheritance to represent
this in ABAP Objects.
Figure 82: Using Inheritance
If this is the case, you need to adhere to the relevant concepts of inheritance. For
example, the semantics must be preserved when you redefine methods. Furthermore,
inherited components must be used as intended in the superclass.
2005/Q4
© 2005 SAP AG. All rights reserved.
129
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 risk
of identifying the wrong places in which to use inheritance. Sometimes the need for
another attribute for a class is incorrectly answered with a specialization.
For example, a superclass Car contains the subclasses Red Car, Blue Car, and so on.
The statement “A red car is a specific car” is only correct at first glance. However,
there are no cars without a color. At most, there are some cars that have not been
painted. Therefore, every car needs the attribute color, assuming that it is relevant
to the application. Therefore, the attribute should already have been defined in the
superclass, or there is no longer an authorization for subclasses of this type. There
would also be contradictions with reality when you try to implement a method for
painting the cars.
Note: Such attributes are often also defined as reference variables to a
superclass of role classes. There is one description class for each role. To
change the role of an instance, exchange the references to the corresponding
role description instances. Specialist literature also refers to this as a “role
design pattern”.
In some cases, specialization relationships are identified that do not allow for the
semantics to be preserved.
For example, the class Square inherits from the class Rectangle. If you try to define
methods for the rectangle that change the width and height separately, these methods
would not make sense when applied to the square. Even if the methods were redefined
to 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 inheritance
only because some required functions were found in a (super)class – is also impossible.
130
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
121
Lesson: Inheritance and Casting
Exercise 7: Class Hierarchies
Exercise Duration: 60 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Define subclasses
•
Redefine superclass methods in subclasses
•
Effectively use visibility sections
Business Example
Your airplane management program is to be further refined. Put specific airplanes in
relation to their general airplane class.
Task 1:
In the class LCL_AIRPLANE, define the local subclass LCL_PASSENGER_PLANE
for passenger planes.
1.
Complete your program ZBC401_##_MAIN (where ## is your two-digit group
number) 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 same
type as the table field SFLIGHT-SEATSMAX.
3.
Define and implement an instance constructor that assigns values to all instance
attributes in the class.
4.
Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed
using the WRITE statement.
Task 2:
In the class LCL_AIRPLANE, define the local subclass LCL_CARGO_PLANE for
cargo planes.
1.
The class must have a private instance attribute, MAX_CARGO, with the same
type as the table field SCPLANE-CARGOMAX.
2.
Define and implement an instance constructor that assigns values to all instance
attributes in the class.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
131
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
3.
Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed
using the WRITE statement.
4.
Define the functional method GET_CARGO to return the cargo value to the
calling 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 your
new classes.
2.
Call the static method DISPLAY_N_O_AIRPLANES (before instantiating any
objects).
3.
Use the two references to create an instance of each of the subclasses
LCL_PASSENGER_PLANE and LCL_CARGO_PLANE. Decide for yourself
how to fill the attributes.
4.
Call the DISPLAY_ATTRIBUTES method for both instances.
5.
Call the static method DISPLAY_ATTRIBUTES a second time.
Task 4:
Analyze your program.
132
1.
Observe the program flow in the ABAP Debugger, paying special attention to
the call of the DISPLAY_ATTRIBUTES method.
2.
Could the method GET_TECHNICAL_ATTRIBUTES be called directly from
the redefined method DISPLAY_ATTRIBUTES of the subclasses?
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
Solution 7: Class Hierarchies
Task 1:
In the class LCL_AIRPLANE, define the local subclass LCL_PASSENGER_PLANE
for passenger planes.
1.
Complete your program ZBC401_##_MAIN (where ## is your two-digit group
number) or copy the program SAPBC401_CASS_MAIN_E. )
If applicable, enter the source code for your new class in the include program.
2.
a)
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
b)
Model solution: SAPBC401_INHS_MAIN_A
The class must have a private instance attribute, MAX_SEATS, with the same
type as the table field SFLIGHT-SEATSMAX.
a)
3.
Define and implement an instance constructor that assigns values to all instance
attributes in the class.
a)
4.
Refer to the model solution.
Refer to the model solution.
Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed
using the WRITE statement.
a)
Refer to the model solution.
Task 2:
In the class LCL_AIRPLANE, define the local subclass LCL_CARGO_PLANE for
cargo planes.
1.
The class must have a private instance attribute, MAX_CARGO, with the same
type as the table field SCPLANE-CARGOMAX.
a)
2.
Refer to the model solution.
Define and implement an instance constructor that assigns values to all instance
attributes in the class.
a)
Refer to the model solution.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
133
Unit 2: Object-Oriented Concepts and Programming Techniques
3.
Redefine DISPLAY_ATTRIBUTES so that all instance attributes are displayed
using the WRITE statement.
a)
4.
TAW10_3
Refer to the model solution.
Define the functional method GET_CARGO to return the cargo value to the
calling 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 your
new classes.
a)
2.
Call the static method DISPLAY_N_O_AIRPLANES (before instantiating any
objects).
a)
3.
Refer to the model solution.
Call the DISPLAY_ATTRIBUTES method for both instances.
a)
5.
Refer to the model solution.
Use the two references to create an instance of each of the subclasses
LCL_PASSENGER_PLANE and LCL_CARGO_PLANE. Decide for yourself
how to fill the attributes.
a)
4.
Refer to the model solution.
Refer to the model solution.
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 to
the call of the DISPLAY_ATTRIBUTES method.
a)
2.
Carry out this step in the usual manner.
Could the method GET_TECHNICAL_ATTRIBUTES be called directly from
the redefined method DISPLAY_ATTRIBUTES of the subclasses?
Answer: No, because the component of the superclass is private.
Continued on next page
134
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
Result
Model 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
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
DATA: name
TYPE s_capacity
TYPE string,
planetype TYPE saplane-planetype.
CLASS-DATA: n_o_airplanes TYPE i.
ENDCLASS.
"lcl_airplane DEFINITION
*------------------------------------------------------------------*
*
CLASS lcl_airplane IMPLEMENTATION
*
*------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
Continued on next page
136
© 2005 SAP AG. All rights reserved.
2005/Q4
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.
ENDCLASS.
"get_technical_attributes
"lcl_airplane IMPLEMENTATION
*---------------------------------------------------------------------*
*
CLASS lcl_cargo_plane DEFINITION
*---------------------------------------------------------------------*
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
137
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.
"lcl_cargo_plane DEFINITION
ENDCLASS.
*---------------------------------------------------------------------*
*
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.
"constructor
ENDMETHOD.
METHOD display_attributes.
super->display_attributes( ).
WRITE: / ’Max Cargo = ’, max_cargo.
ULINE.
"display_attributes
ENDMETHOD.
METHOD get_cargo.
re_cargo = max_cargo.
ENDMETHOD.
"get_cargo
Continued on next page
138
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
"lcl_cargo_plane IMPLEMENTATION
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS lcl_passenger_plane DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..
PUBLIC SECTION.
METHODS: constructor IMPORTING im_name TYPE string
im_planetype TYPE saplane-planetype
im_seats TYPE sflight-seatsmax.
METHODS: display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: max_seats TYPE sflight-seatsmax.
"lcl_passenger_plane DEFINITION
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS lcl_passenger_plane IMPLEMENTATION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_passenger_plane IMPLEMENTATION.
METHOD constructor.
CALL METHOD super->constructor( EXPORTING im_name
= im_name
im_planetype = im_planetype ).
max_seats = im_seats.
"constructor
ENDMETHOD.
METHOD display_attributes.
super->display_attributes( ).
WRITE: / ’Max Seats = ’, max_seats.
ULINE.
ENDMETHOD.
ENDCLASS.
2005/Q4
"display_attributes
"lcl_passenger_plane IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
139
Unit 2: Object-Oriented Concepts and Programming Techniques
140
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
TAW10_3
131
Lesson: Inheritance and Casting
Exercise 8: Polymorphism
Exercise Duration: 20 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Program narrowing cast assignments
•
Use inheritance relationships for polymorphic method calls
Business Example
Your airplane management program should display the attributes of the airplane
objects generically: that is, it should be open to future extensions with additional
airplane classes.
Task 1:
Buffer the airplane references in a suitable type of internal table.
1.
Complete your ZBC401_##_MAIN program or copy the sample solution from
the previous exercise. (## is your two-digit group number).
2.
In your main program, define an internal table for buffering airplane references
if you do not already have one. The row type of the internal table should be
REF 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 the
DISPLAY_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 the
call of the DISPLAY_ATTRIBUTES method.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
141
Unit 2: Object-Oriented Concepts and Programming Techniques
2.
142
TAW10_3
What would happen if the method DISPLAY_ATTRIBUTES had not been
redefined in the subclasses?
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
Solution 8: Polymorphism
Task 1:
Buffer the airplane references in a suitable type of internal table.
1.
2.
Complete your ZBC401_##_MAIN program or copy the sample solution from
the previous exercise. (## is your two-digit group number).
a)
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
b)
Model solution: SAPBC401_CASS_MAIN_A
In your main program, define an internal table for buffering airplane references
if you do not already have one. The row type of the internal table should be
REF TO LCL_AIRPLANE.
a)
See the source code extract from the model solution.
Task 2:
Display the attributes of all airplane types that have been created so far.
1.
Insert the references to your passenger and cargo airplanes into the internal table.
a)
2.
See the source code extract from the model solution.
Program a loop through the contents of the internal table. Call the
DISPLAY_ATTRIBUTES method every time the loop runs.
a)
See the source code extract from the model solution.
Task 3:
Analyze your program.
1.
Follow the program flow in the ABAP Debugger, paying special attention to the
call of the DISPLAY_ATTRIBUTES method.
a)
2.
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
What would happen if the method DISPLAY_ATTRIBUTES had not been
redefined in the subclasses?
Answer: The implementation from the superclass would be executed. Your
program would not contain polymorphism.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
143
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
Result
Source 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
TAW10_3
135
Lesson: Inheritance and Casting
Exercise 9: Aggregation and Generic Calls
Exercise Duration: 45 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Implement aggregation relationships between classes
•
Program narrowing cast assignments
•
Use inheritance relationships for polymorphic method calls
Business Example
The management of airplane instances should no longer take place in the main
program. Instead, it should be encapsulated in a new class for airlines.
System Data
System:
Client:
User ID:
Password:
Set up instructions:
AS 6.20 system
will be assigned
will be assigned
will be assigned
will be assigned
No special settings if you are using a standard SAP Web
Task 1:
Define a local class for airlines.
1.
From the include program SAPBC401_CAST_B, copy the portions of the
source text for the local class LCL_CARRIER into your include program
ZBC401_##_AIRPLANE so that you can add to them there (## is your two-digit
group number).
2.
Extend the signature and implementation of the ADD_AIRPLANE method
so that the airplane references can be added to the previously defined list
AIRPLANE_LIST.
3.
Extend the implementation of the DISPLAY_AIRPLANES method so that the
attributes of all airplanes of the airline can be added to the list. Each time an
airplane is added, its DISPLAY_ATTRIBUTES method should be called.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
145
Unit 2: Object-Oriented Concepts and Programming Techniques
4.
TAW10_3
Extend the implementation of the DISPLAY_ATTRIBUTES method so that all
of the attributes of the airline can be displayed and, consequently, the contents of
the airplane list can also be displayed.
Task 2:
In the main program, create an airline instance. Transfer some airplane references
to it and display the attributes.
1.
Remove all the statements from the main program that define the global internal
table for airplane references and their insertions.
2.
In the main program, define a suitably typed reference variable for your new
airline class.
3.
Using the reference, generate an instance of your class LCL_CARRIER. Decide
for yourself how to fill the attributes.
4.
Call the ADD_AIRPLANE method to transfer the airplane instances that have
been created so far to the airline. You may also create and transfer additional
airplanes.
5.
Display the attributes of the airline by calling its method
DISPLAY_ATTRIBUTES.
Task 3:
Optional exercise: Determining the highest cargo value.
146
1.
Define and implement the functional method GET_HIGHEST_CARGO in
class LCL_CARRIER to calculate the highest cargo value (load capacity) of all
cargo planes. Use the Widening Cast technique to identify all relevant airplanes
for this task.
2.
For testing purposes, this new method can be called within
DISPLAY_ATTRIBUTES of class LCL_CARRIER.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Inheritance and Casting
Solution 9: Aggregation and Generic Calls
Task 1:
Define a local class for airlines.
1.
2.
From the include program SAPBC401_CAST_B, copy the portions of the
source text for the local class LCL_CARRIER into your include program
ZBC401_##_AIRPLANE so that you can add to them there (## is your two-digit
group number).
a)
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
b)
Model solution: SAPBC401_CASS_MAIN_B
Extend the signature and implementation of the ADD_AIRPLANE method
so that the airplane references can be added to the previously defined list
AIRPLANE_LIST.
a)
3.
Extend the implementation of the DISPLAY_AIRPLANES method so that the
attributes of all airplanes of the airline can be added to the list. Each time an
airplane is added, its DISPLAY_ATTRIBUTES method should be called.
a)
4.
See the source code extract from the model solution.
See the source code extract from the model solution.
Extend the implementation of the DISPLAY_ATTRIBUTES method so that all
of the attributes of the airline can be displayed and, consequently, the contents of
the airplane list can also be displayed.
a)
See the source code extract from the model solution.
Task 2:
In the main program, create an airline instance. Transfer some airplane references
to it and display the attributes.
1.
Remove all the statements from the main program that define the global internal
table for airplane references and their insertions.
a)
2.
See the source code extract from the model solution.
In the main program, define a suitably typed reference variable for your new
airline class.
a)
See the source code extract from the model solution.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
147
Unit 2: Object-Oriented Concepts and Programming Techniques
3.
Using the reference, generate an instance of your class LCL_CARRIER. Decide
for yourself how to fill the attributes.
a)
4.
See the source code extract from the model solution.
Call the ADD_AIRPLANE method to transfer the airplane instances that have
been created so far to the airline. You may also create and transfer additional
airplanes.
a)
5.
TAW10_3
See the source code extract from the model solution.
Display the attributes of the airline by calling its method
DISPLAY_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 in
class LCL_CARRIER to calculate the highest cargo value (load capacity) of all
cargo planes. Use the Widening Cast technique to identify all relevant airplanes
for this task.
a)
2.
Refer to the model solution.
For testing purposes, this new method can be called within
DISPLAY_ATTRIBUTES of class LCL_CARRIER.
a)
Refer to the model solution.
Result
Source 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
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
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
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.
2005/Q4
"lcl_carrier IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
151
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 Information
For more information about this subject, refer to the SAP Library and the ABAP
keyword documentation for the individual statements.
152
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson:
143
Lesson: Interfaces and Casting
Interfaces and Casting
Lesson Duration: 120 Minutes
Lesson Overview
The only real difference between interfaces and inheritance is the role they play. The
programming advantages are thus the same as for inheritance.
Lesson Objectives
After completing this lesson, you will be able to:
•
•
•
•
•
•
Define and implement interfaces
Implement interface methods
Use interface references to make narrowing cast assignments
Use interface references to make widening cast assignments
Define polymorphism with reference to interfaces
Use cast assignments with interfaces to make generic calls
Although there are no significant technical differences between regular inheritance
and the implementation of interfaces, 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 serves
to build on the analogy with regular inheritance rather than presenting significant
new programming techniques.
In this lesson, you must make a clear distinction between the terms signature and
interface. Otherwise, you will confuse the participants.
Business Example
You want to implement client/server relationships in combination with generic access
from your model in ABAP Objects.
Areas of Use for Interfaces
Interfaces differ from regular inheritance in their area of use. In terms of programming,
however, there are hardly any differences.
2005/Q4
© 2005 SAP AG. All rights reserved.
153
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
From a technical point of view, interfaces are simply superclasses that cannot be
instantiated, do not have an implementation part, and only have public components.
However, we will see that you can simulate multiple inheritance using interfaces.
In ABAP Objects, interfaces primarily serve to define uniform interfaces (protocols)
for services. Various classes can offer – that is, implement – these services in different
ways, but keep the same semantics. Interfaces contain no implementations.
In ABAP Objects, the same components can generally be defined in interfaces and in
classes. To recognize the semantic differences from regular inheritance, concentrate
on 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 implementing
a service in different ways, but using the same method names and with a uniform
signature. With regular inheritance, you would define such a method in the shared
superclass. However, if you cannot siutably model a superclass for inheritance, you
need to define an interface and then define this method there. Therefore, you can
compare this case with a generalization relationship with a superclass.
154
© 2005 SAP AG. All rights reserved.
2005/Q4
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 (both
technically and semantically) the services that he wants the providers to offer. Each
class can now decide for itself whether it serves the interface, that is, actually
offers the services defined there. Therefore, this case is similar to a specialization
relationship with a subclass.
As with regular inheritance, access to these services is usually generic, that is, it uses
a reference that is typed on the interface. As with regular inheritance, you can thus
perform polymorphism with interfaces.
2005/Q4
© 2005 SAP AG. All rights reserved.
155
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 to
their name, they have the stereotype «interface». The use of an interface is represented
by a dotted line with a two-sided arrow from the user to the interface; the stereotype
«uses» is optional. The fact that a class implements an interface is represented by a
dotted arrow from the class to the interface.
The similarity with representing a generalization/specialization relationship is
justified, as we have just described.
Creating Generalization/Specialization Relationships
Using Interfaces
In ABAP Objects, the same components can be defined in an interface as in classes.
However, interfaces do not know the visibility levels of components: that is, all
components of an interface are public.
Note: Note: The areas of use for interfaces as the uniform interface for
offering services.
156
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Interfaces and Casting
Figure 87: Defining and Implementing an Interface
We recommend that you do a separate demonstration to show the
definition and implementation of an interface. You can use program
SAPBC401_VEHICLE_MAIN_J as the copy template for this.
The slide above was included because the participants are likely to have problems
with interfaces. This slide shows the perfect recipe for defining and implementing
interfaces. 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 interface
methods are implemented in the classes. Following this procedure (in the exercises
also) 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 preparatory
programming (which brings together the two submodels) is required in order to have a
clear starting point. In the second part of the exercise, the participants implement the
procedure shown on the slide discussed above.
2005/Q4
© 2005 SAP AG. All rights reserved.
157
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 that
most participants will not have previously experienced how easy it can be to join
totally independent applications using object-oriented programming.
The background here is the semantic context in terms of the interface to be defined.
Classes implement interfaces as follows:
•
•
•
The interface name is listed in the definition part of the class with the
INTERFACES statement. This must be in the PUBLIC SECTION, that is,
interfaces can only be implemented publicly.
Interface methods must be implemented in the implementation part of the class.
The components defined in the interface can be addressed in the implementation
part of the class.
Interface components are distinguished from the other components in the
implementing class by prefixing the interface name followed by a tilde (~) (the
interface resolution operator).
interface_name~component_name
To simplify access to interface components, you can use alias names. These can
only appear in the definition part of a class or in the interface definition. Their use is
subject to the visibility restriction of the defining class.
Example of an alias in the interface:
ALIASES a_1 FOR lif_1~method_1.
The interface method lif_1~method_1 can be addressed with the shorter form
ref->a_1
.
158
© 2005 SAP AG. All rights reserved.
2005/Q4
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 class
implements the interface. Syntactically, this takes place with the interface resolution
operator ~, just as with access to the interface components in the implementation
part of the class.
Alternately, you can use the alias names defined in the implementing class for the
interface components. Even if shared components of the implementing classes are
subsequently transferred to the interface, access to these components does not need to
be adapted. However, the source code would then be less self-explanatory because
you could conclude from the syntax that the components were defined in the class.
Point out that the access to interface components using object references shown here
is rarely used. At this point, the completeness of the explanation is what matters. The
next section shows you actually work with interfaces.
Polymorphism with Interfaces
Because interfaces cannot be instantiated, an interface reference can only refer to
instances of classes that have implemented the interface. Therefore, if you want
to perform polymorphism with interfaces, you must use narrowing cast to copy a
reference to the reference variable that was typed with the interface, just as with
regular inheritance.
2005/Q4
© 2005 SAP AG. All rights reserved.
159
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
Some relationships cannot be portrayed well in static diagrams. At this point, we
recommend that you draw the following diagram by hand and hide the slides:
1.
2.
3.
4.
5.
6.
7.
Draw the reference variable R_RENTAL (as an example) on the left side.
Write CREATE OBJECT r_rental ... above the reference variable.
Draw the object display of a car rental company on the right side and connect
it to the reference variable.
Within this object, draw an area with a few implemented interface components.
Draw another reference variable R_PARTNER at some distance below the first
one.
Write R_PARTNER = R_RENTAL above the second reference variable and ask
the participants to specify the content of the second reference variable.
Now, it depends what you want to show with the diagram: From a technical point
of view, only an address is copied so you can draw an arrow from R_PARTNER
to the object.
You must ask which components are addressed with R_PARTNER.
In contrast, in the following graphic we want to indicate the syntactic restriction
of the second reference variable. (Using the second variable, you can therefore
only access the implementing interface components can because the static type
is critical for the syntax check.)
Figure 89: Narrowing Cast with Interface References
160
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Interfaces and Casting
If the class has implemented the interface, it is certain that all components that can be
accessed syntactically after the cast assignment are actually available in the instance.
The interface always contains at least the same components as the implementing class.
A user can thus address the instance of the implementing class using the interface. The
prefixing of the interface name and the interface resolution operator is thus omitted.
However, the user is restricted to using the components from the interface.
In the example shown here, the methods DISPLAY_PARTNER and
CHECK_AVAILABILITY of the interface LIF_PARTNER can only be accessed after
assigning the reference variable R_PARTNER. It is not possible to access the specific
components of the instance from class LCL_RENTAL (GET_NAME in the above
example) using the reference variable R_PARTNER.
The view is thus usually narrowed, or at least unchanged, which is why we describe
this type of assignment of reference variables as narrowing cast. There is a switch
from a view of several components to a view of a few components. The term upcast
is also common.
Figure 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 that
implement the interface but who simply wants to address the components defined in
the interface, could use an interface reference for this access.
In the example shown above, a travel agency (LCL_TRAVEL_AGENCY) needs to
manage all the various kinds of business partner in one list. The row type of the
internal table must therefore be typed as the reference to the interface LIF_PARTNER.
2005/Q4
© 2005 SAP AG. All rights reserved.
161
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
The travel agency only wants to request the services in order to display their
attributes and to check availability. The relevant methods DISPLAY_PARTNER
and CHECK_AVAILABILITY are defined in the interface LIF_PARTNER and
implemented in all business partner classes.
Objects of different classes (LCL_HOTEL, LCL_RENTAL, and LCL_CARRIER)
can be kept in an internal table, typed with interface references (LIF_PARTNER). The
components defined in the interface can then be accessed uniformly.
For this example, method ADD_PARTNER is therefore needed. This copies the
references to all the kinds of business partner in this internal table. Its import
parameter 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 used
to call methods, whereby different implementations can be executed depending on the
object of the reference.
The dynamic type and not the static type of the reference variable is used to search for
the implementation of a method. In the above example, r_partner->display_partner(
) therefore uses the class of the instance to which r_partner actually refers in order to
search for the implementation of display_partner. It does not, for example, use the
static type for r_partner (which is always REF TO lif_partner).
162
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Interfaces and Casting
The implementation that is now executed when DISPLAY_PARTNER is called
depends on the object to which the interface reference R_PARTNER currently refers.
When objects from different classes react differently to the same method calls, this is
known as polymorphism.
The option of performing polymorphism is one of the main strengths of interfaces;
a client can handle different classes uniformly, irrespective of their implementation.
The runtime system searches for the right implementation of a method on behalf
of the client.
Polymorphism can be used to write programs that are highly generic, that is, they do
not need to be changed significantly if use cases are added.
In the example given here, it would therefore be very easy to realize a boat rental
addition. The relevant class – for example, with the name LCL_SHIPPING –
would simply have to implement the interface LIF_PARTNER and thus the method
DISPLAY_PARTNER defined there. Business partner management could then easily
include shipowning companies and also request them to display their attributes.
Your demonstration program should now resemble the executable program
SAPBC401_VEHICLE_MAIN_K. You should run your program in debugging mode.
At this point, we recommend having the participants do the second exercise of this
lesson.
Note: If the participants have already done this type of exercise as part of
inheritance, reduce the next exercise to a simple recapitulation.
In terms of programming, there are no new ideas.
2005/Q4
© 2005 SAP AG. All rights reserved.
163
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
At this point, we recommend that you add to your narrowing cast diagram and hide
the slides:
1.
2.
3.
Draw a reference variable R_RENTAL2 below R_PARTNER.
WriteR_RENTAL2 ?= R_PARTNER above the third reference variable and
discuss with the participants the necessity of including the “?”. Then ask the
participants what the content of the third reference variable is.
Draw an arrow from R_RENTAL2 to the object.
You must ask which components are addressed with R_RENTAL2.
Figure 92: Widening Cast Assignment and Exception Handling
If you want to assign an interface reference to a class reference where the class has
implemented the interface, you must use the widening cast assignment operator
MOVE ... ?TO ... or its short form ?=. Otherwise, the system would return
a message stating that it is not certain that all components that can be accessed
syntactically after the cast assignment 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 implementing
class at runtime. After assigning this type of reference (back) to a reference to the
implementing class, clients are no longer limited to interface components. In the
example given here, all components of the LCL_CARRIER instance can be accessed
again after the assignment using reference R_CARRIER.
164
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Interfaces and Casting
The view is thus usually widened, or at least unchanged, which is why we describe
this type of assignment of reference variables as widening cast. There is a switch
from a view of a few components to a view of more components. The term downcast
is also common.
A typical area of use for widening cast assignments is when specific components
of instances need to be addressed whose references are kept in variables that are
typed on the interface. A user who is interested in the finer points of instances of
implementing classes cannot use the interface reference for this access because this
only allows access to the interface components. In the example here, a travel agency
(LCL_TRAVEL_AGENCY) needs to book a flight but keeps all the various business
partner references in an internal table that was typed on the interface LIF_PARTNER.
Therefore, what happens if there is no airline reference in the interface reference
R_PARTNER at runtime but the widening cast assignment operator is used to copy
the reference to the then invalid reference R_CARRIER? In contrast to narrowing cast
assignment, it is possible that the static type of the target variable (R_CARRIER) is
neither more general than nor the same as the dynamic type of the source variable
(R_PARTNER), 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 requirements
of the target variable. Otherwise, an exception that can be handled is triggered, and
the original value of the target variable remains the same. This exception of error
class CX_SY_MOVE_CAST_ERROR can be identified using TRY-ENDTRY and
the CATCH statement.
Another way of preventing this runtime error would be to use runtime type
identification (RTTI) classes. They can be used to determine the dynamic type at
runtime and to set a condition for the cast.
Assignments between interface reference variables, whose typing interfaces are not
related to each other, cannot be checked statically and must therefore be performed
using widening cast. With such an assignment, the system checks at runtime whether
the class of the instance to which the source reference refers also supports the interface
with which the target reference is typed.
We recommend you do a separate demonstration to show the necessity of identifying
the exception.
Note: You must refer to the specific lesson about the exception concept. You
do not have enough time to discuss this topic now.
2005/Q4
© 2005 SAP AG. All rights reserved.
165
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
Interface Hierarchies
We have already seen several times that an interface implementation strongly
resembles regular inheritance. We therefore need to ask what the interface counterpart
of hierarchical inheritance looks like. We want to explain interface hierarchies using
an application example.
Compound interfaces are only discussed here as a preview of what is covered later in
the 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 further
service “room reservation” in the interface LIF_PARTNER. In this case, the classes
LCL_CARRIER and LCL_RENTAL would have to implement the appropriate
method because they have integrated the interface LIF_PARTNER. However,
implementation of a room reservation – keeping the same semantics – is not possible
for airlines or car rental companies.
However, because there are several other business partner types for which an
implementation would be useful (for example, motels and hotels), the method needs to
be centrally defined and not defined individually for motels and hotels. On the other
hand, the option of easily extending the model with other accommodation provider
types (for example, guesthouse) must be retained.
166
© 2005 SAP AG. All rights reserved.
2005/Q4
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 included
interface. It represents an extension of the included interface.
The including interface is known as a compound interface. An included interface
represents a component of another interface and is therefore known as a component
interface. An elementary interface does not itself contain other interfaces.
The UML notation corresponds to the implementation of an elementary interface
by a class.
2005/Q4
© 2005 SAP AG. All rights reserved.
167
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 compound
interface in order to integrate all components. Nevertheless, the components of the
component 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 in
the first implementing class. Alias names are suitable for short-form syntax when
accessing components from different interfaces. You can get a central documentary
view of all components with the definition of these alias names in the implementing
class.
168
© 2005 SAP AG. All rights reserved.
2005/Q4
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 interface
and for cast assignments.
Figure 97: Using Interfaces
Interfaces are used to describe protocols for using components without connecting
a kind of implementation. An intermediate layer is introduced between the client
and the server to protect the client from the explicit server, thereby making the client
independent.
2005/Q4
© 2005 SAP AG. All rights reserved.
169
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
Interfaces enable different classes to be handled uniformly, providing they
implemented the interfaces. As with inheritance, you can also perform polymorphism
using interface reference variables.
As with regular inheritance, the definition of an interface means an abstraction of the
implementing classes to a specific partial aspect.
Multiple inheritance can be simulated using interfaces: If several interfaces are
included, all components are available to all of these interfaces. All methods must be
implemented.
170
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
159
Lesson: Interfaces and Casting
Exercise 10: Interface Implementation
Exercise Duration: 45 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Define interfaces
•
Implement interfaces
Business Example
You now need to add a vehicle management procedure to your airplane management
program. The airlines and car rental companies then need to be abstracted to business
partners; that is, they need to offer general services using an abstract interface.
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 program
SAPBC401_CASS_MAIN_B (where ## is your two-digit group number).
2.
From the include program SAPBC401_VEHT_F, copy the portions of the source
code for the local classes LCL_VEHICLE, LCL_TRUCK, LCL_BUS, and
LCL_RENTAL into a new include program ZBC401_##_VEHICLE to extend
them there if necessary (## is your two-digit group number). Include this new
include program in your main program.
3.
From program SAPBC401_VEHT_MAIN_A, copy the portions of the source
code for the generation of the instances and for the method calls into your main
program to extend them there if necessary.
4.
To test your work so far, call the DISPLAY_ATTRIBUTES method for the car
rental company. The list should now display all airplanes of your airline and all
vehicles of your car rental company.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
171
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 main
program 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. This
needs to define a DISPLAY_PARTNER method. Draw the relationships to the
classes LCL_RENTAL and LCL_CARRIER.
3.
Define the local interface LIF_PARTNERS and the method
DISPLAY_PARTNER.
Hint: Include the portions of the source code needed for this in
your main program in an appropriate order with the remaining class
definitions.
4.
172
Implement the interface in the classes LCL_CARRIER and LCL_RENTAL. You
need to display a business partner’s attributes in such a way that they call their
own DISPLAY_ATTRIBUTES methods.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Interfaces and Casting
Solution 10: Interface Implementation
Task 1:
Define a class for car rental companies and a class hierarchy for general vehicles,
buses, and trucks. Generate a car rental company and add a few vehicle instances.
Add the attributes of the car rental company to the list.
1.
2.
Complete your ZBC401_##_MAIN program or copy the program
SAPBC401_CASS_MAIN_B (where ## is your two-digit group number).
a)
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
b)
Model solution: SAPBC401_INTS_MAIN_A
From the include program SAPBC401_VEHT_F, copy the portions of the source
code for the local classes LCL_VEHICLE, LCL_TRUCK, LCL_BUS, and
LCL_RENTAL into a new include program ZBC401_##_VEHICLE to extend
them there if necessary (## is your two-digit group number). Include this new
include program in your main program.
a)
3.
From program SAPBC401_VEHT_MAIN_A, copy the portions of the source
code for the generation of the instances and for the method calls into your main
program to extend them there if necessary.
a)
4.
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
To test your work so far, call the DISPLAY_ATTRIBUTES method for the car
rental company. The list should now display all airplanes of your airline and all
vehicles of your car rental company.
a)
See the source code extract from the model solution.
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 main
program 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
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
Caution: You will not receive any immediate output on the list.
a)
2.
If necessary, add an interface LIF_PARTNERS to your UML diagram. This
needs to define a DISPLAY_PARTNER method. Draw the relationships to the
classes LCL_RENTAL and LCL_CARRIER.
a)
3.
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
Ask your instructor if you have any questions.
Define the local interface LIF_PARTNERS and the method
DISPLAY_PARTNER.
Hint: Include the portions of the source code needed for this in
your main program in an appropriate order with the remaining class
definitions.
a)
4.
See the source code extract from the model solution.
Implement the interface in the classes LCL_CARRIER and LCL_RENTAL. You
need to display a business partner’s attributes in such a way that they call their
own DISPLAY_ATTRIBUTES methods.
a)
Refer to the model solution.
Result
Source 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
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
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
TAW10_3
Lesson: Interfaces and Casting
"lcl_vehicle DEFINITION
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS lcl_vehicle IMPLEMENTATION
*---------------------------------------------------------------------*
CLASS lcl_vehicle IMPLEMENTATION.
METHOD get_average_fuel.
re_avgfuel = im_distance / im_fuel.
"get_average_fuel
ENDMETHOD.
METHOD constructor.
make = im_make.
ADD 1 TO n_o_vehicles.
"constructor
ENDMETHOD.
METHOD set_make.
IF im_make IS INITIAL.
" me->init_make( ). also possible
init_make( ).
ELSE.
make = im_make.
ENDIF.
"set_make
ENDMETHOD.
METHOD init_make.
make = ’default make’.
"init_make
ENDMETHOD.
METHOD get_make.
ex_make = make.
"get_make
ENDMETHOD.
METHOD display_attributes.
WRITE: make.
"display_attributes
ENDMETHOD.
METHOD get_count.
re_count = n_o_vehicles.
ENDMETHOD.
ENDCLASS.
"get_count
"lcl_vehicle IMPLEMENTATION
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
177
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.
"constructor
ENDMETHOD.
METHOD display_attributes.
WRITE: / icon_ws_truck AS ICON.
super->display_attributes( ).
WRITE: 20 ’ Cargo = ’, max_cargo.
ULINE.
"display_attributes
ENDMETHOD.
METHOD get_cargo.
re_cargo = max_cargo.
ENDMETHOD.
"get_cargo
ENDCLASS.
Continued on next page
178
© 2005 SAP AG. All rights reserved.
2005/Q4
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.
"constructor
ENDMETHOD.
METHOD display_attributes.
WRITE: / icon_transportation_mode AS ICON.
super->display_attributes( ).
WRITE:
20 ’ Passengers = ’, max_passengers.
ULINE.
"display_attributes
ENDMETHOD.
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS lcl_rental DEFINITION
*---------------------------------------------------------------------*
CLASS lcl_rental DEFINITION.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
179
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
METHODS
display_attributes.
TYPE REF TO lcl_vehicle.
INTERFACES lif_partners.
PRIVATE SECTION.
"------------------DATA: name TYPE string,
vehicle_list TYPE TABLE OF REF TO lcl_vehicle.
ENDCLASS.
*---------------------------------------------------------------------*
*
CLASS lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------*
CLASS lcl_rental IMPLEMENTATION.
METHOD lif_partners~display_partner.
display_attributes( ).
ENDMETHOD.
METHOD constructor.
name = im_name.
"constructor
ENDMETHOD.
METHOD add_vehicle.
APPEND im_vehicle TO vehicle_list.
"add_vehicle
ENDMETHOD.
METHOD
display_attributes.
DATA: r_vehicle TYPE REF TO lcl_vehicle.
WRITE: /
WRITE:
icon_transport_proposal AS ICON, name.
’ Here comes the vehicle list: ’. ULINE. ULINE.
LOOP AT vehicle_list INTO r_vehicle.
r_vehicle->display_attributes( ).
ENDLOOP.
ENDMETHOD.
ENDCLASS.
"display_attributes
"lcl_rental IMPLEMENTATION
Continued on next page
180
© 2005 SAP AG. All rights reserved.
2005/Q4
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
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( ).
"lif_partners~display_partner
ENDMETHOD.
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
TAW10_3
Lesson: Interfaces and Casting
ex_name = name.
ENDMETHOD.
ENDCLASS.
2005/Q4
"get_name
"lcl_carrier IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
183
Unit 2: Object-Oriented Concepts and Programming Techniques
184
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
TAW10_3
173
Lesson: Interfaces and Casting
Exercise 11: Aggregation, Generic Calls,
and Polymorphism
Exercise Duration: 45 Minutes
Exercise Objectives
After 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 Example
You now need to add a user class to your program. Travel agencies need to manage
various business partners using the interface and access the business partners’ general
services.
Task 1:
Define a local class for travel agencies.
1.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise (## is your two-digit group number.)
2.
If necessary, add a class to your UML diagram LCL_TRAVEL_AGENCY that
uses the interface LIF_PARTNERS.
3.
From program SAPBC401_VEHT_B, copy the portions of the source code for
the local class LCL_TRAVEL_AGENCY into your main program or one of your
include programs to extend them there.
4.
Add to the row type of the internal table PARTNER_LIST so that references to
the business partners that have implemented your interface can be buffered.
5.
Add to the signature and implementation of method ADD_PARTNER so that
business partner references can be added to the list PARTNER_LIST.
6.
Add to the implementation of method DISPLAY_AGENCY_PARTNERS so
that the attributes of all the travel agency’s business partners can be added to the
list. The centrally provided method DISPLAY_PARTNER needs to be called for
each business partner.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
185
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 the
airline and car rental company to this instance, and add the attributes.
186
1.
In the main program, define a suitably typed reference variable for your new
travel agency class.
2.
Using the reference, generate an instance of your class LCL_TRAVEL_AGENCY.
Decide for yourself how to fill the attributes.
3.
Call the method ADD_PARTNER to transfer the references to the generated
airline and car rental company instances to the travel agency.
4.
Add the attributes of the travel agency by calling its method
DISPLAY_AGENCY_PARTNERS.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Interfaces and Casting
Solution 11: Aggregation, Generic Calls,
and Polymorphism
Task 1:
Define a local class for travel agencies.
1.
2.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise (## is your two-digit group number.)
a)
Carry out this step in the usual manner. For more information, refer to
the SAP Library.
b)
Model solution: SAPBC401_INTS_MAIN_B
If necessary, add a class to your UML diagram LCL_TRAVEL_AGENCY that
uses the interface LIF_PARTNERS.
a)
3.
From program SAPBC401_VEHT_B, copy the portions of the source code for
the local class LCL_TRAVEL_AGENCY into your main program or one of your
include programs to extend them there.
a)
4.
See the source code extract from the model solution.
Add to the signature and implementation of method ADD_PARTNER so that
business partner references can be added to the list PARTNER_LIST.
a)
6.
Carry out this step in the usual manner. For more information, refer to
the SAP Library.
Add to the row type of the internal table PARTNER_LIST so that references to
the business partners that have implemented your interface can be buffered.
a)
5.
Ask your instructor if you have any questions.
See the source code extract from the model solution.
Add to the implementation of method DISPLAY_AGENCY_PARTNERS so
that the attributes of all the travel agency’s business partners can be added to the
list. The centrally provided method DISPLAY_PARTNER needs to be called for
each business partner.
a)
See the source code extract from the model solution.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
187
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 the
airline and car rental company to this instance, and add the attributes.
1.
In the main program, define a suitably typed reference variable for your new
travel agency class.
a)
2.
Using the reference, generate an instance of your class LCL_TRAVEL_AGENCY.
Decide for yourself how to fill the attributes.
a)
3.
See the source code extract from the model solution.
Call the method ADD_PARTNER to transfer the references to the generated
airline and car rental company instances to the travel agency.
a)
4.
See the source code extract from the model solution.
See the source code extract from the model solution.
Add the attributes of the travel agency by calling its method
DISPLAY_AGENCY_PARTNERS.
a)
See the source code extract from the model solution.
Result
Source code:
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
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
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
METHODS
display_agency_partners.
TYPE REF TO lif_partners.
PRIVATE SECTION.
"-------------------
Continued on next page
190
© 2005 SAP AG. All rights reserved.
2005/Q4
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.
METHOD
"display_agency_partners
constructor.
name = im_name.
ENDMETHOD.
METHOD
"constructor
add_partner.
APPEND im_partner TO partner_list.
ENDMETHOD.
ENDCLASS.
2005/Q4
"add_partner
"lcl_travel_agency IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
191
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 Information
For more information, refer to the SAP Library.
192
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson:
181
Lesson: Events
Events
Lesson Duration: 75 Minutes
Lesson Overview
This lesson provides a general introduction to the concept of events in object
orientation, followed by an explanation of all related modeling aspects and syntax
elements. The Registration section contains the information that is probably most
important to understand the topic.
Lesson Objectives
After completing this lesson, you will be able to:
•
•
•
•
Define and trigger events
Handle events
Register and deregister event handling
Explain the key differences between explicit method calls and event-controlled
method calls
Note: This application example used here does not specify that the events are
defined in superclasses or interfaces.
Therefore, before you look at the first graphic about the event concept, you could also
start the course by turning the approach around and having the participants discuss
which class should do the defining and triggering and which should do the handling.
Assuming that the participants have understood the inheritance concept, they should
be able to come up with the solution themselves. The same applies to the optional
exercise in which participants define the event in the interface.
Business Example
You want to implement event-controlled behavior from your model in ABAP Objects.
Event-Controlled Method Calls
Besides attributes and methods, classes – and their instances – can contain a third type
of component: events. Instance events can be triggered by the instances of the class,
while static instance events can be triggered by the class itself.
Events can also be defined as interface components.
2005/Q4
© 2005 SAP AG. All rights reserved.
193
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 this
event. This means that the runtime system may call these handler methods after the
event has been triggered. In other words, the handler method is not usually called
directly by the client.
This results in a completely different modeling concept: While you are developing the
class that triggers the event, you do not need to know anything about the class that is
handling it. The triggering class sends a specific message to all classes of the running
program (and, if need be, their instances). At the time of development, it is completely
unclear what type of handlers there will be and how many will be used.
Because of the definition of the handler method, the range of possible results can be
narrowed down; however, which, if any, of these results actually will occur can only
be determined after the event has been triggered.
An event can have exporting parameters, which means that, in contrast to the explicit
method call, the calling program determines the protocol.
In this application example, after an instance in the “vehicle” class is created, it
triggers the event “vehicle created.” This event is received by different instances and
is processed differently by each one. The rental car company considers purchasing a
vehicle, the vehicle registration office registers the car, and so on.
Caution: Do not confuse this concept of events in object-oriented
programming with events in the ABAP runtime system
(LOAD-OF-PROGRAM, START-OF-SELECTION, and so on). Also, do not
confuse it with background processing or workflow control.
194
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Events
Figure 99: Event Handling in a UML Class Diagram
In UML class diagrams, a dotted arrow with the stereotype «handlesEventOf» points
from the handling class to the triggering class. The event definition and signature
only appear implicitly in the handling class within the handler method. The handler
methods are separated from the other methods using the stereotype «eventHandler».
Triggering and Handling Events
The following summarizes all of the required programming steps for event-controlling.
Figure 100: Triggering and Handling Events: Overview
2005/Q4
© 2005 SAP AG. All rights reserved.
195
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 to
program all steps. The separation of cause and effect in your programming should be
reflected in the way you construct complex applications. Often, the event is already
triggered and all you have to do is create another event handler.
Figure 101: Defining and Triggering Events: Syntax
Within a class, instance events are defined using the EVENTS statement, while static
events are defined using the CLASS-EVENTS statement.
Events can only have exporting parameters, which must be passed by value as a copy.
A class or instance can trigger an event at runtime using the RAISE EVENT statement.
Both instance events and static events can be triggered in instance methods. Only
static events can be triggered in static methods.
When an event is triggered, the handler methods that are registered to this event are
called in sequence. Of course, these handler methods can trigger more events of
their own.
196
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Events
Figure 102: Handling Events: Syntax
Instance events or static methods can be defined within a class to handle events. To do
so, you must specify the event (FOR EVENT) and the class or interface in which the
event was defined (OF).
If the event contains exporting parameters and you want to be able to address
these syntactically, you must specify the exporting parameters immediately after
IMPORTING in the definition of the method. The handler method’s signature can
consist of no more than the exporting parameters of the associated event. The
parameters are typed by the handler method during the definition of the event. The
object that triggers the event determines the protocol.
In addition to the explicitly defined exporting parameters, the predefined importing
parameter SENDER can always be listed. By using this parameter, you can place a
reference to the event-trigger object into the handler method.
Therefore, handler methods are usually called by triggered events (RAISE EVENT);
however, they can also be called explicitly (CALL METHOD).
Registering for Events
The definition of the handler method only specifies how and to which event of which
class the method will react. At runtime, it needs to be determined which possible
reactions will actually take place and when each of these will happen.
2005/Q4
© 2005 SAP AG. All rights reserved.
197
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
When triggering instance events, you also have to specify what event the reaction will
trigger. If instance methods are set to carry out the reaction, you also have to specify
which instance(s) will perform the reaction.
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 without
the 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 is
always carried out using the trigger. When the event is triggered, the runtime uses the
trigger 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 car
rental class, and the vehicle registration class. However, you can only predetermine
which car rental instances and vehicle registration instances will react to which
vehicle instance, and when they will do so.
Registrations can also be revoked.
198
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Events
Figure 104: Registering Event Handling: Syntax
Events are registered using the SET HANDLER statement. Registration is only active
at program runtime.
With instance events, FOR is followed by the reference to the object that triggers the
event. Alternately, you can also use the addition ALL INSTANCES. That way, you
can also register objects that have not yet been created.
The addition
ACTIVATION ’X’ is optional during registration. To undo the registration, use
ACTIVATION space.
You can register several methods with one SET-HANDLER statement:
SET HANDLER
ref_handler_1->on_eventname_1
...
ref_handler_n->on_eventname_n
FOR ... .
2005/Q4
© 2005 SAP AG. All rights reserved.
199
Unit 2: Object-Oriented Concepts and Programming Techniques
TAW10_3
If several methods were registered to one event, the sequence in which the event
handler methods are called is not defined: that is, there is no guaranteed sequence in
which the event handler methods are called.
If a new event handler is registered within an event handler method for an event that
has just been triggered, this event handler is added to the end of the sequence and is
also executed when in turn. If an existing event handler is deregistered in an event
handler 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 handler
table. All handler methods that are registered to the various events are listed within
the table. For instance methods, the handler table also contains references to the
registered objects.
Objects that are registered for event handling are not deleted by the garbage collector
if there are no remaining references to them.
Your demonstration program should now resemble the executable program
SAPBC401_VEHICLE_MAIN_L. You should run your program in debugging mode.
200
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Events
Visibility Sections in Event Handling
Events 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.
PUBLIC
All
PROTECTED
Can only be handled by users within that class or its subclasses
•
PRIVATE
Can only be handled within its class
The visibility of a handler method controls who is authorized to register the
method, that is, the locations where the SET HANDLER statement may be
programmed.
PUBLIC
Anywhere in the program
PROTECTED
Can be handled by users within that class or its subclasses
PRIVATE
Can only be handled within its class
Event handler methods can only have the same visibility or more restricted visibility
than the events 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 looking
at the source code. If these concerns are voiced, repeat the characteristics of the event
concept and its advantages from the beginning of the lesson. Then point out the
significance of modeling and the diagrams.
2005/Q4
© 2005 SAP AG. All rights reserved.
201
Unit 2: Object-Oriented Concepts and Programming Techniques
202
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
TAW10_3
191
Lesson: Events
Exercise 12: Events in Superclasses
Exercise Duration: 40 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Define and trigger events
•
Handle events
•
Register event handling
Business Example
Airplane and vehicle references are to be included in the airline and the car rental
companies’ 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 the
reference to the airplane is entered into the airline’s list of airplanes.
1.
Complete your ZBC401_##_MAIN program or copy the program
SAPBC401_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 be
event-controlled.
3.
Identify the class that is suitable for triggering the event and the classes that
should be used for handling the event. Use your UML diagram if necessary.
If applicable, illustrate the relationships in your UML diagram.
4.
Define the public event AIRPLANE_CREATED and trigger it in the class
LCL_AIRPLANE using a suitable method.
5.
Change the method ADD_AIRPLANE in class LCL_CARRIER into a handler
method for the event that you just defined. You will need to change both the
signature and the implementation.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
203
Unit 2: Object-Oriented Concepts and Programming Techniques
6.
TAW10_3
Register the new handler method so that the airline enters every airplane that
was created after itself in the list.
Note: Although this model is unrealistic, we will use it for the time
being. A different rule for entering the airplane can be created later.
7.
Observe the execution of the program in the ABAP Debugger.
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 to
be in this case?
Task 2:
Define an event for the creation of a vehicle. Trigger and handle it so that the reference
to the vehicle is entered into the car rental company’s list of vehicles.
204
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 previous
exercise.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Events
Solution 12: Events in Superclasses
Task 1:
Define an event for the creation of an airplane. Trigger and handle it so that the
reference to the airplane is entered into the airline’s list of airplanes.
1.
2.
Complete your ZBC401_##_MAIN program or copy the program
SAPBC401_INTS_MAIN_B (where ## is your two-digit group number).
a)
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
b)
Model solution: SAPBC401_EVES_MAIN_A
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 be
event-controlled.
a)
3.
Ask your instructor if you have any questions.
Identify the class that is suitable for triggering the event and the classes that
should be used for handling the event. Use your UML diagram if necessary.
If applicable, illustrate the relationships in your UML diagram.
a)
4.
Define the public event AIRPLANE_CREATED and trigger it in the class
LCL_AIRPLANE using a suitable method.
a)
5.
See the source code extract from the model solution.
Change the method ADD_AIRPLANE in class LCL_CARRIER into a handler
method for the event that you just defined. You will need to change both the
signature and the implementation.
a)
6.
Ask your instructor if you have any questions.
See the source code extract from the model solution.
Register the new handler method so that the airline enters every airplane that
was created after itself in the list.
Note: Although this model is unrealistic, we will use it for the time
being. A different rule for entering the airplane can be created later.
a)
See the source code extract from the model solution.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
205
Unit 2: Object-Oriented Concepts and Programming Techniques
7.
Observe the execution of the program in the ABAP Debugger.
a)
8.
TAW10_3
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
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 to
be 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 reference
to 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)
2.
See the source code extract from the model solution.
Define the event VEHICLE_CREATED and proceed as you did in the previous
exercise.
a)
b)
See the source code extract from the model solution.
.
Result
Source 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
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
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
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
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
METHODS
display_attributes.
IMPORTING sender.
INTERFACES: lif_partners.
PRIVATE SECTION.
"------------------DATA: name TYPE string,
vehicle_list TYPE TABLE OF REF TO lcl_vehicle.
ENDCLASS.
"lcl_rental DEFINITION
*---------------------------------------------------------------------*
*
CLASS lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------*
CLASS lcl_rental IMPLEMENTATION.
METHOD lif_partners~display_partner.
display_attributes( ).
ENDMETHOD.
"lif_partners~display_partner
Continued on next page
210
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Events
METHOD
constructor.
name = im_name.
SET HANDLER add_vehicle FOR ALL INSTANCES.
ENDMETHOD.
METHOD
"constructor
add_vehicle.
APPEND sender TO vehicle_list.
ENDMETHOD.
METHOD
"add_vehicle
display_attributes.
DATA: r_vehicle TYPE REF TO lcl_vehicle.
WRITE: /
WRITE:
icon_transport_proposal AS ICON, name.
’ Here comes the vehicle list: ’. ULINE. ULINE.
LOOP AT vehicle_list INTO r_vehicle.
r_vehicle->display_attributes( ).
ENDLOOP.
ENDMETHOD.
"display_attributes
ENDCLASS.
"lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------*
*
CLASS lcl_travel_agency DEFINITION
*---------------------------------------------------------------------*
...
SAPBC401_EVES_A
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_EVES_A
*
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
*
CLASS lcl_airplane DEFINITION
*
*------------------------------------------------------------------*
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
"--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
211
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
EXPORTING ex_weight
ex_tankcap
DATA: name
TYPE saplane-planetype
TYPE s_plan_wei
TYPE s_capacity.
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
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
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
TAW10_3
Lesson: Events
name = im_name.
ENDMETHOD.
"constructor
METHOD get_name.
ex_name = name.
ENDMETHOD.
ENDCLASS.
2005/Q4
"get_name
"lcl_carrier IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
215
Unit 2: Object-Oriented Concepts and Programming Techniques
216
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
TAW10_3
Lesson: Events
205
Exercise 13: (Optional): Events in Interfaces
Exercise Duration: 30 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Define events in interfaces
•
Trigger interface events in implementing classes
•
Handle interface events
•
Register event handling
Business Example
Airline and car rental company references are to be entered into the travel agent’s list.
This process is to be event-controlled. Be sure to create your program so that it can be
easily extended to manage additional business partners of the travel agent in the future.
System Data
System:
Client:
User ID:
Password:
Set up instructions:
6.20 system.
will be assigned
will be assigned
will be assigned
will be assigned
No special settings for using a standard SAP Web AS
Task:
Define an event for the creation of a business partner. Trigger and handle it so that the
reference to the business partner is entered into the travel agent’s list of partners.
1.
Complete your ZBC401_##_MAIN program or copy the model solution from
the 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’s
list is to be event-controlled.
3.
2005/Q4
If necessary, examine your UML diagram. Which class or interface should
define the event? Which class or interface should trigger it? Which class or
interface should handle it?
Continued on next page
© 2005 SAP AG. All rights reserved.
217
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 method
in the class that you selected.
5.
Change the method ADD_PARTNER in the class LCL_TRAVEL_AGENCY
into a handler method for the event that you just defined. You will need to
change both the signature and the implementation.
6.
Register the new handler method, so that the travel agent enters every business
partner that was created after itself into the list.
Note: Although this model is unrealistic, we will use it for the time
being. A different rule for entering the business partner can be created
later.
7.
218
Observe the execution of the program in the ABAP Debugger.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Events
Solution 13: (Optional): Events in Interfaces
Task:
Define an event for the creation of a business partner. Trigger and handle it so that the
reference to the business partner is entered into the travel agent’s list of partners.
1.
2.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise (where ## is your two-digit group number).
a)
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
b)
Model solution: SAPBC401_EVES_MAIN_B
Remove the calls of the ADD_PARTNER method from your main program.
Note: The entry of a business partner reference into the travel agent’s
list is to be event-controlled.
a)
3.
See the source code extract from the model solution
If necessary, examine your UML diagram. Which class or interface should
define the event? Which class or interface should trigger it? Which class or
interface should handle it?
If applicable, illustrate the relationships in your UML diagram.
a)
4.
Define the event PARTNER_CREATED and trigger it using a suitable method
in the class that you selected.
a)
5.
Speak to your instructor if you have any questions.
See the source code extract from the model solution.
Change the method ADD_PARTNER in the class LCL_TRAVEL_AGENCY
into a handler method for the event that you just defined. You will need to
change both the signature and the implementation.
a)
See the source code extract from the model solution.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
219
Unit 2: Object-Oriented Concepts and Programming Techniques
6.
TAW10_3
Register the new handler method, so that the travel agent enters every business
partner that was created after itself into the list.
Note: Although this model is unrealistic, we will use it for the time
being. A different rule for entering the business partner can be created
later.
a)
7.
See the source code extract from the model solution.
Observe the execution of the program in the ABAP Debugger.
a)
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
Result
Source code extract:
SAPBC401_EVES_MAIN_B
REPORT
sapbc401_eves_main_b.
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
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
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
METHODS
display_attributes.
importing sender.
INTERFACES: lif_partners.
PRIVATE SECTION.
"------------------DATA: name TYPE string,
vehicle_list TYPE TABLE OF REF TO lcl_vehicle.
ENDCLASS.
"lcl_rental DEFINITION
*---------------------------------------------------------------------*
*
CLASS lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_rental IMPLEMENTATION.
METHOD lif_partners~display_partner.
display_attributes( ).
ENDMETHOD.
METHOD
"lif_partners~display_partner
constructor.
name = im_name.
SET HANDLER add_vehicle FOR ALL INSTANCES.
RAISE EVENT lif_partners~partner_created.
ENDMETHOD.
"constructor
Continued on next page
222
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Events
METHOD
add_vehicle.
APPEND sender TO vehicle_list.
ENDMETHOD.
METHOD
"add_vehicle
display_attributes.
DATA: r_vehicle TYPE REF TO lcl_vehicle.
skip 2.
WRITE: /
WRITE:
icon_transport_proposal AS ICON, name.
’ Here comes the vehicle list: ’. ULINE. ULINE.
LOOP AT vehicle_list INTO r_vehicle.
r_vehicle->display_attributes( ).
ENDLOOP.
ENDMETHOD.
"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
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.
METHOD
"display_agency_partners
constructor.
name = im_name.
SET HANDLER add_partner FOR ALL INSTANCES.
ENDMETHOD.
METHOD
"constructor
add_partner.
APPEND sender TO partner_list.
ENDMETHOD.
"add_partner
ENDCLASS.
"lcl_travel_agency IMPLEMENTATION
SAPBC401_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
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
Unit 2: Object-Oriented Concepts and Programming Techniques
ENDCLASS.
226
TAW10_3
"lcl_carrier IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
2005/Q4
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 Information
For more information, refer to the SAP Library.
2005/Q4
© 2005 SAP AG. All rights reserved.
227
Unit Summary
TAW10_3
Unit Summary
You should now be able to:
•
Define inheritance relationships between classes
•
Redefine methods
•
Create narrowing cast assignments
•
Create widening cast assignments
•
Explain the concept of polymorphism with reference to 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
TAW10_3
217
Test Your Knowledge
Test Your Knowledge
1.
What is the ABAP syntax required to make a local subclass inherit from a
superclass?
2.
What is the ABAP syntax required to redefine an inherited method in a local
class?
3.
Suppose you are copying a subclass reference to a reference variable that is
typed to the superclass (narrowing cast). What components can you access
with this reference variable?
Choose the correct answer(s).
□
□
□
□
4.
A
B
C
D
Redefined components of the superclass
Newly defined components of the subclass
Inherited components of the superclass
Redefined components of the subclass
Assume that a reference variable typed on a superclass contains a subclass
reference and you copy this to a reference variable that is typed on the class
(widening cast). Which of the following components can you access with this
reference variable?
Choose the correct answer(s).
□
□
□
□
2005/Q4
A
B
C
D
Redefined components of the superclass
Newly defined components of the subclass
Inherited components of the superclass
Redefined components of the subclass
© 2005 SAP AG. All rights reserved.
229
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 an
interface 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).
□
□
□
□
8.
A
B
C
D
The components of the interface
The components of the class that are not defined in the interface
All components of the class
The components of the interface for which alias names have been
defined
Suppose that a reference variable that is typed on an interface contains an
instance reference of a class that implements this interface and you copy this
to a reference variable that is typed on the class (widening cast). Which of the
following components can you access with this reference variable?
Choose the correct answer(s).
□
□
□
□
230
A
B
C
D
The components of the interface
The components from the class that are not defined on the interface
All components of the class
The components of the interface for which alias names have been
defined
© 2005 SAP AG. All rights reserved.
2005/Q4
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 E
of class C?
12. With which statement would you register handler method M_H of the reacting
instance REF_H with the triggering instance REF_R?
13. Can events be defined in interfaces?
14. Can events be triggered in interfaces?
2005/Q4
© 2005 SAP AG. All rights reserved.
231
Test Your Knowledge
220
TAW10_3
Answers
1.
What is the ABAP syntax required to make a local subclass inherit from a
superclass?
Answer: The INHERITING FROM addition to the CLASS-DEFINITION
statement.
2.
What is the ABAP syntax required to redefine an inherited method in a local
class?
Answer: The REDEFINITION addition to the METHODS statement.
3.
Suppose you are copying a subclass reference to a reference variable that is
typed to the superclass (narrowing cast). What components can you access
with this reference variable?
Answer: A, C
4.
Assume that a reference variable typed on a superclass contains a subclass
reference and you copy this to a reference variable that is typed on the class
(widening cast). Which of the following components can you access with this
reference variable?
Answer: A, B, C
5.
For what purpose do you use inheritance?
Answer: Inheritance is how generalization/specialization relationships between
classes are implemented in a program.
232
© 2005 SAP AG. All rights reserved.
2005/Q4
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 an
interface 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 an
instance reference of a class that implements this interface and you copy this
to a reference variable that is typed on the class (widening cast). Which of the
following components can you access with this reference variable?
Answer: A, B, C, D
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 E
of class C?
Answer:
METHODS m_h FOR EVENT e OF c ... .
12. With which statement would you register handler method M_H of the reacting
instance REF_H with the triggering instance REF_R?
Answer:
SET HANDLER ref_h->m_h FOR ref_r.
Refer to the relevant section of the lesson.
2005/Q4
© 2005 SAP AG. All rights reserved.
233
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
Unit 3
Object-Oriented Repository Objects
223
For more information, see the introductory instructor notes in the lesson.
Unit Overview
THis unit introduces you to Class Builder. Class Builder is a tool that enables you to
create global classes and interfaces that can be used by any program.
Unit Objectives
After completing this unit, you will be able to:
•
•
•
•
•
•
•
Describe the functions of the Class Builder
Create global classes using the Class Builder
Create interfaces using the Class Builder
Reference global classes 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 Contents
Lesson: Global Classes and Interfaces .......................................... 237
Procedure: Importing Local Classes and Interfaces ....................... 247
Procedure: Moving the Method Definition of a Global Class to an
Implemented Interface ......................................................... 255
Demonstration: Moving a Method Definition to an Interface.............. 255
Procedure: Creating an OO Transaction .................................... 271
Demonstration: Creating an Object-Oriented Transaction ................ 271
2005/Q4
© 2005 SAP AG. All rights reserved.
235
Unit 3: Object-Oriented Repository Objects
Exercise 14:
Exercise 15:
Exercise 16:
Exercise 17:
236
TAW10_3
Global Classes .................................................. 273
Global Interfaces................................................ 277
(Optional): Refactoring Assistant ............................ 289
ALV Grid Control ................................................ 293
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson:
224
Lesson: Global Classes and Interfaces
Global Classes and Interfaces
Lesson Duration: 180 Minutes
Lesson Overview
This lesson introduces you to a new tool in the ABAP Workbench: The Class Builder,
which was integrated into SAP R/3 4.6A at the same time as ABAP Objects. We will
examine the Class Builder’s main functions, its integration into the ABAP Workbench,
and, in particular, the Object Navigator.
We will demonstrate the use of global standard classes using the powerful example of
the ALV Grid Control.
Lesson Objectives
After completing this lesson, you will be able to:
•
•
•
•
•
•
•
Describe the functions of the Class Builder
Create global classes using the Class Builder
Create interfaces using the Class Builder
Reference global classes 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 lesson
only serves to introduce new types of Repository objects and the associated tools.
Once again, you should highlight the strengths of the ABAP Workbench SAP
development environment, particularly in comparison to working with other
programming languages. For example, a context-sensitive editor does not necessarily
offer a high-performance, cross-platform, upwardly compatible, actively integrated,
and business-oriented application language.
Business Example
You want to develop your classes and interfaces as actively integrated Repository
objects.
2005/Q4
© 2005 SAP AG. All rights reserved.
237
Unit 3: Object-Oriented Repository Objects
TAW10_3
Creating Global Classes and Interfaces
As with subroutines, local classes or interfaces can only be used within the program in
which they are defined and implemented. The CLASS statement is a local, declarative
statement in the program. Just as the TYPES statement defines local data types, the
CLASS statement defines local object types.
In both cases, it is irrelevant whether or not the source text is stored separately in
include programs.
On the other hand, global classes or global interfaces are individual Repository objects
with all of the normal attributes (active integration, versioning, transport system, and
so on). The namespace convention (Y*, Z*, or a special customer namespace) is the
same as that used for the namespace of other Repository objects.
A special maintenance tool is available for global classes in the ABAP Workbench
as of SAP R/3 4.6A: the Class Builder.
Be sure to explain the correct use of the Class Builder slowly and in
detail. In addition to the presentation, you should show all of the steps in
a separate demonstration class. For instance, you could create the class of
airplanes globally as a demo and then have the participants build houses
and hotels in the exercise. They will take to this quite enthusiastically!
A further idea: do not perform the inheritance, redefinition and overloading of the
constructor yourself, but rather let the participants discover this themselves in the
Class Builder. This was a huge motivation in the First Teach of the course!
238
© 2005 SAP AG. All rights reserved.
2005/Q4
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 development
tool for all Repository objects. It also supports the Class Builder. As with other
Repository objects, the easiest way to create a new global class is to use the context
menu in the navigation area. First select the package node or select the class node
itself within a package.
A dialog box asks you to make further attributes for the new class. Do not change
the default attributes at this point; you will learn about the different settings and
their effects later.
Do the same when creating global classes.
The global class or global interface is then displayed in the Class Builder table in
the editor area of the Object Navigator.
2005/Q4
© 2005 SAP AG. All rights reserved.
239
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. You
can define new attributes here.
You can use the input help when you are defining the type attributes. Remember to
use meaningful short descriptions.
Figure 108: Definition of Methods
240
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
Choose the Methods tab to open the list of all method definitions in the class. You can
define new methods here. You can use the input help when defining the attributes.
Remember to use meaningful short descriptions.
There are separate editor windows for the signature and the implementation.
Caution: Finding the signature of methods is often overlooked, or even
forgotten, in the exercises. Demonstrate this several times!
Choose the Constructor button to define an instance constructor. The constructor
name is chosen automatically and the selection possibilities in the editor window for
the signature are restricted appropriately.
Hint: Methods can be transported separately.
We suggest that you include the interface in your demonstration class later, after the
first exercise is complete. The focus is on working with the Class Builder, and not on
integrating the class with implemented interface methods in the application; this should
happen right at the end. You will have to hold back some of the participants here.
2005/Q4
© 2005 SAP AG. All rights reserved.
241
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 name
of the interface in the Interfaces tab. Once you have done that, all of the interface’s
components automatically appear under the relevant tabs according to the naming
convention and the interface resolution operator.
Figure 110: Definition of Method Signatures
242
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
In the method list, select a method and choose the Parameter button to go to the
signature maintenance. You can define new formal parameters here.
You can use the input help when defining the attributes. Remember to use meaningful
short descriptions.
You can scroll between the signatures using the Previous Method or Next Method
buttons. 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 implement
the modifications here.
You can display the method’s signature by choosing the relevant button.
2005/Q4
© 2005 SAP AG. All rights reserved.
243
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 method
during the implementation.
Figure 113: Definition of Components Using the Navigation Area
244
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
You can also define attributes, methods, or events in the context menu in the Object
Navigator’s navigation area. The properties are then maintained in a dialog box, and
not in the table we saw before.
Hint: Print selected portions of the source text using Class → Print or
Method → Print.
Remind participants of the importance of documentation. They should document
every class individually as well as the class as a whole.
Figure 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 Call
method icon.
2005/Q4
© 2005 SAP AG. All rights reserved.
245
Unit 3: Object-Oriented Repository Objects
TAW10_3
You can test the triggering of events in a class as follows:
1.
2.
3.
Select an event.
Choose Handler. This registers a standard method for the event.
Call a method in which the event trigger was implemented.
The event that was triggered and all of the exported actual parameters are displayed
in a list.
Demonstrate the following procedure in the system because the menu path is not easy
to find and it may not be clear how to use the next screen correctly. This is a good
opportunity to create a global interface for the business partners. You will also need it
later when you add global classes to your demonstration program.
246
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
232
Lesson: Global Classes and Interfaces
Importing Local Classes and Interfaces
Use
This procedure is an easy way to make global copies of local classes and local
interfaces.
Hint: This function cannot be used from within OBJECT-NAVIGATOR.
Procedure
1.
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 program
classes.
3.
Enter the name of the main program and, if the local classes and interfaces were
defined within include programs, select Expand Includes.
4.
Choose Display Classes/Interfaces.
5.
Enter names for the global classes and interfaces that you want to create.
Remember the customer namespace, if applicable.
6.
Select the global classes and interfaces that you want to create and choose the
Import button.
Figure 115: Importing a Local Program Class
2005/Q4
© 2005 SAP AG. All rights reserved.
247
Unit 3: Object-Oriented Repository Objects
TAW10_3
Other Functions of the Class Builder
You 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 subclass
ZCL_CARGO_PLANE_00 will inherit from superclass ZCL_AIRPLANE_00.
248
© 2005 SAP AG. All rights reserved.
2005/Q4
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 the
Redefine 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
Unit 3: Object-Oriented Repository Objects
TAW10_3
Technically, you are not defining a class within a class, but a class that is local in
the Repository object of the global class.
All components of the global class have access to these local types, but they are
encapsulated 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 (for
Local Class Implementations).
Figure 119: Structured Display of Inherited Components
To improve your understanding of inheritance and interface components, you can set
the Group by Classes and Interfaces flag in the User-Specific Settings for the Class
Builder. The system will then display the components of the global class in a structure.
250
© 2005 SAP AG. All rights reserved.
2005/Q4
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, display
the appropriate dialog box by choosing the Sort button.
Addition of Global Classes Using the ABAP Editor
Like other repository objects, global classes and interfaces are added in the navigation
area of the OBJECT-NAVIGATOR.
Be sure to demonstrate the following editing possibilities, ideally using the global
demonstration class that you just created.
Show both possibilities: Drag&Drop and the Pattern button.
2005/Q4
© 2005 SAP AG. All rights reserved.
251
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
TAW10_3
Lesson: Global Classes and Interfaces
In the navigation area, click on a class name and drag it to the editing area. This
creates a CREATE OBJECT statement. You must then add the reference variable and
the actual parameters, if applicable, to the statement.
Alternately, you can choose the Pattern button. The CREATE-OBJECT statement is
under 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. This
creates a CREATE METHOD statement. You must then add the reference variable
and the actual parameters, if applicable, to the statement.
Alternately, you can choose the Pattern button. The CALL-METHOD statement is
under ABAP Objects Pattern. You can generate the statement using the input help.
Optionally, you can prepare the participants for the next exercise by including the
global interface in the global class and adapting the demonstration program to use the
global interface. This step may not be necessary for more able groups of participants.
Make sure you take advantage of the positive motivational effect at the end of
the exercise: Again, this should show the participants how easy it is to extend
object-oriented software applications if they have been modeled well and consistently.
2005/Q4
© 2005 SAP AG. All rights reserved.
253
Unit 3: Object-Oriented Repository Objects
TAW10_3
The Refactoring Assistant
In an ideal world, all classes, interfaces, and the associations between them
would be modeled completely using UML diagrams before developers began
implementing them. However, in some cases, the model needs to be adapted
during the implementation phase. The Refactoring Assistant offers a range of
user-friendly options for you to change Repository objects. For example, you can use
the Refactoring Assistant to move the components of a class within the inheritance
hierarchy. Hint: For a complete list of features of the Refactoring Assistant, refer to
the 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 Refactoring
Assistant. 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 know
how much you will need to alter object references after making these changes.
254
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
240
Lesson: Global Classes and Interfaces
Moving the Method Definition of a Global Class to an
Implemented 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 to
move 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 an
Interface
Purpose
This section demonstrates the correct use of the Refactoring Assistant. This is also a
good time to point out the easy connection to the SAP Library.
System Data
System:
will be assigned
Client:
will be assigned
User ID:
will be assigned
Password:
will be assigned
Set up instructions:
No special settings required if you are using a standard
SAP Web AS 6.20 training system
1. Either copy the global class CL_BC401_BOOT_CALL_METHOD and global
interface IF_BC401_BOOT_EMPTY or create your own equivalent objects.
2.
Analyze and activate the copy of the interface (which is currently empty).
Adapt the copy of the class: Change the interfaces list to include the name of the
copy of the interface.
Analyze, activate, and test the copy of the class.
3.
2005/Q4
Open the Refactoring Assistant and refer to the SAP Library.
© 2005 SAP AG. All rights reserved.
255
Unit 3: Object-Oriented Repository Objects
TAW10_3
Move the SEND_MESSAGE method from the class to the interface using
Drag&Drop.
4.
Save your work and point out the message texts.
5.
Look at the interface: The method definition has been inserted.
6.
Activate the interface.
7.
Look at the class: The method definition has been adapted.
Caution: Adapt the SEND_MESSAGE method in the CALLER
method.
8.
Activate and test the class
9.
Sample objects in package BC401:
•
•
Global class CL_BC401_BOOD_CALL_METHOD
Global interface IF_BC401_BOOD_EMPTY
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 the
ZCL_##_HOUSE class and then create the ZCL_##_HOTEL class as a
subclass. The hotel could then be integrated into the application.
256
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
Object-Oriented ABAP Programming:
ALV Grid Control
The following will illustrate possible application areas of object-oriented ABAP
programming and the use of SAP standard classes. As examples, there will be brief
discussions of the ALV Grid Control (ALV stands for Advanced List Viewer) in the
context of the SAP Control Framework and the Business Add-Ins.
The Control Framework is a collection of global classes and interfaces that you
can use to add SAP GUI controls in your ABAP Objects programs, regardless of
the platform. We will show you how to use SAP standard classes effectively with
reference 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 simply
revision. If that is the case, consider demonstrating a different application control or
adding event handling to the SAP Grid Control.
You must emphasize that this is an application example. This is not an introduction
to dialog programming with EnjoySAP controls.
Figure 125: The ALV Grid Control
The ALV Grid Control is a tool that you can use to display non-hierarchical lists in a
standardized 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
Unit 3: Object-Oriented Repository Objects
TAW10_3
The ALV Grid Control contains a number of interactive standard functions that users
of lists often need, for example, print, export, and so on. As a developer, you have
the option of hiding these standard functions. When required, you can adapt the
implementations to fit the needs of your application. You can also add your own
functions 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 by
container controls. Generally, application controls (ALV Grid Control, Tree Control,
Picture Control, and so on) are always embedded in this container control, which, in
turn, is connected to the screen.
There are different types of container controls. However, they all incorporate
fundamental control functions, such as scroll bars.
Let us take a common case as an example: placing an ALV Grid Control in a screen
area with a fixed size.
You need to create an instance of each of the global classes CL_GUI_CUSTOM_CONTAINER and CL_GUI_ALV_GRID.
258
© 2005 SAP AG. All rights reserved.
2005/Q4
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.
2.
3.
4.
Use the fullscreen editor of the Screen Painter to define a custom control area
on your screen.
Create an instance of the class CL_GUI_CUSTOM_CONTAINER and transfer
the name of the custom control area to the constructor.
Create an instance of the class CL_GUI_GUI_ALV_GRID and transfer the
reference to the custom control instance to the constructor.
Call the method SET_TABLE_FOR_FIRST_DISPLAY of the grid control
instance and transfer the internal standard table to it.
If this table has a global row type, you can transfer the name of this global
structure to the same method. The ALV Grid Control instance then automatically
creates the field catalog.
If you change the contents of the internal tables while the program is running, you
only need to call the REFRESH_TABLE_DISPLAY method in the relevant dialog
step to refresh the display.
2005/Q4
© 2005 SAP AG. All rights reserved.
259
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 is
displayed, for example. In the example displayed, the booking data for the individual
flight 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 handler
method.
260
© 2005 SAP AG. All rights reserved.
2005/Q4
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 discussion
though!
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 as
well.
A handler method can either be a class method (static method) or an instance method
of an object. If a class method is defined as a handler method, no object of the handled
class needs to be instantiated to use the method.
To create a handler object for an event, first define a class. This class has a
public method (in the PUBLIC SECTION) that can react to an event. During the
implementation of the handler method, define the source text that should be run when
the event is triggered. The method receives the information delivered by the event
from the mouse position when you double-click, and creates an information message
in the control example that displays the row and field of the mouse click.
2005/Q4
© 2005 SAP AG. All rights reserved.
261
Unit 3: Object-Oriented Repository Objects
TAW10_3
Preferably, use the system to demonstrate how you can easily catch the double-click
through this new handler class. As an exercise, the participants should at least
program this in order to reinforce their knowledge of the event handling as well (the
double-click exercise is therefore a must!).
With advanced participants, we recommend that you also use the optional exercise
three 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 teaching
approach carefully! A total of four exercises on the ALV are available. Of
course, your time schedule will also determine the number of exercises
you can cover.
Note: Extensive documentation about the SAP Control Framework is
available. The SAP Library contains comprehensive descriptions of all
classes and a complete tutorial.
The Object Navigator also contains the Enjoy Demo Center, which makes
it very easy to use standard template programs. You can find it by choosing
Environment → Examples → Control Examples.
Individual elements of the SAP Control Framework are also covered in other
courses.
SAP also offers a separate comprehensive course about dialog programming
with the EnjoySAP controls. It covers all aspects, including complex
programming techniques like drag 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
TAW10_3
Lesson: Global Classes and Interfaces
Object-Oriented ABAP Programming:
Business Add-Ins
Unlike customer exits, Business Add-Ins of the changed software delivery process
are taken into account here. Generally, the typical delivery process does not only
consist of providers and users,: rather, several intermediate providers may be involved
in the delivery chain for software. For example, an SAP application program can
be extended with an industry solution (Industrial Business Unit [IBU]); the same
program 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 full
demo here from the corresponding ABAP course. You can also use the
SAPBC401_CLSS_MAIN_BADI program as a reference, and demonstrate this
step-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
Unit 3: Object-Oriented Repository Objects
TAW10_3
Caution: The adapter displayed here on the graphic is always the same. Both the
partner 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 the
enhancement option through an interface and an adapter class that implements the
interface.
The interface can then be implemented by several possible users in the delivery
chain. Multiple implementations are therefore also possible; once a BAdI has been
implemented, it can also be implemented by users who appear further to the right in
the 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>) with
corresponding, formally defined methods. The adapter class that is automatically
generated 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 to
be coded, but happens in the adapter class itself in an undefined sequence. When you
have several active implementations, there is no predefined processing sequence.
264
© 2005 SAP AG. All rights reserved.
2005/Q4
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 the
BAdI interface and the adapter class. To ensure you keep a clear overview, it is
recommended that you retain these names.
Note: Detailed information on the BAdI interface definition is provided in
the specific training course on the enhancement techniques and is not part
of 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
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 Business
Add-In interface.”
An object of the adapter class is instantiated by the call of the GET_INSTANCE static
method 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
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 BAdI
name, you can use one of the following proven search mechanisms:
The Repository Information-System (SE84)
The application hierarchy (SE81)
The Implementation Guide through SPRO
Navigate directly via F1->Technical Info into the application program and
search for the instantiation of the BAdI adapter class using the CL_EXITHANDLER=>GET_INSTANCE call.
Double-clicking on the reference variable
(here, R_ADAPTER) brings you to its definition, in which the BAdI interface is used
for typing. You can derive the BAdI name from the name of the interface.
2005/Q4
© 2005 SAP AG. All rights reserved.
267
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 you
study the documentation on this subject. The implementation is performed through
the implementation maintenance (Tools → ABAP Workbench → Business Add-Ins →
Implementation). Alternately, you could also go to the implementations by navigating
in the menu from the BAdI definition.
To implement a BAdI, a BAdI implementation name must be issued. The naming
convention here, as usual, is Z<impl>. A dialog box then appears for selecting the
corresponding BAdI.
The code to be implemented is stored in a method of an automatically generated
customer class. For this reason, the name of the implementing class must now be
given in a final dialog box. The default name from the system is comprised of “Y
or 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 the
method. Of course, you can also create auxiliary methods in the implementing class to
better 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
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 the
corresponding course. However, it is vital that the trainer test this first in advance!
Object-Oriented Transactions as a Transaction Type
In Transaction maintenance, you can create a transaction code as an object-oriented
transaction (OO). This means that you link the transaction code to either the
transaction service of the ABAP Objects services for persistent objects or to a public
method in a global or local class of a program. When calling this type of OO
transaction, which is linked to an instance method, the system automatically creates an
instance of the class in its own internal session and then executes this instance method.
This section is interesting for two reasons:
1.
This new transaction type has made it possible to develop purely object-oriented
applications, that is, applications that are not associated with procedural
framework programs.
Caution: Procedural framework programs are still required for screen
fields.
2.
2005/Q4
Participants need to learn about the object-oriented transaction services before
they can understand the flag OO Transaction Model. However, they need to
know the OO transaction as a transaction type before they learn this.
© 2005 SAP AG. All rights reserved.
269
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 the
transaction service of the ABAP Objects services. Conversely, if it is not set, you can
call any method in a global or local class.
Users therefore now have the opportunity to call methods themselves (through menu
options, 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 message
from the Extended Syntax Check. Instead, you will either cause a runtime
error, or there will be no display.
Therefore, you may have to resort to methods in local program classes. Naturally, you
can then use all the conventional dialog programming techniques.
270
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
254
Lesson: Global Classes and Interfaces
Creating 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 the
transaction code to a normal instance method.
4.
Enter the Class Name and Method. Set the Local in Program flag and, if you are
using a local class, enter the program name.
5.
Save the transaction code.
Demonstration: Creating an Object-Oriented Transaction
Purpose
Above all, the aim is to clarify the terms transaction, transaction code, program,
class, and method.
Point out the creation of the instance in particular. The GUID should help you with
that.
System Data
System:
will be assigned
Client:
will be assigned
User ID:
will be assigned
Password:
will be assigned
Set up instructions:
No special settings required if you are using a standard
SAP Web AS 6.20 training system
1. Either analyze the class CL_BC401_BOOD_ID in depth or create your own.
2.
Show the class the features of the tool by having them test it.
3.
Create a transaction code.
Choose the option Method of a Class (OO Transaction) as an Initial Object.
4.
Leave the OO transaction model flag unchecked.
Link either to the DISPLAY_ATTRIBUTES method of the global class
CL_BC401_BOOD_ID or to your own method.
5.
2005/Q4
Save the transaction code.
© 2005 SAP AG. All rights reserved.
271
Unit 3: Object-Oriented Repository Objects
6.
Enter the transaction code in the command field or insert it in a role – for
example, in your personal Favorites – and execute the transaction.
7.
Sample objects in package BC401:
•
•
272
TAW10_3
Global class CL_BC401_BOOD_ID
Transaction code BC401_BOOD
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
255
Lesson: Global Classes and Interfaces
Exercise 14: Global Classes
Exercise Duration: 40 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Describe the functions of the Class Builder
•
Create global classes using the Class Builder
Business Example
You 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 type
STRING
as a private instance
attribute
MAX_BEDS
of the type I
as a private instance
attribute
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 private
attributes with the import parameters
IM_NAME and IM_BEDS
DISPLAY_ATTRIBUTES
Instance method for displaying attributes
in an ABAP list
DISPLAY_N_O_HOTELS
Static method to display the number of
created hotel instances in an ABAP list
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
273
Unit 3: Object-Oriented Repository Objects
TAW10_3
Maintain the short texts.
Task 2:
Check your work.
274
1.
Activate your class.
2.
Test your class in the Class Builder’s testing environment.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
Solution 14: Global Classes
Task 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 remove
the inheritance relationship to the global class CL_HOUSE and the
global interface IF_PARTNERS.
2.
Define the following attributes in the class:
NAME
of the type
STRING
as a private instance
attribute
MAX_BEDS
of the type I
as a private instance
attribute
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 private
attributes with the import parameters
IM_NAME and IM_BEDS
DISPLAY_ATTRIBUTES
Instance method for displaying attributes
in an ABAP list
DISPLAY_N_O_HOTELS
Static method to display the number of
created hotel instances in an ABAP list
Maintain the short texts.
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
Unit 3: Object-Oriented Repository Objects
TAW10_3
Task 2:
Check your work.
1.
Activate your class.
a)
2.
Test your class in the Class Builder’s testing environment.
a)
276
Carry out this step in the usual manner. Additional information is available
in the SAP Library.
Follow the processes as outlined in the relevant section of this lesson.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
259
Lesson: Global Classes and Interfaces
Exercise 15: Global Interfaces
Exercise Duration: 30 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Describe the functions of the Class Builder
•
Create interfaces using the Class Builder
•
Reference global classes/interfaces in other Repository objects
Business Example
You want to add a hotel as a new business partner in your program for managing a
travel agency’s business partners. Replace the local interface that you have been using
with a global one so that it can also be implemented by the global hotel class.
System Data
System:
Client:
User ID:
Password:
Set up instructions:
6.20 system.
will be assigned
will be assigned
will be assigned
will be assigned
No special settings if you are using a standard SAP Web AS
Task 1:
Create a global interface for generalized access to business partner instances.
1.
If applicable, change the interface name in your UML diagram to
ZIF_##_PARTNERS. (## is your two-digit group number).
2.
Create the global interface ZIF_##_PARTNERS.
Define the instance method DISPLAY_PARTNER and the instance event
PARTNER_CREATED in the interface.
Hint: Import the local interface from your ZBC401_##_MAIN
program or from the previous lesson’s model solution
SAPBC401_EVES_MAIN_B.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
277
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 should
implement the interface method DISPLAY_PARTNER and trigger the instance
event PARTNER_CREATED. Draw the corresponding relationships in your
diagram.
2.
Include the interface in your hotel class.
3.
Implement the interface method in such a way that the hotel’s
DISPLAY_ATTRIBUTES instance method is called.
4.
Trigger the instance event in a suitable instance method of the hotel class.
Task 3:
Add an instance of your global hotel class to your main program.
278
1.
Complete your ZBC401_##_MAIN program or copy the program
SAPBC401_EVES_MAIN_B (where ## is your two-digit group number).
2.
Remove the definition of the local interface and adapt all places where it was
used to suit the new global interface.
3.
Define a reference variable, specify your global hotel class as the type, and
create an instance.
4.
Run your program. If you have done everything correctly, the simple instantiation
should be enough to be able to display the hotel attributes on the list as well.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
Solution 15: Global Interfaces
Task 1:
Create a global interface for generalized access to business partner instances.
1.
If applicable, change the interface name in your UML diagram to
ZIF_##_PARTNERS. (## is your two-digit group number).
a)
2.
Ask your instructor if you have any questions.
Create the global interface ZIF_##_PARTNERS.
Define the instance method DISPLAY_PARTNER and the instance event
PARTNER_CREATED in the interface.
Hint: Import the local interface from your ZBC401_##_MAIN
program or from the previous lesson’s model solution
SAPBC401_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 should
implement the interface method DISPLAY_PARTNER and trigger the instance
event PARTNER_CREATED. Draw the corresponding relationships in your
diagram.
a)
2.
Speak to your instructor if you have any questions.
Include the interface in your hotel class.
a)
3.
Implement the interface method in such a way that the hotel’s
DISPLAY_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
Unit 3: Object-Oriented Repository Objects
4.
TAW10_3
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 to
the SAP Library.
Task 3:
Add an instance of your global hotel class to your main program.
1.
2.
Complete your ZBC401_##_MAIN program or copy the program
SAPBC401_EVES_MAIN_B (where ## is your two-digit group number).
a)
Carry out this step in the usual manner. For more information, refer to
the SAP Library.
b)
Model solution: SAPBC401_CLSS_MAIN_A
Remove the definition of the local interface and adapt all places where it was
used to suit the new global interface.
a)
3.
See the source code extract from the model solution.
Define a reference variable, specify your global hotel class as the type, and
create an instance.
a)
4.
See the source code extract from the model solution.
Run your program. If you have done everything correctly, the simple instantiation
should be enough to be able to display the hotel attributes on the list as well.
a)
Carry out this step in the usual manner. For more information, refer to
the SAP Library.
Result
Source 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
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
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
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
METHODS
display_attributes.
INTERFACES:
if_partners.
IMPORTING sender.
PRIVATE SECTION.
"------------------DATA: name TYPE string,
vehicle_list TYPE TABLE OF REF TO lcl_vehicle.
ENDCLASS.
"lcl_rental DEFINITION
*---------------------------------------------------------------------*
*
CLASS lcl_rental IMPLEMENTATION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_rental IMPLEMENTATION.
METHOD if_partners~display_partner.
display_attributes( ).
ENDMETHOD.
METHOD
"lif_partners~display_partner
constructor.
name = im_name.
SET HANDLER add_vehicle FOR ALL INSTANCES.
RAISE EVENT if_partners~partner_created.
ENDMETHOD.
METHOD
"constructor
add_vehicle.
APPEND sender TO vehicle_list.
ENDMETHOD.
METHOD
"add_vehicle
display_attributes.
DATA: r_vehicle TYPE REF TO lcl_vehicle.
skip 2.
WRITE: /
WRITE:
icon_transport_proposal AS ICON, name.
’ Here comes the vehicle list: ’. ULINE. ULINE.
LOOP AT vehicle_list INTO r_vehicle.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
283
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.
METHOD
"display_agency_partners
constructor.
Continued on next page
284
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
name = im_name.
SET HANDLER add_partner FOR ALL INSTANCES.
ENDMETHOD.
METHOD
"constructor
add_partner.
APPEND sender TO partner_list.
ENDMETHOD.
"add_partner
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
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
TAW10_3
Lesson: Global Classes and Interfaces
ENDMETHOD.
"constructor
METHOD get_name.
ex_name = name.
ENDMETHOD.
ENDCLASS.
2005/Q4
"get_name
"lcl_carrier IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
287
Unit 3: Object-Oriented Repository Objects
288
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
TAW10_3
271
Lesson: Global Classes and Interfaces
Exercise 16: (Optional): Refactoring
Assistant
Exercise Duration: 15 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Describe the functions of the Class Builder
•
Create global classes using the Class Builder
Business Example
You 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 your
two-digit group number).
It will define the attribute NAME and the method DISPLAY_ATTRIBUTES.
The class ZCL_##_HOTEL will inherit from it. Draw the relationships in your
diagram.
2.
Create the global class ZCL_##_HOTEL and leave it empty.
3.
Define an inheritance relationship to make ZCL_##_HOUSE the superclass
and ZCL_##_HOTEL the subclass.
Task 2:
Move the general components of the ZCL_##_HOTEL class to the superclass.
1.
Use the Refactoring Assistant to move the NAME attribute, the instance
constructor, and the DISPLAY_ATTRIBUTES method into the class
ZCL_##_HOUSE.
2.
Adapt the signature and the implementation of the instance constructor in the
superclass.
3.
Adapt the implementation of the DISPLAY_ATTRIBUTES method in the
superclass.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
289
Unit 3: Object-Oriented Repository Objects
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.
TAW10_3
If you have done everything correctly, the display of the list should be the same
as in the previous exercise.
290
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
Solution 16: (Optional): Refactoring
Assistant
Task 1:
Define a global superclass for houses and have your hotel class inherit from it.
1.
If necessary, add the class ZCL_##_HOUSE to your UML diagram (## is your
two-digit group number).
It will define the attribute NAME and the method DISPLAY_ATTRIBUTES.
The class ZCL_##_HOTEL will inherit from it. Draw the relationships in your
diagram.
a)
2.
3.
Speak to your instructor if you have any questions.
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
Define an inheritance relationship to make ZCL_##_HOUSE the superclass
and 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.
2.
Use the Refactoring Assistant to move the NAME attribute, the instance
constructor, and the DISPLAY_ATTRIBUTES method into the class
ZCL_##_HOUSE.
a)
Follow the processes as outlined in the relevant section of this lesson.
b)
Speak to your instructor if you have any questions.
Adapt the signature and the implementation of the instance constructor in the
superclass.
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
Unit 3: Object-Oriented Repository Objects
3.
4.
5.
6.
TAW10_3
Adapt the implementation of the DISPLAY_ATTRIBUTES method in the
superclass.
a)
Follow the processes as outlined in the relevant section of this lesson.
b)
Speak to your instructor if you have any questions.
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.
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.
Observe the execution of the program in the ABAP Debugger.
If you have done everything correctly, the display of the list should be the same
as in the previous exercise.
a)
292
Carry out this step in the usual manner. For more information, refer to
the SAP Library.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
275
Lesson: Global Classes and Interfaces
Exercise 17: ALV Grid Control
Exercise Duration: 45 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Create an ALV Grid Control
•
React to double-clicking on the ALV Grid Control
Business Example
The user wants to receive further information about an output list.
You can display additional information by double-clicking on a special row in a list
that was created using an ALV Grid Control.
2005/Q4
© 2005 SAP AG. All rights reserved.
293
Unit 3: Object-Oriented Repository Objects
294
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
Unit 3: Object-Oriented Repository Objects
295
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
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 in
an 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 data
from the SPFLI database table.
3.
Define the reference variables R_CONTAINER and R_ALV_GRID required
for the ALV Grid Control in the main program. Do this directly after the report
statement.
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 the
reference variables to instantiate the two classes in this PBO module. Pay
particular attention to the fact that the CREATE OBJECT is NOT called
repeatedly when the PBO is called repeatedly.
5.
To display the ALV Grid Control data, call the method SET_TABLE_FOR_FIRST_DISPLAY and transfer the internal table with the flight
connection data.
Caution: Note that you are working with a SCREEN in this exercise
and 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
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 solution
SAPBC401_CLSS_ALV of the last exercise to ZBC401_##_ALV_EVENT1.
Alternatively, you can also use and enhance the copy template
SAPBC401_CLST_ALV_EVENT (where you fill in the blanks).
2.
If the user double-clicks on a row in the ALV Grid Control, the triggered
DOUBLE_CLICK event should be caught by a handler method of the class
LCL_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 and
E_COLUMN as the handler method.
3.
The row number and the name of the column that the user clicked on should be
displayed 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 string
variable “”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 model
TRAVEL_AGENCY. When you execute a function using the toolbar, an ALV Grid
Control should appear with a list of all airplane types. When you double-click on this
list, 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. Alternately, you could also copy the model solution SAPBC401_CLSS_MAIN_A or
the copy template SAPBC401_CLST_MAIN_B (where you fill in the blanks) to
ZBC401_##_ALV_EVENT2.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
297
Unit 3: Object-Oriented Repository Objects
2.
TAW10_3
If the user clicks on the “Display plane types” button, an ALV Grid Control
should be displayed with the list of airplane types. The data for this list
is contained in the internal table LIST_OF_PLANETYPES of the class
LCL_AIRPLANE. You can use the functional method GET_PLANETYPES
to obtain this internal table.
The function code of the button should be PLANETYPES. You can catch this
function code using the processing block AT USER-COMMAND and the
system field SY-UCOMM.
If SY-UCOMM has the value PLANETYPES, you must call the screen with the
ALV Grid Control using the command CALL SCREEN ’0100’.
Hint: If you are not familiar with ABAP reporting concepts, ask your
instructor for assistance.
Motivate the group to work together as a team. Some participants will certainly
be 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 the
airplane types, a list of flights with this type of airplane should be displayed.
1.
Enhance your last program version or copy the model solution
SAPBC401_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 of
flights should be displayed for this airplane type from the SFLIGHT database
table. This list should be displayed on the same ALV Grid Control.
Program the method DISPLAY_FLIGHTS of the class LCL_CARRIER as the
handler method of the event DOUBLE_CLICK.
Hint: Previously, an additional class was always defined as the handler
class. In this exercise, a class of the model that already exists should
make the handling method available for the first time.
Continued on next page
298
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
The appropriate records in this handler method must be read from the database
table SFLIGHT into an internal table. Set up the ALV Grid Control again using
the parameter SET_TABLE_FOR_FIRST_DISPLAY.
Hint: To ensure that the application returns a result that logically makes
sense, only read records from SFLIGHT with the relevant airplane
types and “Lufthansa” or “American Airlines” airline. Also assign
the 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, you
have to check the check table SCARR to make sure that the airline
exists. Only those airlines that appear in this check table are allowed. In
addition, only some flights and bookings exist in the training system for
these airlines (Lufthansa flights definitely exist).
Hint: Do not forget to register the event (SET HANDLER ...)
2005/Q4
© 2005 SAP AG. All rights reserved.
299
Unit 3: Object-Oriented Repository Objects
TAW10_3
Solution 17: ALV Grid Control
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
a)
2.
You want to display flight connection data from the SPFLI database table in
an 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 data
from the SPFLI database table.
a)
3.
Create the internal standard table in the ABAP Dictionary (SE11) under
Data type - Table type. Additional information is available in the SAP
Library.“”
Define the reference variables R_CONTAINER and R_ALV_GRID required
for the ALV Grid Control in the main program. Do this directly after the report
statement.
a)
4.
Carry out this step in the usual manner.
See the source code extract from the model solution or refer to the
corresponding slides about the ALV Grid Control.
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 the
reference variables to instantiate the two classes in this PBO module. Pay
particular attention to the fact that the CREATE OBJECT is NOT called
repeatedly when the PBO is called repeatedly.
a)
5.
See the source code extract from the model solution. Speak to your
instructor if you have any questions.
To display the ALV Grid Control data, call the method SET_TABLE_FOR_FIRST_DISPLAY and transfer the internal table with the flight
connection data.
Continued on next page
300
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
Caution: Note that you are working with a SCREEN in this exercise
and 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 your
instructor 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 solution
SAPBC401_CLSS_ALV of the last exercise to ZBC401_##_ALV_EVENT1.
Alternatively, you can also use and enhance the copy template
SAPBC401_CLST_ALV_EVENT (where you fill in the blanks).
a)
2.
Model solution: SAPBC401_CLSS_ALV_EVENT_1
If the user double-clicks on a row in the ALV Grid Control, the triggered
DOUBLE_CLICK event should be caught by a handler method of the class
LCL_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 and
E_COLUMN as the handler method.
a)
3.
See the source code extract from the model solution.
The row number and the name of the column that the user clicked on should be
displayed 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 string
variable “”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
Unit 3: Object-Oriented Repository Objects
*& Report
TAW10_3
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
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
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 model
TRAVEL_AGENCY. When you execute a function using the toolbar, an ALV Grid
Control should appear with a list of all airplane types. When you double-click on this
list, 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. Alternately, you could also copy the model solution SAPBC401_CLSS_MAIN_A or
the copy template SAPBC401_CLST_MAIN_B (where you fill in the blanks) to
ZBC401_##_ALV_EVENT2.
a)
Carry out this step in the usual manner.
Continued on next page
304
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Global Classes and Interfaces
2.
If the user clicks on the “Display plane types” button, an ALV Grid Control
should be displayed with the list of airplane types. The data for this list
is contained in the internal table LIST_OF_PLANETYPES of the class
LCL_AIRPLANE. You can use the functional method GET_PLANETYPES
to obtain this internal table.
The function code of the button should be PLANETYPES. You can catch this
function code using the processing block AT USER-COMMAND and the
system field SY-UCOMM.
If SY-UCOMM has the value PLANETYPES, you must call the screen with the
ALV Grid Control using the command CALL SCREEN ’0100’.
Hint: If you are not familiar with ABAP reporting concepts, ask your
instructor for assistance.
Motivate the group to work together as a team. Some participants will certainly
be very familiar with Reporting concepts and will be willing to help here.
a)
See the source code extract from the model solution. Speak to your
instructor 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 the
airplane types, a list of flights with this type of airplane should be displayed.
1.
Enhance your last program version or copy the model solution
SAPBC401_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 of
flights should be displayed for this airplane type from the SFLIGHT database
table. This list should be displayed on the same ALV Grid Control.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
305
Unit 3: Object-Oriented Repository Objects
TAW10_3
Program the method DISPLAY_FLIGHTS of the class LCL_CARRIER as the
handler method of the event DOUBLE_CLICK.
Hint: Previously, an additional class was always defined as the handler
class. In this exercise, a class of the model that already exists should
make the handling method available for the first time.
The appropriate records in this handler method must be read from the database
table SFLIGHT into an internal table. Set up the ALV Grid Control again using
the parameter SET_TABLE_FOR_FIRST_DISPLAY.
Hint: To ensure that the application returns a result that logically makes
sense, only read records from SFLIGHT with the relevant airplane
types and “Lufthansa” or “American Airlines” airline. Also assign
the 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, you
have to check the check table SCARR to make sure that the airline
exists. Only those airlines that appear in this check table are allowed. In
addition, only some flights and bookings exist in the training system for
these 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 your
instructor 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
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
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
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
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
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
EXPORTING ex_weight
ex_tankcap
DATA: name
TYPE saplane-planetype
TYPE s_plan_wei
TYPE s_capacity.
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
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
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
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
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
Unit 3: Object-Oriented Repository Objects
TAW10_3
ENDMETHOD.
ENDCLASS.
"get_name
"lcl_carrier IMPLEMENTATION
*&---------------------------------------------------------------------*
*&
Include
SAPBC401_VEHD_J
*
*&---------------------------------------------------------------------*
*---------------------------------------------------------------------*
*
CLASS lcl_vehicle DEFINITION
*---------------------------------------------------------------------*
*...nothing has changed here !
316
© 2005 SAP AG. All rights reserved.
2005/Q4
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 Information
Information about this topic is available in the SAP Library.
2005/Q4
© 2005 SAP AG. All rights reserved.
317
Unit Summary
TAW10_3
Unit Summary
You should now be able to:
•
Describe the functions of the Class Builder
•
Create global classes using the Class Builder
•
Create interfaces using the Class Builder
•
Reference global classes 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
TAW10_3
301
Test Your Knowledge
Test Your Knowledge
1.
Which of the following statements are correct?
Choose the correct answer(s).
2.
□
□
□
□
□
A
B
C
D
E
□
F
□
G
□
H
□
I
You can create function modules using the Class Builder.
A global class can contain a local class.
A global interface can contain a local interface.
A global class can contain a local interface.
A nested definition of classes is when a local class is within a global
class.
Using the Class Builder, a local class can be converted into a global
class.
A local class can be copied using the Class Builder: the copy is then a
global class.
You can use the Refactoring Assistant to move the methods to a
different class within an inheritance hierarchy.
You can use the Refactoring Assistant to design model diagrams.
For a user to be able to execute an object-oriented program, you always need to
supply a module pool program or a function group program. Otherwise, there is
nowhere for the CREATE OBJECT statement to create the instance.
Determine whether this statement is true or false.
□
□
2005/Q4
True
False
© 2005 SAP AG. All rights reserved.
319
Test Your Knowledge
302
TAW10_3
Answers
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 to
supply a module pool program or a function group program. Otherwise, there is
nowhere for the CREATE OBJECT statement to create the instance.
Answer: False
The creation of the first instance and the call of the first method can be realized
using an OO transaction. However, certain restrictions apply.
Additional information is available in the SAP Library.
320
© 2005 SAP AG. All rights reserved.
2005/Q4
Unit 4
ALV Grid Control
303
Tell the participants that ALV Grid Control application is valid for global classes and
this technique can be used for all types of lists.
Unit Overview
In this unit, we will look at an application area using object-oriented ABAP
programing with ALV Grid Control application in general and global classes. ALV
means Advanced List Viewer. ALV Grid Control can also be used to create lists in
the SAP system and replaces the classic method for creating lists using the WRITE
command.
Unit Objectives
After 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 Contents
Lesson: ALV Grid Control - Simple Lists......................................... 323
Exercise 18: ALV Grid Control - Simple Lists ............................... 329
Lesson: ALV Grid Control - Field Catalog ....................................... 337
2005/Q4
© 2005 SAP AG. All rights reserved.
321
Unit 4: ALV Grid Control
TAW10_3
Lesson: ALV Grid Control - Layout ............................................... 349
Exercise 19: ALV Grid Control - Field Catalog and Layout ............... 357
Lesson: ALV Grid Control - Events ............................................... 368
Exercise 20: ALV Grid Control - Events ..................................... 371
322
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson:
304
Lesson: ALV Grid Control - Simple Lists
ALV Grid Control - Simple Lists
Lesson Duration: 1 Minutes
Lesson Overview
This lesson covers the Control Framework, providing an overview of the programming
model that can be used to work with the ALV Grid Control. We will then look at how
you can use the ALV Grid Control to quickly create lists that are simple, but contain a
wide variety of functions.
Lesson Objectives
After completing this lesson, you will be able to:
•
•
Describe the Control Framework
Create simple lists using ALV Grid Control
Business Example
You are a programmer at ABC Travel. You have been asked to take an existing
report that displays flight information in a list, and enhance it so that users can
display additional information in a details list. You will use the ALV Grid Control to
implement this details list.
SAP Control Framework and ALV Grid Control
The SAP Control Framework is a network of global classes and interfaces that you
can use to incorporate SAP GUI controls into your ABAP object program for all
platforms. Using the widely implemented ALV Grid Control, in the following section
we 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 an
introduction to dialog programming with EnjoySAP controls.
2005/Q4
© 2005 SAP AG. All rights reserved.
323
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 a
uniform format. The list data is displayed as a table on the screen. This tool is very
user-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 list
users frequently use, for example, printing, and export. Developers can hide these
standard functions if they wish. However, you can modify the implementations on
an application-specific basis if required. You can also add your own functions to
the application toolbar.
324
© 2005 SAP AG. All rights reserved.
2005/Q4
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 application
control. Application controls (for example, ALV Grid Control, tree controls, and
picture controls) must be embedded in a container control, which in turn must be
connected with the screen.
There are different types of container controls. All of these types encapsulate basic
control 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_CONTAINER
and CL_GUI_ALV_GRID must be generated.
2005/Q4
© 2005 SAP AG. All rights reserved.
325
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.
2.
3.
4.
Define a custom control area on your screen using the screen painter’s grahical
fullscreen editor.
Generate an instance of the CL_GUI_CUSTOM_CONTAINER class and give
the constructor the name of the custom control area you have defined.
Generate an instance of the class CL_GUI_ALV_GRID and assign the
constructor the reference to the container control instance you have just
generated.
Call the SET_TABLE_FOR_FIRST_DISPLAY method of the Grid Control
instance 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 global
structure. The field catalog will then be set up by the grid control instance itself.
326
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: ALV Grid Control - Simple Lists
If the contents of the internal table change during the rest of the program run, it is
enough to call the method REFRESH_TABLE_DISPLAY in the corresponding dialog
step, to update the display accordingly.
Note: Comprehensive information is available on the SAP Control
Framework. The SAP Library contains details and an entire tutorial on all
classes.
The Enjoy Demo Center is also located in the Object Navigator under
Environment -> Examples -> Control Examples. This provides user-friendly
standard template program functions.
Individual elements of the SAP Control Framework are also covered by other
training courses.
SAP also offers a comprehensive training course on dialog programming
using the Enjoy SAP controls, covering complex programming techniques
such 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
Unit 4: ALV Grid Control
328
TAW10_3
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: ALV Grid Control - Simple Lists
309
Exercise 18: ALV Grid Control - Simple Lists
Exercise Duration: Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Output data using an ALV Grid Control
Business Example
Users would like to obtain detailed information in an output list.
System Data
System:
Client:
User ID:
Password:
Set up instructions:
1.
Will be announced by trainer
Will be announced by trainer
Will be announced by trainer
Will be announced by trainer
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 display
a list of all flights for which this type is used. Implement the list using the ALV Grid
Control.
Hint: Use the hide technique to go to the list. To do this, define a global
variant.
1.
Copy the template program TAW10_ALVT from the BC_TAW10 package
(Copy all). Enter the name ZTAW10_##_ALV_1 for the copied program, and
familiarize yourself with the program.
2.
Go to the display_attributes method of the lcl_airplane class and implement
the 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 fill
this table with the flights (sflight table) for which the aircraft type that was
clicked 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
Unit 4: ALV Grid Control
330
TAW10_3
4.
In the main program, define reference variables required for the ALV Grid
Control.
5.
For screen 100, go to the graphical Screen Painter and create a container area
that is sufficiently large. Give this area a self-explanatory name. Activate the
screen and leave the graphical Screen Painter.
6.
Instantiate the container controland ALV Grid Control objects in the existing
manage_alv_grid PBO module. Make sure that only one object is generated
even if the module is called several times. Call the set_table_for_first_display
method and pass your internal table that already contains the flights.
7.
Activate the entire program, start it, and test your new functions.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: ALV Grid Control - Simple Lists
Solution 18: ALV Grid Control - Simple Lists
Task:
Add an option to your program that allows users to select the aircraft type, and display
a list of all flights for which this type is used. Implement the list using the ALV Grid
Control.
Hint: Use the hide technique to go to the list. To do this, define a global
variant.
1.
Copy the template program TAW10_ALVT from the BC_TAW10 package
(Copy all). Enter the name ZTAW10_##_ALV_1 for the copied program, and
familiarize yourself with the program.
a)
2.
Go to the display_attributes method of the lcl_airplane class and implement
the hide technique. Make sure you read the note displayed above.
a)
3.
See the source text in the sample solution.
In the main program, define reference variables required for the ALV Grid
Control.
a)
5.
See the source text in the sample solution.
Define an internal table that has the same structure as the sflight table and fill
this table with the flights (sflight table) for which the aircraft type that was
clicked 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)
4.
Carry out this step as normal.
See the source text in the sample solution.
For screen 100, go to the graphical Screen Painter and create a container area
that is sufficiently large. Give this area a self-explanatory name. Activate the
screen and leave the graphical Screen Painter.
a)
Go to the Screen Painter by double-clicking 100 in the navigation area
under the screen flolder of your program. In the application toolbar, select
Layout and go to the graphical Screen Painter. Here, generate the container
area by selecting the corresponding button (button with a small c, for
container) in the application toolbar on the left and then use the cursor to
drag the area to the required location. Enter the name of the container area
in the name field on the top left.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
331
Unit 4: ALV Grid Control
6.
Instantiate the container controland ALV Grid Control objects in the existing
manage_alv_grid PBO module. Make sure that only one object is generated
even if the module is called several times. Call the set_table_for_first_display
method and pass your internal table that already contains the flights.
a)
7.
TAW10_3
See the source text in the sample solution.
Activate the entire program, start it, and test your new functions.
a)
Carry out this step as normal.
Result
Solution program:
REPORT
TAW10_ALVS_1
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
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
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
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.
2005/Q4
" USER_COMMAND_0100
INPUT
© 2005 SAP AG. All rights reserved.
335
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
TAW10_3
Lesson:
316
Lesson: ALV Grid Control - Field Catalog
ALV Grid Control - Field Catalog
Lesson Duration: 50 Minutes
Lesson Overview
This lesson demonstrates how you can use the field catalog to display user-defined
fields in the ALV Grid Control, amongst other things.
Lesson Objectives
After 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 Grid
Control is SAP's recommended procedure for creating lists.
Business Example
You are a programmer at ABC Travel. You have been requested to enhance flight
information by adding data that is only calculated at runtime. To do this, you have to
add a new column to the ALV.
2005/Q4
© 2005 SAP AG. All rights reserved.
337
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
TAW10_3
Lesson: ALV Grid Control - Field Catalog
The internal table with the data to be displayed can have a user-specific line type. In
order for the proxy instance to satisfactorily format the data it receives during the
screen output or when a print list is created, it requires relevant information known as
the field catalog.
You can have the proxy instance automatically generate the field catalog. For line
types that are defined in the ABAP Dictionary, you only need to inform the proxy
instance of the structure's name in the ABAP Dictionary.
Alternativly, or in addition to this, you can provide the proxy instance with this display
information using an additional internal table. For the sake of simplicity, we will call
this additional table a field catalog. The global data type of this internal table is
LVC_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 the
display of the column position or heading is different.
The internal table has (exclusive or additional) columns that are not contained in
a dictionary structure.
For each column in the data table that deviates from an underlying dictionary structure
or is not available in a dictionary structure, the field catalog must contain a line that
determines the technical characteristics and other column format information.
Figure 142: Grid Structure Options
2005/Q4
© 2005 SAP AG. All rights reserved.
339
Unit 4: ALV Grid Control
TAW10_3
Field catalogs are generated in a number of ways, depending on the line type used
by 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 to
enter the name of the global structure type. Data table columns that are not defined in
the 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/or
additional 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 it
only 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
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 table
type and a line-compatible structure as a work area.
Fill the work area's fields for each relevant column in your data table, and insert
it in the internal table for the field catalog.
Enter a data table column name for the fieldname field. This field is used to assign a
field catalog column to a data table column.
The other fields in the field catalog can be broken down into two groups as regards
usage when setting up a field catalog:
•
•
The reference to global types (structure fields in the ABAP Dictionary) is created
using 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 of
the specified structure fields will be transferred from the ABAP Dictionary. You can
overwrite 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 toenter
valuesfor all fields in the last group.
2005/Q4
© 2005 SAP AG. All rights reserved.
341
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 a
line in the field catalog.
If you want to refer to a field of a global structure type that has the same name, it is
enough to enter the name of this structure in the ref_table field. You only need to
enter the field name from the structure in the ref_field field if the column name of the
data table and structure field name differ.
342
© 2005 SAP AG. All rights reserved.
2005/Q4
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 the
SBOOK type and two others. These must be described in the field catalog, along
with the column to be hidden.
2005/Q4
© 2005 SAP AG. All rights reserved.
343
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 field
description comes from the Dictionary structure(SBOOK), while another part is
explicitly defined in the field catalog (it_fieldcat).
The field catalog (internal table) is filled in the program and is passed on together
with the name of the Dictionary structure during the method call. The information is
merged accordingly in the set_table_for_first_display method.
Note that the fields of the it_sbook data table must also contain useful entries that
cannot be read from the SBOOK table.
If you set up the field catalog semi-automatically or manually, you should check that it
is consistent by double right-clicking in an area of the ALV grid that does not contain
any data (for example, the heading), keeping the Shift key pressed.
344
© 2005 SAP AG. All rights reserved.
2005/Q4
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 taken
into account. Without explicit positioning, fields that are manually attached to the
field catalog are positioned before the other data table fields. Exceptions are always
displayed 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 that
must adhere to the following convention:
C<col_constant> {0|1}{0|1}.In this context, <col_constant> represents a color
constant of the col type group. The second digit determines whether the color will
be 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 selection
dialogs 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
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 and
decimals_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 layout
structure 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
TAW10_3
Lesson: ALV Grid Control - Field Catalog
Facilitated Discussion
Any questions can now be discussed.
Discussion Questions
Use the following questions to engage the participants in the discussion. Feel free to
use your own additional questions.
See list of objectives
2005/Q4
© 2005 SAP AG. All rights reserved.
347
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
TAW10_3
Lesson:
326
Lesson: ALV Grid Control - Layout
ALV Grid Control - Layout
Lesson Duration: 80 Minutes
Lesson Overview
In this lesson you will learn how to change the layout of an ALV Grid Control.
Lesson Objectives
After 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 Example
You are a programmer at ABC Travel. You have been requested to display some lines
in the ALV output in red, depending on the content. Other lines are to be displayed
in orange, again depending on the content. As usual, it is up to you to complete this
difficult 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
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 reference
to 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_display method.
Figure 150: Key Fields of the Layout Structure
350
© 2005 SAP AG. All rights reserved.
2005/Q4
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, users
can 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 the
mouse button pressed.
2005/Q4
© 2005 SAP AG. All rights reserved.
351
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 layout
structure, and pass the layout structure to the is_layout parameter of the
set_table_for_first_display method.
If you enter “X” in the excp_led field of the layout structure, colored LEDs are
displayed instead of the normal traffic light icons.
352
© 2005 SAP AG. All rights reserved.
2005/Q4
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 for
the it_sort parameter of the set_table_for_first_display method. Use the lvc_t_sort
type for this table.
In this internal table, you must insert a line for each field that will be used as a sort
criterion.
•
•
•
2005/Q4
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, you
can also insert the fields in the required sequence in the sort criteria's internal
table.
Enter “X” in the up field, if you wish to sort the the entries in ascending order.
© 2005 SAP AG. All rights reserved.
353
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 is
enough to maintain another field for the color values in the data table. This field should
be the last component of the data table's line type. If the original global structure type
is used as the line type for the ALV Grid Control, the color values are not displayed as
a column on the screen. Instead, only the color required for the line is used.
The INCLUDE TYPE (or INCLUDE STRUCTURE) statement provides a simple
option 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 color
constants of the COL type group that you must incorporate into your program, for
example using the TYPE-POOLS col statement.
In the info_fname field, enter the component name of your color column for a
structure of the global type lvc_s_layo and pass the structure to the parameter
is_layout of the method set_table_for_first_display.
354
© 2005 SAP AG. All rights reserved.
2005/Q4
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 command
FORMAT.
2005/Q4
© 2005 SAP AG. All rights reserved.
355
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, only
some standard functions are useful. You can display either only a subset of the
standard functions, or hide the entire toolbar.
To hide individual functions, define an internal table of the ui_functions type. Fill
the internal table with the name of the functions that are to be kept inactive. Inactive
functions on the application toolbar are not displayed. Inactive functions that are
assigned 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. The
class constants for function codes all have the prefix MC_FC_. The prefix MC_MB_
represents an entire menu in the toolbar.
Finally, pass the table to the standard functions when you call the
set_table_for_first_display method.
To completely deactivate all functions on the application toolbar, you can use the
MC_FC_EXCL_ALL class constant.
To hide the entire toolbar, only set the no_toolbar parameter of the layout structure
to “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 at
a later stage.
356
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
335
Lesson: ALV Grid Control - Layout
Exercise 19: ALV Grid Control - Field
Catalog and Layout
Exercise Duration: Minutes
Exercise Objectives
After 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 Example
Instead of displaying the occupied and maximum spaces for each flight class, the
flight list should now only display one value: The number of free seats. To enhance
readability, the list is to be output with a striped zebra pattern, and the number of free
seats should be indicated using traffic lights.
System Data
System:
Client:
User ID:
Password:
Set up instructions:
1.
Will be announced by trainer
Will be announced by trainer
Will be announced by trainer
Will be announced by trainer
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 seats
for the classes economy, business, and first class will be hidden, and the total number
of free seats displayed instead. To improve readability, a traffic light should appear
in front of each flight, as determined by a threshold value. This light will specify
whether the flight is fully booked, nearly booked, or whether there are still seats
available. This list is also to appear with a zebra pattern.
1.
Use your program from the last exercise or copy the sample solution
TAW10_ALVS_1from the packageBC_TAW10.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
357
Unit 4: ALV Grid Control
358
TAW10_3
2.
Change the definition of your internal table for the flights. Attach the columns
freeseats and lights to the internal table. The freeseats field should have the
same type as the seatsmax table field and the lights field should have a character
field with a length of 1.
3.
In the main program for the ALV Grid Control, create a layout structure and a
field catalog (internal table) with a work area.
4.
During data selection, calculate the total number of free seats for a flight. For
each flight, enter the values 1, 2, or 3 for the lights field, depending on whether
the flight is fully booked, there are only a maximum of 10 seats, or more than
10 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. Take
note of the module sequence. Fill the field catalog so that the free seats appear in
the last column of the list. Hide any other seat-related fields.
6.
In the flow logic, create another module: set_layout output. Create this module
in the main program as well. Fill the layout structure so that a light appears
for each flight, based on the values in the lights column. Format the list in a
striped zebra pattern.
7.
Go to the manage_alv_grid module and pass the field catalog and the layout
structure to the set_table_for_first_display method.
8.
Activate the entire program, start it, and view your list.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: ALV Grid Control - Layout
Solution 19: ALV Grid Control - Field Catalog
and Layout
Task:
Change your list so that the fields with the occupied and maximum number of seats
for the classes economy, business, and first class will be hidden, and the total number
of free seats displayed instead. To improve readability, a traffic light should appear
in front of each flight, as determined by a threshold value. This light will specify
whether the flight is fully booked, nearly booked, or whether there are still seats
available. This list is also to appear with a zebra pattern.
1.
Use your program from the last exercise or copy the sample solution
TAW10_ALVS_1from the packageBC_TAW10.
a)
2.
Change the definition of your internal table for the flights. Attach the columns
freeseats and lights to the internal table. The freeseats field should have the
same type as the seatsmax table field and the lights field should have a character
field with a length of 1.
a)
3.
See the source text in the sample solution.
During data selection, calculate the total number of free seats for a flight. For
each flight, enter the values 1, 2, or 3 for the lights field, depending on whether
the flight is fully booked, there are only a maximum of 10 seats, or more than
10 seats available.
a)
5.
See the source text in the sample solution.
In the main program for the ALV Grid Control, create a layout structure and a
field catalog (internal table) with a work area.
a)
4.
Carry out this step as normal.
See the source text in the sample solution.
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. Take
note of the module sequence. Fill the field catalog so that the free seats appear in
the 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
Unit 4: ALV Grid Control
6.
In the flow logic, create another module: set_layout output. Create this module
in the main program as well. Fill the layout structure so that a light appears
for each flight, based on the values in the lights column. Format the list in a
striped zebra pattern.
a)
7.
See the source text in the sample solution.
Go to the manage_alv_grid module and pass the field catalog and the layout
structure to the set_table_for_first_display method.
a)
8.
TAW10_3
See the source text in the sample solution.
Activate the entire program, start it, and view your list.
a)
Carry out this step as normal.
Result
Solution program:
REPORT
TAW10_ALVS_2
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
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
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
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
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
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
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.
366
" set_field_catalog
© 2005 SAP AG. All rights reserved.
OUTPUT
2005/Q4
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
Unit 4: ALV Grid Control
Lesson:
346
TAW10_3
ALV Grid Control - Events
Lesson Duration: 1 Minutes
Lesson Overview
The ALV Grid Control can also react to user-defined entries. To demonstrate how
this works in principle, in this lesson we will look at how the system reacts to a user
double-clicking the mouse button.
Lesson Objectives
After 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 on
events, which means that a quick overview will suffice. The priority here is for
participants to implement the theory using a practical example. In other words, the
focus here is on the actual exercise.
Business Example
You are a programmer at ABC Reisen. You have been requested to enhance the list so
that when users double-click on a line, a dialog box appears displaying the free seats
for each flight class (economy, business, and first class).
Events for ALV Grid Control - Double-Clicking
An ALV Grid Control can react to a user double-clicking the mouse button. One
possible reaction is that a subsequent processing is triggered in which additional
information is displayed, for example.
368
© 2005 SAP AG. All rights reserved.
2005/Q4
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 or
aircraft data could be displayed in addition to the flight data. From a technical point of
view, the event DOUBLE_CLICK is caught using a handler method.
2005/Q4
© 2005 SAP AG. All rights reserved.
369
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, this
could 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 instance
method. If a class method is defined as a handler method, there is no need to
instantiate 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. This
class has a public method (in the PUBLIC SECTION) that can react to an event. In
the handler method's implementation, create the source text that will run when you
trigger the event. The method receives the information delivered by the event from
the position of the mouse when the user executes a double-click, and in the control
example, generates an information message that displays the line and field where the
mouse is clicked.
370
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
349
Lesson: ALV Grid Control - Events
Exercise 20: ALV Grid Control - Events
Exercise Duration: Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
React to a user mouse-click in the ALV Grid Control
Business Example
When a user double-clicks a line in the flight list, a dialog box should appear displaying
the number of available seats for each flight class (economy, business, and first class).
System Data
System:
Client:
User ID:
Password:
Set up instructions:
1.
Will be announced by trainer
Will be announced by trainer
Will be announced by trainer
Will be announced by trainer
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 box
appears 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 for
the double_click event of the ALV Grid Control (class: CL_GUI_ALV_GRID).
2005/Q4
1.
Use your program from the last exercise or copy the sample solution
TAW10_ALVS_2from the packageBC_TAW10.
2.
In your program, create a local class, and in this class write a handler method for
the on_double_click event of the CL_GUI_ALV_GRID class.
3.
The handler method should provide more information on the number of free
seats for a flight (selected line), by specifying in a dialog box the number of
spaces 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 on
a line in the ALV list.
© 2005 SAP AG. All rights reserved.
371
Unit 4: ALV Grid Control
TAW10_3
Solution 20: ALV Grid Control - Events
Task:
Add the following function to your flight list: When users select a flight, a dialog box
appears 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 for
the 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 solution
TAW10_ALVS_2from the packageBC_TAW10.
a)
2.
In your program, create a local class, and in this class write a handler method for
the on_double_click event of the CL_GUI_ALV_GRID class.
a)
3.
See the source text in the sample solution.
Remember to register for the event at the appropriate location.
a)
5.
See the source text in the sample solution.
The handler method should provide more information on the number of free
seats for a flight (selected line), by specifying in a dialog box the number of
spaces left for each of the categories first, business, and economy class.
a)
4.
Carry out this step as normal.
See the source text in the sample solution.
Activate your program, start it, and test what happens when you double-click on
a line in the ALV list.
a)
Carry out this step as normal.
Result
Solution program:
REPORT
TAW10_ALVS_3
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
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
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
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
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
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
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
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.
2005/Q4
" set_field_catalog
OUTPUT
© 2005 SAP AG. All rights reserved.
379
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
TAW10_3
Unit Summary
Unit Summary
You 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
Unit Summary
382
TAW10_3
© 2005 SAP AG. All rights reserved.
2005/Q4
Unit 5
Exception Handling and RTTS
361
For more information, see the introductory instructor notes in the lesson.
Unit Overview
This unit describes how closely the procedures and object-oriented parts of the
programming language ABAP Objects are integrated, using the new exception concept
and language scope for Run Time Type Services (RTTS) as an example.
Unit Objectives
After 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 Contents
Lesson: Exception Handling in ABAP Objects .................................. 385
Procedure: Define Global Exception Classes .............................. 391
Demonstration: Defining a Global Exception Class........................ 393
Demonstration: Raising, Propagating, and Handling an Exception...... 395
Demonstration: Mapping Other Exceptions to the Original Exception .. 403
Exercise 21: Class-Based Exceptions....................................... 407
2005/Q4
© 2005 SAP AG. All rights reserved.
383
Unit 5: Exception Handling and RTTS
TAW10_3
Exercise 22: (Optional): Mapping Exceptions to Each Other............. 417
Lesson: RTTS (Run Time Type Service) ........................................ 428
Exercise 23: RTTI: Querying Object Attributes ............................. 439
Exercise 24: (Optional): RTTC: Creating Types at Runtime.............. 443
384
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson:
362
Lesson: Exception Handling in ABAP Objects
Exception Handling in ABAP Objects
Lesson Duration: 90 Minutes
Lesson Overview
This lesson provides a comprehensive introduction to the new class-based exception
concept in ABAP Objects. The essential attributes and activities are presented in
detail and then applied in practical examples for SAP Web Application Server 6.20.
Lesson Objectives
After 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 existing
features of ABAP Objects. Naturally, the old exceptions concept can still be used but
they will no longer be developed.
Participants with experience in Java will notice marked similarities in syntax and
runtime behavior. The main point again is to present the additional user-friendly
options available in ABAP Objects and the ABAP Workbench.
In the unlikely event that participants are (still) skeptical about object-oriented
programming, it may be helpful to motivate them with a simple example from
procedural programming: Until now, subroutines could not raise exceptions that
could be handled. Instead, you had to implement a relationship check yourself, using
EXIT (or RETURN as of SAP Web AS 6.10) and auxiliary variables that you had to
define. Now, any processing block in ABAP Objects can raise a class-based exception.
Business Example
You need to use the new exceptions concept in your ABAP Object programs.
2005/Q4
© 2005 SAP AG. All rights reserved.
385
Unit 5: Exception Handling and RTTS
TAW10_3
Class-Based Exception Handling
We use the term exception to refer to a situation that arises while a program is being
executed, 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 to
the existing concept. Exceptions and exception handling are now based on classes.
This concept includes the concepts that preceded it but also enhances (and thus
replaces) them.
Figure 159: An Overview of the Class-Based Exception Concept
Class-based exceptions are raised either by the RAISE EXCEPTION statement or by
the runtime environment. Division by zero, for example, would be an example of an
exception raised by the runtime environment.
In an exception situation, an exception is represented by an exception object - that
is, an instance of an exception class. The attributes of each exception object contain
information about the error situation.
When handling an exception, you can have it raise new exceptions and thus create a
chain of exceptions. Therefore, in special cases, you can catch a runtime exception
and have it raise an exception of its own.
You can define exception classes yourself, but there is already a range of predefined
exception classes in the system, particularly for exceptions in the runtime environment.
You usually create exception classes globally in the Class Builder, but you can also
define local exception classes within a program or global class.
386
© 2005 SAP AG. All rights reserved.
2005/Q4
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. In
particular, all previously catchable runtime errors can now be handled as class-based
exceptions.
If a class-based exception is raised, the system interrupts the normal program flow and
tries to navigate to a suitable handler. If it cannot find a handler, a runtime error occurs.
All exception classes are derived from the one of the classes CX_NO_CHECK,
CX_DYNAMIC_CHECK, or CX_STATIC_CHECK, which are themselves derived
from 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 the
hierarchy 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 all
exception classes:.The GET_SOURCE_POSITION method returns the name of the
main program and (if relevant) the names of the include program and the line number
in the source code where the exception occurred. The GET_TEXT method returns
an exception text in the form of a string.
Newly defined exception classes inherit from one of these superclasses, so other
components can be added. These are usually individual exception texts.
2005/Q4
© 2005 SAP AG. All rights reserved.
387
Unit 5: Exception Handling and RTTS
TAW10_3
You can assign several texts to each class. The IDs assigned to these are created by
the Class Builder as identically named static constants. You can then specify which
text is to be used when an exception is raised by passing one of these constants to the
import parameter TEXTID of the instance constructor.
All exception classes inherit the KERNEL_ERRID attribute from CX_ROOT. This
attribute contains the name of the appropriate runtime error if the exception was
raised by the runtime environment, for example, BCD_ZERODIVIDE if the program
catches a CX_SY_ZERODIVIDE exception (division by zero). If the exception is not
listed, a runtime error occurs.
An exception can only be handled if the statement that could raise it is enclosed in a
TRY-ENDTRY block. The exception is then handled using the CATCH statement in
the TRY-ENDTRY block.
Figure 161: Structure of a TRY-ENDTRY Block
The TRY block contains the set of statements that handle the exceptions. If an
exception occurs in the TRY block, the system searches first for a CATCH statement
in the same TRY-ENDTRY block and then gradually searches outwards in all the
enclosing TRY-ENDTRY blocks that handle the exception. If it finds one, it navigates
to this handler. If it cannot find a handler but the TRY-ENDTRY block is in a
procedure, the system then tries to propagate the exception to the calling program.
A CATCH block contains the exception handler that is executed if a specified
exception has occurred in the associated TRY block. You can specify any number of
exception classes to the CATCH statement. In this way, you define an exception
handler for all these exception classes and their subclasses.
388
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Exception Handling in ABAP Objects
Like all control structures in ABAP Objects, TRY-ENDTRY blocks can be nested
to any depth. Thus the TRY block, CATCH blocks, and the CLEANUP block in
particular can contain complete TRY-ENDTRY blocks.
After an exception occurs, the system searches through the listed exception handlers
in the order specified. It then executes the first exception handler whose CATCH
statement contains the relevant exception class or one of its superclasses.
A CLEANUP block is executed if the TRY-ENDTRY block is exited because the
system cannot find a handler for an exception within a specific TRY-ENDTRY block
but the exception is handled in a surrounding TRY-ENDTRY block or propagated to
a calling program.
In the following sections, we will focus on global exception classes that are handled
locally. Remember, you can also use local exception classes handled locally or global
exception classes handled in methods of other global classes.
Example: Handling a Predefined Exception
There are two special features to note in the following example. First, we will simply
instantiate a standard exception class, rather than define a new one. Second, the
exception will be raised by the runtime system as the result of an error, rather than by
a procedure.
Figure 162: Example Syntax for Handling Predefined Exceptions
2005/Q4
© 2005 SAP AG. All rights reserved.
389
Unit 5: Exception Handling and RTTS
TAW10_3
In the above calculation, if the value range for data type I is exceeded, the runtime
system raises the exception CX_SY_ARITHMETIC_OVERFLOW. This exception is
handled in the implemented CATCH block. The reference to the appropriate instance
is stored in the data object REF_EXC. The handler can then access the instance’s
exception text using the functional method GET_TEXT. The text is stored in the data
object TEXT with the type STRING and then displayed as an information message.
Note: The MESSAGE statement was extended in SAP Web AS 6.10 so that
any string 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 specify
the message type message_type.
If the value range for data type I (information) is not exceeded, no exception is raised
and the TRY block is processed completely. The processing block then continues
executing after the keyword ENDTRY.
The class CX_SY_ARITHMETIC_OVERFLOW is a subclass of the classes
CX_SY_ARITHMETIC_ERROR, CX_DYNAMIC_CHECK, and CX_ROOT. Thus
the exception raised above can also be handled if you enter one of these classes after
the CATCH statement.
Caution: This is a demonstration example that has been deliberately kept
simple. Normally, you would define the RESULT variable with numerical
type F to avoid a runtime error. You could then define the size of the result
value before using MOVE to convert to an integer variable if required.
As with the (obsolete) use of CATCH SYSTEM-EXCEPTIONS, this is also about
catching runtime errors that cannot be entirely excluded. A typical example of this
can be found in widening cast assignments.
The ABAP keyword documentation for each statement lists the classes whose
exceptions may occur when that statement is executed. The following will show you
how to create your own global exception classes.
390
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
368
Lesson: Exception Handling in ABAP Objects
Define Global Exception Classes
1.
In the Class Builder, create a global class as described in the SAP Library. When
you enter its name, use the prefix CX_. Choose the option Exception Class
as the Class Type.
Note: Do not change the default entry for Inherits from superclass
unless 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, for
generic extensions to exception texts).
If these attributes are public, the Class Builder generates an appropriate instance
constructor so that values can be set for these attributes when the exception
is raised. The import parameters are generated with the same names as the
attributes.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
391
Unit 5: Exception Handling and RTTS
3.
TAW10_3
Save as many exception texts as you need. When you do so, you can insert your
attributes as parameters in the static text in the form &<attribute_name>&.
Note: For the first text you create yourself, always use a predefined
static constant as an ID. It always has the same name as the exception
class itself. If no text is specified explicitly when the exception is raised,
the text with this ID is used instead.
For all other texts, define other IDs. The Class Builder then generates identically
named static constants automatically. When the exception is raised, you pass one
of these constants to the import parameter TEXTID to specify the appropriate
text for the exception instance.
Figure 164: Define Variable Exception Texts
Note: The exception texts of global exception classes are stored in their
translations in the Open Text Repository (OTR) . Note that several texts
can be assigned to a single class. You assign a text to an exception
using the TEXTID attribute, which contains the globally unique ID
of the text object in the OTR in an instance at runtime. The method
GET_TEXT then exports this text, replaces any text parameters with the
contents of the relevant attributes as necessary, and returns the text as
a character string.
4.
392
Activate your exception class.
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Exception Handling in ABAP Objects
Demonstration: Defining a Global Exception Class
Purpose
You should make clear how much the system supports developers. When using global
classes they need only add the missing elements that fit their needs. In other words:
You can’t go wrong.
You should also demonstrate how the features of the Class Builder are adapted
automatically when you create an exception class.
System Data
System:
will be assigned
Client:
will be assigned
User ID:
will be assigned
Password:
will be assigned
Set up instructions:
No special settings required if you are using a standard
SAP Web AS 6.20 training system
1. 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 local
class 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 the
attribute PLANETYPE.
5.
Enter a text for the predefined ID, such as: Airplane type ...
unknown..
is
Insert the airplane type generically using the public instance attribute.
6.
Define other public static constants as IDs for another exception text. Suggested
name: CX_BC401_EXCD_PLANETYPE_F.
7.
Define another text for this second ID, such as: Airplane type...
a cargo plane.
is
Insert the airplane type generically using the public instance attribute.
8.
2005/Q4
Activate the exception class
© 2005 SAP AG. All rights reserved.
393
Unit 5: Exception Handling and RTTS
9.
TAW10_3
Sample object in the package BC401:
global class CX_BC401_EXCD_PLANETYPE
Propagating and Handling an Exception
Exceptions that occur in procedures do not necessarily need to be handled where they
occur; they can be propagated to the caller of the procedure. The caller can then
handle the exception itself or propagate it to its own caller, and so on. The highest
levels in which an exception can be propagated are processing blocks without local
data areas, that is, event blocks or dialog modules. The exceptions propagated by the
called procedures must be dealt with there, as must any exceptions raised within this
processing block itself. Otherwise, a runtime error occurs.
To propagate an exception from a procedure, you generally use the RAISING
addition when you are defining the procedure interface. In methods of local classes
and subroutines, specify the RAISING addition directly when you are defining the
procedure:
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. In
methods of global classes, the exception classes whose instances are to be propagated
are entered in the exception table of the method in the Class Builder. You also need
to set the Exception Class flag for each exception table. The process is similar for
function modules. To set the indicator in the Function Builder, choose the Exceptions
tab. A global method or function module can only raise class-based or conventional
exceptions.
394
© 2005 SAP AG. All rights reserved.
2005/Q4
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 constants
defined as additional text IDs in the exception class can also be used to supply the
value. When the exception is raised, the appropriate text for that exception instance
is raised. After the exception has been caught, you can display the text using the
functional method GET_TEXT.
If the caller does not catch the exception, it can be passed upwards to the next-level
caller. Before control is passed to the next-level caller, the optional CLEANUP block
may be executed. You then use this block to run the appropriate statements.
Demonstration: Raising, Propagating, and Handling an
Exception
Purpose
Here you should demonstrate that an actual instance of the exception class is
generated, which the regular object-oriented ABAP Objects syntax elements then
access.
You also show the extended features of the ABAP Debugger as they relate to the
class-based exception concept. By displaying the reference contents, you should be
able to emphasize the object-oriented approach of the new exception concept even
more.
2005/Q4
© 2005 SAP AG. All rights reserved.
395
Unit 5: Exception Handling and RTTS
TAW10_3
System Data
System:
will be assigned
Client:
will be assigned
User ID:
will be assigned
Password:
will be assigned
Set up instructions:
No special settings required if you are using a standard
SAP Web AS 6.20 training system
1. Extend the signature of the method GET_ATTRIBUTES of the local class
LCL_PLANE copied in the previous demonstration program, so that it
propagates an instance of the global exception class.
2.
Raise an exception within the method for both situations 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 class
LCL_CARRIER: Catch the exception when the method GET_ATTRIBUTES is
called and the list is subsequently displayed.
To do this, define a local reference with the type of a global exception class.
We suggest the name L_REF_EXC.
4.
If an exception occurs, export the dynamically-set text and display it in the list
instead of the unsatisfactory entries.
To do so, define a text variable with a suitable type locally. We suggest the
name: L_EXC_TEXT.
396
5.
Activate and execute the program.
6.
Execute the program in debugging mode, thus demonstrating the features of the
ABAP Debugger when an exception is raised.
7.
Sample object in package BC401:
Executable program SAPBC401_EXCD_HANDLE_EXCEP
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Exception Handling in ABAP Objects
Example: Raising, Propagating and Handling an
Exception
CLASS lcl_plane DEFINITION.
PUBLIC SECTION.
...
METHODS get_attributes
EXPORTING
ex_name
TYPE t_name_15
value(ex_wa_plane) TYPE saplane
RAISING
cx_bc401_excd_planetype.
ENDCLASS.
"lcl_plane DEFINITION
CLASS lcl_plane IMPLEMENTATION.
...
METHOD get_attributes.
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.
2005/Q4
"lcl_plane
© 2005 SAP AG. All rights reserved.
397
Unit 5: Exception Handling and RTTS
ENDCLASS.
TAW10_3
"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
TAW10_3
Lesson: Exception Handling in ABAP Objects
ENDMETHOD.
ENDCLASS.
"display_attributes
"lcl_carrier IMPLEMENTATION
The instance method GET_ATTRIBUTES of the local class LCL_PLANE displays
the name and other attributes of the airplane. If the airplane type is not valid, raise and
propagate the exception you defined yourself : CX_BC401_EXCD_PLANETYPE. In
other words, there may be instances of airplanes in this scenario whose type is not
valid. For example, there may be no data for the airplane type in the table SAPLANE
or the airplane may be a cargo plane. The exception class is written so that there is a
separate text available for each of these two situations. In one of the two cases, the
default value is passed to the parameter TEXTID, while in the other an additionally
defined static constant is passed, depending on the cause of the error. In both cases,
the program also passes the invalid airplane type itself to the exception instance.
The exception is handled in the instance method DISPLAY_ATTRIBUTES of
the class LCL_CARRIER. If the exception is raised, execution of the method
GET_ATTRIBUTES terminates and continues with the execution of the CATCH
block. Note that the program no longer executes the WRITE statements entered in the
TRY block after the method call. The system copies the reference to the instance of
the exception class to the local variable L_REF_EXC. The exported error text is set
dynamically so that it contains context-sensitive information.
Hint: It would also have been possible to deal with the two errors by means
of two exception classes. You could then use different CATCH blocks to deal
with whichever of the two errors occurred. However, at this point we wanted
to demonstrate how you would use different texts within one exception class.
Class-Based Exceptions in Debugging Mode
If an exception is raised, the name of the exception class is displayed in the Exception
Raised field in debugging mode.
If this exception is caught using a CATCH block, this is displayed in the form of a
success message. The pointer for the current statement then moves to this CATCH
block.
2005/Q4
© 2005 SAP AG. All rights reserved.
399
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 the
exception instance and navigate to the point in the source code where the exception
occurred.
We advise you to have the participants do the exercise on defining, raising,
propagating, and handling class-based exceptions at this point.
Exception Classes: The Inheritance Hierarchy
The following section explains consequences that arise from the choice of an
exception class’s superclass. It also demonstrates how the exceptions in the runtime
system are integrated into the inheritance hierarchy of the exception classes.
400
© 2005 SAP AG. All rights reserved.
2005/Q4
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 be
handled or propagated explicitly using the RAISING addition. If this is not the case,
the syntax check displays a warning. If you define your own exception classes,
CX_STATIC_CHECK is defined as the superclass by default.
The rule for subclasses of CX_DYNAMIC_CHECK also applies to subclasses of
CX_DYNAMIC_CHECK. You must either handle them or explicitly propagate them
using the RAISING addition. The difference is that this is not 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 this
situation are the predefined exceptions CX_SY_... for errors that occur in the
runtime environment. These are usually subclasses of CX_DYNAMIC_CHECK.For
subclasses of CX_NO_CHECK, the rule is that the corresponding exceptions cannot
be propagated explicitly using the RAISING addition. These exceptions can be
handled. Otherwise, they are automatically propagated. Neither a syntax warning nor
a runtime error is caused directly where it is raised. Instead, all exceptions that are not
handled somewhere in the call hierarchy are propagated up to the highest call level.
If it is not caught there either, a runtime error occurs at that point. Some predefined
exceptions with the prefix CX_SY_... for error situations in the runtime environment
are subclasses of CX_NO_CHECK.
. Nn w. u.
2005/Q4
© 2005 SAP AG. All rights reserved.
401
Unit 5: Exception Handling and RTTS
TAW10_3
Mapping Exceptions to Each Other
For the sake of clarity, you should understand that an exception can be propagated
through any number of call hierarchies before it is finally handled.
The following section shows how the raising of different exceptions can be interlinked
or chained. One exception can raise a second, and so on. Each instance should remain
valid, regardless of whether or not the associated CATCH block has already been
left or not. In this respect, you must make sure that the previous exception instance
can always be accessed by means of at least one reference. The public instance
attribute PREVIOUS, inherited by all exception classes from CX_ROOT, provides a
convenient way of doing this.
Figure 168: Mapping Exceptions to Each Other
When raising the next exception, only one reference to the previous exception
instance must be passed to the new instance. You do this with the optional parameter
PREVIOUS of the instance constructor – that is, using RAISE EXCEPTION. In
this way, the new exception is mapped to the previous one. After the mapped
exception has been caught, the instance attribute PREVIOUS contains a reference to
the previous exception instance, and so on. In this way, you can access each instance
in the chain of exceptions. Therefore, you can follow the history of the raising of
the exceptions in the program.
402
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Exception Handling in ABAP Objects
Demonstration: Mapping Other Exceptions to the
Original Exception
Purpose
You should make clear how easy it is to get a reference to the previous exception
instance in a chain of exceptions using the public attribute PREVIOUS.
Caution: At this point, remind participants that chained exceptions must not
be confused with one exception that is passed up several call levels.
System Data
System:
will be assigned
Client:
will be assigned
User ID:
will be assigned
Password:
will be assigned
Set up instructions:
No special settings required if you are using a standard
SAP Web AS 6.20 training system
1. 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 or
her that at least one error situation could occur. Another information message
should then display the text of the original exception. The list should then be
displayed for the invalid airplane type, but not for those that follow it.
3.
Create an exception class. Derive it from superclass CX_STATIC_CHECK.
4.
Enter a text for the predefined ID, such as: The list contains errors.
5.
Extend the signature of the method DISPLAY_ATTRIBUTES of the local class
LCL_CARRIER in the demonstration program, so that it propagates an instance
of the global exception class.
6.
Have the method raise an exception if the original exception is caught for the
invalid airplane type.
Set the reference to point to the instance of this original exception (
previous = local_ref_to_prev_exc).
7.
2005/Q4
Handle the exception in the main program: Catch the exception when the method
DISPLAY_ATTRIBUTES of the local class .LCL_CARRIER is called
© 2005 SAP AG. All rights reserved.
403
Unit 5: Exception Handling and RTTS
TAW10_3
To do this, define a reference in the main program with the type of a global
exception class. We suggest the name REF_EXC.
8.
If the exception occurs, export the dynamically specified text and display it
as an information message.
To do so, define a text variable with a suitable type in the main program. We
suggest the name: EXC_TEXT
Then export the reference to the original exception instance by accessing the
appropriate attribute.
Use this reference to export the text from the original exception and display it
as an information message.
To do so, define a text variable with a suitable type in the main program.
Suggested name: PREVIOUS_TEXT
9.
Activate and execute the program.
10. Execute the program in debugging mode, showing the content of the PREVIOUS
attribute and of the references to the different exception instances.
11. Sample objects in package BC401:
•
•
Global class CX_BC401_EXCD_LIST
Executable program SAPBC401_EXCD_GET_PREVIOUS
Example: Creating a Chain of Exceptions
As in the previous example, the method GET_ATTRIBUTES has been defined
and 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.
404
"lcl_carrier DEFINITION
© 2005 SAP AG. All rights reserved.
2005/Q4
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
exc_text
2005/Q4
TYPE REF TO cx_bc401_excd_list,
TYPE string,
© 2005 SAP AG. All rights reserved.
405
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 method
DISPLAY_ATTRIBUTES of the class LCL_CARRIER. The exception text is
displayed in the list. Another exception is then raised, since the list now contains
errors. The reference to the first exception instance is passed to the second.
The exception for the list with the errors is now handled in the main program. First, the
exception text is displayed as an information message. However, since the exception
is mapped to a second exception for the invalid airplane type, the instance attribute
PREVIOUS contains a reference to the second exception. You use this reference to
export the text from the original exception and display it as an information message.
Since the method DISPLAY_ATTRIBUTES propagates its exception to the main
program, the system stops list processing within the DISPLAY_ATTRIBUTES
method as soon as the first error occurs.
Hint: It would also be possible to propagate the original exception from the
method DISPLAY_ATTRIBUTES. We would not then have had to define two
exception classes explicitly. However, the point of this example is to show
how exceptions can be chained.
406
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
381
Lesson: Exception Handling in ABAP Objects
Exercise 21: Class-Based Exceptions
Exercise Duration: 45 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Define global exception classes
•
Raise class-based exceptions
•
Propagate class-based exceptions
•
Handle class-based exceptions
Business Example
Your airplane management program should use the class-based exception concept if
an invalid airplane type occurs. An error text should be displayed in the list, instead of
the current default values.
System Data
System:
Client:
User ID:
Password:
Set up instructions:
SAP Web AS 6.20 system
will be assigned
will be assigned
will be assigned
will be assigned
No special settings required if you are using a standard
Task 1:
Create a global exception class for an invalid airplane type.
1.
Create a global exception class called ZCX_##_INVALID_PLANETYPE
(where ## is your two-digit group number). Choose the superclass so that the
syntax check determines if the relevant exception is handled after it is raised or
if it is explicitly propagated.
2.
Add an attribute for the airplane type (suggested name: PLANETYPE) and
assign the type S_PLANETYPE to it.
3.
Create a default error message that can be enhanced dynamically to include
the airplane type.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
407
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 from
the airplane management program, SAPBC401_EVES_MAIN_B.
2.
Raise your exception within method ET_TECHNICAL_ATTRIBUTES of local
class LCL_AIRPLANE.
Ensure that the invalid airplane type is copied into the attribute of the exception
instance.
3.
Make sure that the raised exception is explicitly propagated.
Task 3:
Handle the raised exception.
1.
Catch your exception in the DISPLAY_ATTRIBUTES method of local class
LCL_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 data
type STRING.
408
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Exception Handling in ABAP Objects
Solution 21: Class-Based Exceptions
Task 1:
Create a global exception class for an invalid airplane type.
1.
2.
Create a global exception class called ZCX_##_INVALID_PLANETYPE
(where ## is your two-digit group number). Choose the superclass so that the
syntax check determines if the relevant exception is handled after it is raised or
if it is explicitly propagated.
a)
Follow the processes as outlined in the relevant section of this lesson.
b)
Model solution: CX_BC401_INVALID_PLANETYPE
Add an attribute for the airplane type (suggested name: PLANETYPE) and
assign the type S_PLANETYPE to it.
a)
3.
Follow the processes as outlined in the relevant section of this lesson.
Create a default error message that can be enhanced dynamically to include
the airplane type.
a)
Follow the processes as outlined in the relevant section of this lesson.
Task 2:
Raise your new exception if an error occurs.
1.
2.
Complete your ZBC401_##_MAIN program or copy the model solution from
the airplane management program, SAPBC401_EVES_MAIN_B.
a)
Additional information is available in the SAP Library.
b)
Model solution: SAPBC401_EXCS_RAISE_TRY
Raise your exception within method ET_TECHNICAL_ATTRIBUTES of local
class LCL_AIRPLANE.
Ensure that the invalid airplane type is copied into the attribute of the exception
instance.
a)
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
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 class
LCL_AIRPLANE.
Define a local reference variable for this purpose (suggested name:
R_EXCEPTION) and assign it to the CX_ROOT class.
a)
2.
See the source code extract from the model solution.
Read the error text in the exception instance and display it in the ABAP list.
Define a variable for this purpose (suggested name: EXC_TEXT) with data
type STRING.
a)
See the source code extract from the model solution.
Result
Source 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
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
EXPORTING ex_weight
ex_tankcap
RAISING
DATA: name
TYPE saplane-planetype
TYPE s_plan_wei
TYPE s_capacity
cx_bc401_invalid_planetype.
TYPE string,
planetype TYPE saplane-planetype.
CLASS-DATA: n_o_airplanes TYPE i.
ENDCLASS.
"lcl_airplane DEFINITION
*------------------------------------------------------------------*
*
CLASS lcl_airplane IMPLEMENTATION
*
*------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
name
= im_name.
planetype
= im_planetype.
n_o_airplanes = n_o_airplanes + 1.
RAISE EVENT airplane_created.
ENDMETHOD.
"constructor
METHOD display_attributes.
DATA: weight TYPE saplane-weight,
cap TYPE saplane-tankcap,
r_exception TYPE REF TO cx_root,
exc_text TYPE string.
WRITE: / icon_ws_plane AS ICON,
/ ’Name of Airplane’(001), AT pos_1 name,
/ ’Type of airplane: ’(002), AT pos_1 planetype.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
411
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
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.
ENDCLASS.
"display_attributes
"lcl_cargo_plane IMPLEMENTATION
*---------------------------------------------------------------------*
*
CLASS lcl_passenger_plane DEFINITION
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..
PUBLIC SECTION.
METHODS: constructor IMPORTING im_name TYPE string
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
413
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
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
Unit 5: Exception Handling and RTTS
TAW10_3
METHOD get_name.
ex_name = name.
ENDMETHOD.
ENDCLASS.
416
"get_name
"lcl_carrier IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
391
Lesson: Exception Handling in ABAP Objects
Exercise 22: (Optional): Mapping
Exceptions to Each Other
Exercise Duration: 45 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Define local exception classes
•
Map an exception, when it is raised, to another exception that has already
been raised
•
When handling a mapped exception, evaluate the previous exception as well
Business Example
If your airplane management program encounters an exception and displays an error on
the list, another exception should be raised. The second exception should refer to the
first exception so that both instances can be evaluated when the exception is handled.
System Data
System:
Client:
User ID:
Password:
Set up instructions:
SAP Web AS 6.20 system
will be assigned
will be assigned
will be assigned
will be assigned
No special settings required if you are using a standard
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 from
the previous exercise, SAPBC401_EXCS_RAISE_TRY.
2.
To make your program easier to maintain, create another include program for
your exception class and include it in your main program (suggested name:
ZBC401_##_EXCEPTION).
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
417
Unit 5: Exception Handling and RTTS
3.
TAW10_3
Define a local exception class in your new include program. The exception is
needed in case exception handling takes place when the list is output (suggested
name: LCX_LIST_ERROR).
Hint: Your local exception class should derive from the superclass
CX_STATIC_CHECK.
4.
Add a public instance method to your local exception class. This method returns
a special text appropriate to the error that may occur: for example, “The list
contains an error.” (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 class
LCL_AIRPLANE when the exception for the invalid airplane type is being
handled.
Transfer the reference to the original exception instance to the exception instance
that is to be created.
2.
Extend the signature of the DISPLAY_ATTRIBUTES method so that your new
exception is explicitly propagated.
Task 3:
Handle your new exception and evaluate the information of both the new and the
original exception instance.
1.
Catch your new exception in the DISPLAY_AIRPLANES method of local
class LCL_CARRIER. Define a local reference variable for the purpose with a
suitable type (suggested name: R_EXC).
2.
Use this reference to export the text of your new exception. Define a text variable
for this purpose with an appropriate type (suggested name: EXC_TEXT).
If an exception occurs, display the text of your new exception as well the old
one, in the form of an information message.
3.
Use the same variables to export the text of the original exception.
Enter this text in form of an information message.
418
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Exception Handling in ABAP Objects
Solution 22: (Optional): Mapping Exceptions
to Each Other
Task 1:
Define a local exception class for the event of an error text being displayed in the list.
1.
2.
Complete your ZBC401_##_MAIN program or copy the model solution from
the previous exercise, SAPBC401_EXCS_RAISE_TRY.
a)
Additional information is available in the SAP Library.
b)
Model solution: SAPBC401_EXCS_RAISE_TRY_OPT
To make your program easier to maintain, create another include program for
your exception class and include it in your main program (suggested name:
ZBC401_##_EXCEPTION).
a)
3.
Additional information is available in the SAP Library.
Define a local exception class in your new include program. The exception is
needed in case exception handling takes place when the list is output (suggested
name: LCX_LIST_ERROR).
Hint: Your local exception class should derive from the superclass
CX_STATIC_CHECK.
a)
4.
See the source code extract from the model solution.
Add a public instance method to your local exception class. This method returns
a special text appropriate to the error that may occur: for example, “The list
contains an error.” (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 class
LCL_AIRPLANE when the exception for the invalid airplane type is being
handled.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
419
Unit 5: Exception Handling and RTTS
TAW10_3
Transfer the reference to the original exception instance to the exception instance
that is to be created.
a)
2.
See the source code extract from the model solution.
Extend the signature of the DISPLAY_ATTRIBUTES method so that your new
exception is explicitly propagated.
a)
See the source code extract from the model solution.
Task 3:
Handle your new exception and evaluate the information of both the new and the
original exception instance.
1.
Catch your new exception in the DISPLAY_AIRPLANES method of local
class LCL_CARRIER. Define a local reference variable for the purpose with a
suitable type (suggested name: R_EXC).
a)
2.
See the source code extract from the model solution.
Use this reference to export the text of your new exception. Define a text variable
for this purpose with an appropriate type (suggested name: EXC_TEXT).
If an exception occurs, display the text of your new exception as well the old
one, in the form of an information message.
a)
3.
See the source code extract from the model solution.
Use the same variables to export the text of the original exception.
Enter this text in form of an information message.
a)
See the source code extract from the model solution.
Result
Source 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
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
Unit 5: Exception Handling and RTTS
TAW10_3
*
*---------------------------------------------------------------------*
CLASS lcx_list_error IMPLEMENTATION.
METHOD get_exc_text.
result = ’The list contains an error.’(err).
"get_text
ENDMETHOD.
"lcx_list_error IMPLEMENTATION
ENDCLASS.
BC401_EXCS_RAISE_TRY_CL2
*&---------------------------------------------------------------------*
*&
Include
BC401_EXCS_RAISE_TRY_CL2
*
*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
*
CLASS lcl_airplane DEFINITION
*
*------------------------------------------------------------------*
CLASS lcl_airplane DEFINITION.
PUBLIC SECTION.
"--------------------------------------------CONSTANTS: pos_1 TYPE i VALUE 30.
METHODS: constructor IMPORTING
im_name
TYPE string
im_planetype TYPE saplane-planetype.
METHODS: display_attributes
RAISING lcx_list_error.
CLASS-METHODS: display_n_o_airplanes.
EVENTS: airplane_created.
PRIVATE SECTION.
"---------------------------------------------METHODS: get_technical_attributes
IMPORTING im_type
TYPE saplane-planetype
EXPORTING ex_weight
TYPE s_plan_wei
Continued on next page
422
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Exception Handling in ABAP Objects
ex_tankcap
RAISING
DATA: name
TYPE s_capacity
cx_bc401_invalid_planetype.
TYPE string,
planetype TYPE saplane-planetype.
CLASS-DATA: n_o_airplanes TYPE i.
ENDCLASS.
"lcl_airplane DEFINITION
*------------------------------------------------------------------*
*
CLASS lcl_airplane IMPLEMENTATION
*
*------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
...
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
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
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
Unit 5: Exception Handling and RTTS
ENDMETHOD.
TAW10_3
"constructor
METHOD get_name.
...
ENDMETHOD.
ENDCLASS.
426
"get_name
"lcl_carrier IMPLEMENTATION
© 2005 SAP AG. All rights reserved.
2005/Q4
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 Information
For more information, refer to the SAP Library and the key word documentation
for the individual statements.
2005/Q4
© 2005 SAP AG. All rights reserved.
427
Unit 5: Exception Handling and RTTS
Lesson:
402
TAW10_3
RTTS (Run Time Type Service)
Lesson Duration: 120 Minutes
Lesson Overview
As of SAP Web AS 6.10, ABAP Objects enables you to query type attributes at
runtime 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 Run
Time Type Creation [RTTC] types dynamically at runtime. The combination of both
concepts forms the (Run Time Type Services [RTTS]).
Lesson Objectives
After 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 and
object-oriented features. The procedural parts of ABAP Objects must always be used
in classes, that is, in object-oriented contexts.
However, certain concepts (for example, Run Time Type Identification, Business
Add 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 the
object-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 a
number of problems that were initially left open.
Business Example
An airline wants to identify all its cargo planes.
428
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: RTTS (Run Time Type Service)
RTTI/
Type Analysis at Runtime
In 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 includes
all ABAP types, and thus covers all of the functions of the now obsolete statements
DESCRIBE FIELD and DESCRIBE TABLE.
There is a description class for each type with special attributes for special type
attributes.
Figure 169: Dynamic Type Analysis for RTTI Classes
The class hierarchy of the description classes corresponds to the hierarchy of the types
of ABAP Objects. In addition, the description classes for complex types, references,
classes, and interfaces have special methods that are used to specify references to
subtypes. You can use these methods to navigate through a compound type to all
its subtypes.
To obtain a reference to a description object of a type, you must use the static methods
of the class CL_ABAP_TYPEDESCR or the navigation methods of the special
description class. The description objects are then created from one of the subclasses.
At runtime, exactly one description object exists for each type. The attributes of the
description object contain information on the attributes of the type.
2005/Q4
© 2005 SAP AG. All rights reserved.
429
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 identified
using RTTI. The subclass CL_ABAP_STRUCTDESCR is used for this purpose.
430
© 2005 SAP AG. All rights reserved.
2005/Q4
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 the
appropriate description class. Instances of this class have a COMPONENTS attribute
that you use to describe the individual components of the relevant structure. This
attribute is an internal table. Therefore, you also need to define a work area with
a compatible line type.
The functional method call returns the reference to the description instance of the
transferred structure. Note: You would also have been able to create the WA structure
dynamically. In this example, it is static as usual.
The abstract class CL_ABAP_TYPEDESCR contains the static method
DESCRIBE_BY_DATA. Its RETURNING parameter is typed as a reference to this
superclass. However, since the actual parameter R_DESCR is typed on the subclass
CL_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 this
example, the component names are displayed as the column headers (for the sake of
clarity, we have omitted the formatting options).
2005/Q4
© 2005 SAP AG. All rights reserved.
431
Unit 5: Exception Handling and RTTS
TAW10_3
If you have enough time, we recommend that you demonstrate extracts from
SAPBC401_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. Demonstrate
the reference SENDER of the handler method ADD_VEHICLE for the class
LCL_RENTAL as your example.
Figure 172: RTTI: Querying Object-Type Attributes
As an example, you should enhance the existing application with the travel agency and its business partner.
In the previous example, we specified that an instance of the
LCL_RENTAL vehicle rental class reacts to an event by including the vehicle
instance 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 only
interested in buses.
432
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: RTTS (Run Time Type Service)
The reference to the triggering vehicle instance is contained in the SENDER parameter
of the aforementioned event handler method. Its dynamic object type is to be analyzed
to determine whether the vehicle in question is a bus or a truck.
A functional RTTI method call returns the reference to the description instance of
the transferred vehicle instance.
The abstract class CL_ABAP_TYPEDESCR has this DESCRIBE_BY_OBJECT_REF
method. Its returning parameter is typed as a reference to this superclass.
However, since the actual parameter R_DESCR is typed on the subclass
CL_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. The
functional 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 to
a reference variable that has a LCL_BUS static type. This would result in a
runtime error for vehicle instances that are not buses. The system could then
catch this runtime error. Therefore, a runtime error not being triggered would
be the criterion for including a vehicle in the vehicle list.
RTTC/
Type Creation at Runtime
In SAP Web AS 6.40, RTTC was added to the RTTI type classes to facilitate the
creation of types at runtime.
The properties of the types are implemented by type-object attributes. This means that
each type has a type object whose attributes describe the properties of the type.
2005/Q4
© 2005 SAP AG. All rights reserved.
433
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 the
ABAP type system. Type objects can be created by the type class methods. To
obtain references to type objects, you can call specific static methods for the class
CL_ABAP_TYPEDESCR or methods of the special type classes (GET_I, GET_C,
CREATE).
434
© 2005 SAP AG. All rights reserved.
2005/Q4
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 create
more complex data types such as structures or internal tables.
2005/Q4
© 2005 SAP AG. All rights reserved.
435
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 to
create an internal table type at runtime. The parameter P_LINE_TYPE is an important
formal parameter of this static method. This parameter describes the line type using a
reference to the CL_ABAP_STRUCTDESCR. In the example provided here, SPFLI
is used as the line type. The method DESCRIBE_BY_NAME instantiates a suitable
object for this (the ABAP_TRUE parameter from the sample program originates from
a type pool that is used internally in the RTTC classes).
The question that now arises is what you should technically do with the table type
that has just been created. For instance, you could use it as an example of creating an
internal 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
TAW10_3
Lesson: RTTS (Run Time Type Service)
Using the HANDLE addition, the CREATE DATA statement in the example creates
an internal table whose type is described by an RTTS type object. A reference variable
from the static type of the CL_ABAP_TABLEDESCR class that refers to a type object
is specified for the HANDLE. The type object may have been created on the existing
data 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 usually
find it overwhelming, also make sure that you refer to the corresponding relevant areas
relating to RTTI and RTTC in the documentation so that the participants know that
they can always refer to it themselves at a later stage. Ideally, the instructor should
first show how the participants can access the documentation.
Also make sure that you clearly communicate in advance that this topic will not be
covered completely in this course. It is only an overview of the subject matter. Inform
the 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 out
the second optional exercise. Dynamically creating data objects at runtime is a new
area for many participants and the second exercise will impress the participants with
the options available with ABAP-OO. If you have a tight schedule, however, we
recommend that you theoretically discuss the new RTTS features for 6.40.
2005/Q4
© 2005 SAP AG. All rights reserved.
437
Unit 5: Exception Handling and RTTS
438
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
TAW10_3
411
Lesson: RTTS (Run Time Type Service)
Exercise 23: RTTI: Querying Object
Attributes
Exercise Duration: 30 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Query attributes of objects at runtime using RTTI
Business Example
In the program for the travel agency model, the airline (LCL_CARRIER) wants to
determine 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 change
your previous program. A prerequisite for this is the exercise you completed for
the 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 of
the 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 error
for a widening cast because the type of reference variable can be determined in
advance using an appropriate RTTI call.
2005/Q4
© 2005 SAP AG. All rights reserved.
439
Unit 5: Exception Handling and RTTS
TAW10_3
Solution 23: RTTI: Querying Object
Attributes
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 change
your previous program. A prerequisite for this is the exercise you completed for
the 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)
2.
Copy the copy template in the usual manner or continue to work with
your old program.
RTTI should now solve the method GET_HIGHEST_CARGO created in one of
the 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
TAW10_3
Lesson: RTTS (Run Time Type Service)
This specifically means that you now no longer need to catch the runtime error
for a widening cast because the type of reference variable can be determined in
advance 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
Unit 5: Exception Handling and RTTS
442
© 2005 SAP AG. All rights reserved.
TAW10_3
2005/Q4
TAW10_3
415
Lesson: RTTS (Run Time Type Service)
Exercise 24: (Optional): RTTC: Creating
Types at Runtime
Exercise Duration: 30 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Create and use an internal table type at runtime
Business Example
You want to add an RTTC call, used for creating a type, to a current program. The
program in question also demonstrates dynamic programming, which means that it
reacts 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 a
DB table selected by the user (this is a data browser function).
Define the required reference variables for this and use the corresponding RTTC
functions to create this table type.
Based on this type, you should then create an internal table dynamically at
runtime and display it using an ALV Grid Control. The template to be copied
already contains the relevant lines for this display.
2005/Q4
© 2005 SAP AG. All rights reserved.
443
Unit 5: Exception Handling and RTTS
TAW10_3
Solution 24: (Optional): RTTC: Creating
Types at Runtime
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.
a)
Model solution: SAPBC401_DYNS_RTTS_2
2.
At runtime, use RTTC to create a table type dynamically to display the data of a
DB table selected by the user (this is a data browser function).
Define the required reference variables for this and use the corresponding RTTC
functions to create this table type.
Based on this type, you should then create an internal table dynamically at
runtime and display it using an ALV Grid Control. The template to be copied
already 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
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
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
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
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
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
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
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
Unit 5: Exception Handling and RTTS
titel
TAW10_3
= 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
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
Unit Summary
TAW10_3
Unit 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
•
Query type attributes at runtime
•
Create types dynamically
454
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
427
Test Your Knowledge
Test Your Knowledge
1.
The new exception concept replaces the old one. Thus, all old source code
sections must be rewritten. As of SAP Web AS 6.20, function modules from the
SAP standard system automatically raise object-oriented exceptions.
Determine whether this statement is true or false.
□
□
2.
True
False
Unlike the old exceptions, those embodying the new concept can also be raised
from subroutines and propagated.
Determine whether this statement is true or false.
□
□
3.
True
False
The new exception classes can only be defined globally. This ensures central
maintenance and reuse.
Determine whether this statement is true or false.
□
□
4.
True
False
When you define an exception class, the superclass you choose specifies whether
or not its exceptions must be caught explicitly with a TRY-CATCH-ENDTRY
block and, if so, how the system reacts if the exception is not caught.
Determine whether this statement is true or false.
□
□
2005/Q4
True
False
© 2005 SAP AG. All rights reserved.
455
Test Your Knowledge
428
TAW10_3
Answers
1.
The new exception concept replaces the old one. Thus, all old source code
sections must be rewritten. As of SAP Web AS 6.20, function modules from the
SAP standard system automatically raise object-oriented exceptions.
Answer: False
2.
Unlike the old exceptions, those embodying the new concept can also be raised
from subroutines and propagated.
Answer: True
3.
The new exception classes can only be defined globally. This ensures central
maintenance and reuse.
Answer: False
4.
When you define an exception class, the superclass you choose specifies whether
or not its exceptions must be caught explicitly with a TRY-CATCH-ENDTRY
block and, if so, how the system reacts if the exception is not caught.
Answer: True
456
© 2005 SAP AG. All rights reserved.
2005/Q4
Unit 6
Shared Objects
429
For more information, see the introductory instructor notes in the lesson.
Unit Overview
This unit focuses on a data-storage mechanism that enables you to store data on an
application server that can be accessed by all users, hence the term Shared Objects.
Unit Objectives
After 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 Contents
Lesson: Shared Objects ........................................................... 458
Exercise 25: Using Shared Objects .......................................... 481
2005/Q4
© 2005 SAP AG. All rights reserved.
457
Unit 6: Shared Objects
Lesson:
430
TAW10_3
Shared Objects
Lesson Duration: 60 Minutes
Lesson Overview
Starting 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 can
access this data quickly, independently of the user session. This technique was
developed with the primary objective of saving catalog information and shopping
carts. An attribute of catalogs is that they are read often, but only changed rarely. In
the case of the shopping cart, the data is written by one application and then read by
another program at a different time (in a different user session). Here as well, this
technique delivers considerably better performance than saving the data persistently in
the database.
Lesson Objectives
After 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 relevant
for 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 Example
Mr. Jones is a software developer at a major corporation that develops proprietary
business applications in ABAP. He is asked to develop a flexible new application for
flight bookings. One requirement of the application is that many employees must be
able to access the same customer data simultaneously, without having to read this data
from the database each time. Mr. Jones knows that shared objects can be used to make
data in main memory accessible across session boundaries. He therefore uses shared
objects to develop his flight booking application.
458
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Shared Objects
Introducing Shared Objects
Starting 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 can
create applications in which users write data to this area. Other users can then read
this 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 then
access this catalog at the same time.
•
Saving a shopping cart
The buyer fills the shopping cart and the seller reads it later.
Shared Memory
Shared memory is a memory area on an application server that can be accessed by all
the 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 and
IMPORT statements with the SHARED BUFFER and SHARED MEMORY additions to
access this memory area. Instances of classes "lived" exclusively in the internal session
2005/Q4
© 2005 SAP AG. All rights reserved.
459
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 shared
objects 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)
•
•
•
•
460
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
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Shared Objects
The write accesses should be seldom because writing data to the shared objects area is
performance-intensive. Specifically, you want to optimize runtime, which would be
lost if write access were more frequent.
Note: SAP also uses shared objects in SAP Web AS 6.40. For example, this
technique is used to navigate in the ABAP Workbench. In addition to saving
memory (around 3 MB per user logon), navigation during the first access is
faster by up to a factor of 100.
A prerequisite for saving an object in shared memory is that the class of that object is
defined 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 spawn
several area instances, which differ by name. In addition, an area instance can have
several versions (“area instance versions”), which differ in their version IDs. In the
simplest case, without version management, an area instance consists of a single
area instance version.
2005/Q4
© 2005 SAP AG. All rights reserved.
461
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 the
same name. This is a subclass of CL_SHM_AREA. In an ABAP program, the area is
accessed exclusively using methods of the generated area class.
Hint: Because the area and area class have the same name, it makes sense to
name the area according to the naming conventions for classes – ZCL_*, for
example, in the customer namespace.
You can use static methods (“Attach” methods) of an area class to attach an ABAP
program (or its internal session, where the ABAP program is processed) to an area
instance in shared memory. When you attach an ABAP program, an instance of the
area class is created as an area handle.
The above diagram also shows another class, which is called the area root class. You
can create any number of objects in an area instance, depending on your specific
program. You access these objects uniformly through the instance of the area root
class.
Note: We will limit ourselves to two classes in a specific example.
462
© 2005 SAP AG. All rights reserved.
2005/Q4
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 want
to use shared objects to create a catalog of flight dates, where the users can select
any flight quickly.
2005/Q4
© 2005 SAP AG. All rights reserved.
463
Unit 6: Shared Objects
TAW10_3
Figure 181: Accessing Areas
The diagram again illustrates the fact that any programs can access objects in the
shared objects memory. In this case, two applications, which run in different user
sessions, access objects in the same area. Therefore, we will need several things for
the example application:
•
•
•
Creating an area
Developing a program to create an area instance
Developing a program to read data from the area
Creating an Area
Shared objects are saved in areas of shared memory. You use transaction SHMA to
create and manage areas and their attributes.
464
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Shared Objects
Figure 182: Area Management
Hint: Please note that you have to call transaction code SHMA directly in
SAP 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 namespace
rules apply, which means the area name has to start with Y or Z in the customer
system. Namespaces containing slashes are also supported.
Hint: Note that a global, final area class with the same name as the area is
also created as a subclass of CL_SHM_AREA. Therefore, it makes sense to
choose the area name wisely, as shown in our example.
In an ABAP program, the area will be accessed later exclusively using methods of
the generated area class.
2005/Q4
© 2005 SAP AG. All rights reserved.
465
Unit 6: Shared Objects
TAW10_3
Figure 183: Maintaining Areas
Create,
After you press the
screen for areas appears.
Change, or
Display button, the maintenance
Each area is linked with a global area root class, whose attributes can contain
proprietary data and references to other shared memory-enabled classes. You have to
assign the area root class to an area when you maintain it. If an area instance version is
not 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 ROOT
attribute is generated and typed with the static type of the area root class.
Other Important Terms for Creating an Area
Client-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 active
client by default. You can use the optional importing parameter CLIENT to
access another client explicitly.
466
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Shared Objects
Transactional area
An area instance version of a transactional area is not active immediately after
you remove a change lock with the DETACH_COMMIT method; it is not active
until the next database commit.
This is particularly helpful in implementing shopping carts in the shared objects
memory.
Setting Up an Area Instance
In the last section, we defined an area. We also created the classes that will be
instantiated in this area. In this section, we will examine the statements that we can
use 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. To
set up an area or access an existing area, you need a reference variable that is typed
with the generated area class. This reference serves as a handle for accessing the area.
2005/Q4
© 2005 SAP AG. All rights reserved.
467
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 shared
memory. The program has a handle for this instance of the area; all future operations
are performed using this handle.
468
© 2005 SAP AG. All rights reserved.
2005/Q4
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 objects
memory. To do so, use the AREA HANDLE addition for the CREATE OBJECT
statement. This tells the system the area instance where the objects shall be created.
2005/Q4
© 2005 SAP AG. All rights reserved.
469
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 other
objects 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
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 assign
the root object to the ROOT attribute of the area handle. To do so, you use the
SET_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 then
immediately access the objects contained in that area instance.
2005/Q4
© 2005 SAP AG. All rights reserved.
471
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 from
class CL_SHM_AREA.
Accessing an Area Instance
Once 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
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 performed
using method ATTACH_FOR_READ, which class CL_SHM_AREA provides. This
sets 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
Unit 6: Shared Objects
TAW10_3
Figure 191: Cancelling the Read Lock
Once the read activity is complete, the application releases the read lock. Method
DETACH of the area handle is available for this purpose. The read lock is also released
automatically when the internal session is closed.
States of Area Instance Versions
When you create an area, you can specify that several versions of an area instance are
allowed. 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
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, the
area instance version is active.
2005/Q4
© 2005 SAP AG. All rights reserved.
475
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 versions
of 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 area
instance exist concurrently. As soon as an application sets a change lock for an area
instance, a “version being set up” is created and exists in parallel to the active version.
476
© 2005 SAP AG. All rights reserved.
2005/Q4
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 currently
active version, the version being set up becomes active. The previously active version
is given the attribute Outdated.
2005/Q4
© 2005 SAP AG. All rights reserved.
477
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
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 version
expires. It is then deleted by the garbage collector. You cannot set any locks for
expired versions, nor are they used to determine the number of versions (the latter is
important if the number of area instance versions has been restricted).
2005/Q4
© 2005 SAP AG. All rights reserved.
479
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 active
version 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
TAW10_3
453
Lesson: Shared Objects
Exercise 25: Using Shared Objects
Exercise Duration: 50 Minutes
Exercise Objectives
After 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 Example
You want to run an Internet shop based on an SAP system. To give your Internet
customers the fastest possible access to your catalog, you save it in the shared objects
memory.
You will need a “write program” to manage and describe the catalog and develop a
test application to read the data..
System Data
System:
Client:
User ID:
Password:
Set up instructions:
Will be assigned
Will be assigned
Will be assigned
Will be assigned
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 catalog
in a separate class.
1.
Create an area named ZCL_BC402_##_AREA using transaction SHMA. This
area should have the following attributes:
Client-specific Area
With Versioning
Displacement not Possible
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
481
Unit 6: Shared Objects
TAW10_3
The system automatically prompts you to specify a root class. Create an area
root class with name ZCL_BC402_##_ROOT.
2.
Implement the area root class. It should merely contain a reference to the catalog
class 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 for
writing the catalog data and another method for retrieving the data. It also requires a
global attribute: an internal table that saves the catalog data.
1.
Create a global class with name ZCL_BC402_##_CATALOG. Note that this
class has to be shared memory-enabled.
2.
Create an internal table as a global attribute of the class. The line type of the
internal 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 internal
table 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 and
destination cities, as well as two additional parameters for the earliest and latest
possible 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 program
is also supposed to read the catalog data from the database and pass it on to the
appropriate class.
1.
Create a program with type “Executable Program”.
Name of program: ZBC402_##_WRITE_CATALOG
Continued on next page
482
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Shared Objects
2.
You need three reference variables: one each for the area handle, the area root
class, and the catalog class.
3.
Create an area, an instance of the catalog class, and an instance of the area root
class. Set up the area.
Use the Shared Objects Monitor (transaction code SHMM) to monitor the setup
of 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. For
simplicity's sake, output this data in the SAP List Viewer.
Hint: Alternatively, you can also develop a BSP application that requests
the catalog data.
1.
Create a program.
Name of program: ZBC402_##_READ_CATALOG
2005/Q4
2.
Define a selection screen in which the user can enter the departure and
destination cities. The user should also be able to enter an earliest and latest
possible flight date.
3.
Make sure the data is read from the catalog object. Output the data in the SAP
List Viewer (simplest call).
© 2005 SAP AG. All rights reserved.
483
Unit 6: Shared Objects
TAW10_3
Solution 25: Using Shared Objects
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 catalog
in a separate class.
1.
Create an area named ZCL_BC402_##_AREA using transaction SHMA. This
area should have the following attributes:
Client-specific Area
With Versioning
Displacement not Possible
The system automatically prompts you to specify a root class. Create an area
root class with name ZCL_BC402_##_ROOT.
a)
2.
Follow the instructor's demonstration.
Implement the area root class. It should merely contain a reference to the catalog
class 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 for
writing the catalog data and another method for retrieving the data. It also requires a
global attribute: an internal table that saves the catalog data.
1.
Create a global class with name ZCL_BC402_##_CATALOG. Note that this
class has to be shared memory-enabled.
a)
2.
Create the class in the Class Builder. Refer to the model solution for details.
Create an internal table as a global attribute of the class. The line type of the
internal table should correspond to structure SDYN_CONN.
Suggested name: GT_CATALOG
a)
3.
Refer to the model solution for details.
Create a method to fill the catalog.
Suggested name: FILL_CATALOG
Continued on next page
484
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Shared Objects
This method requires an importing parameter that will be given the internal
table with data.
Implement the method.
a)
4.
Refer to the model solution for details.
Create a second method to satisfy the flight date queries.
Suggested name: GET_FLIGHTS
This method requires one importing parameter each for the departure and
destination cities, as well as two additional parameters for the earliest and latest
possible 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 program
is also supposed to read the catalog data from the database and pass it on to the
appropriate class.
1.
Create a program with type “Executable Program”.
Name of program: ZBC402_##_WRITE_CATALOG
a)
2.
You need three reference variables: one each for the area handle, the area root
class, and the catalog class.
a)
3.
Refer to the model solution for details.
.
Create an area, an instance of the catalog class, and an instance of the area root
class. Set up the area.
Use the Shared Objects Monitor (transaction code SHMM) to monitor the setup
of the area and the set locks.
Read the necessary catalog data from tables SPFLI and SFLIGHT.
a)
4.
Refer to the model solution for details.
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
Unit 6: Shared Objects
TAW10_3
Task 4:
Implement a reading program to read data from the area you just created. For
simplicity's sake, output this data in the SAP List Viewer.
Hint: Alternatively, you can also develop a BSP application that requests
the catalog data.
1.
Create a program.
Name of program: ZBC402_##_READ_CATALOG
a)
2.
Define a selection screen in which the user can enter the departure and
destination cities. The user should also be able to enter an earliest and latest
possible flight date.
a)
3.
Refer to the model solution for details.
Refer to the model solution for details.
Make sure the data is read from the catalog object. Output the data in the SAP
List 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
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
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
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
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
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 Discussion
Reinforcement
Discussion Questions
Use the following questions to engage the participants in the discussion. Feel free to
use 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
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
TAW10_3
Unit Summary
Unit 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
2005/Q4
© 2005 SAP AG. All rights reserved.
493
Unit Summary
494
TAW10_3
© 2005 SAP AG. All rights reserved.
2005/Q4
Unit 7
Case Study
467
For more information, see the introductory instructor notes in the lesson.
Unit Overview
The following case study calls on your previously acquired knowledge and by
performing a comprehensive exercise (cass study), you will further strengthen your
existing knowledge.
Unit Objectives
After completing this unit, you will 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
Unit Contents
Lesson: Case Study and Preview ................................................ 496
Exercise 26: Create a UML Class Diagram................................. 507
Exercise 27: Develop a Solution for a Test Case .......................... 511
2005/Q4
© 2005 SAP AG. All rights reserved.
495
Unit 7: Case Study
Lesson:
468
TAW10_3
Case Study and Preview
Lesson Duration: 30 Hours
Lesson Overview
In this lesson, you will consolidate and apply the knowledge you have gained in this
course. You will do this in the best way possible by applying the ABAP Objects
techniques to the case study presented here.
Lesson Objectives
After completing this lesson, you will 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
If possible, you should allow the participants to spend enough time on the case study
so that they leave the course with a “sense of achievement”. Nothing will motivate
them 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 the
course). If you do this, explain to the participants that they can check their work
against the model solution provided in the folder.
Hint: To explain what is involved, demonstrate the solution once and explain
the exact function of each button.
Give a very brief overview of the 6.40 features of ABAP Unit and Shared
Objects and refer the participants to the relevant specialized course.
The participants need to absorb all of the new knowledge they have gained during
the first week of the course and you do not want to overwhelm them with more new
information.
Business Example
A customer wants to book a flight through a travel agency, but the flight is already
booked. However, the customer is given the option of registering for the flight and
being put on the waiting list.
496
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Case Study and Preview
Case Study
The ABAP Objects program to be created here should provide the user (for example,
the travel agent) with a screen containing functions for managing customers using
flight waiting lists. It should be possible to maintain a waiting list for each flight (row
from table SFLIGHT with the keys CARRID, CONNID, FLDATE).
Note: The model shown here is one possible solution to the waiting list
requirements described. You are also free to use your own UML class
diagram, 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 waiting
lists 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
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 the
requirement specifications. The screen layout and flow logic are already available:
you have to implement the actual flow, that is, the “intelligence” of the program
using object-oriented techniques.
The individual buttons are to have the following functions:
Display
Displays the waiting list for the specified flight (CARRID, CONNID, FLDATE)
Create
Creates the waiting list for the specified flight (CARRID, CONNID, FLDATE)
Delete
Deletes the waiting list for the specified flight (CARRID, CONNID, FLDATE)
Add
Adds the customer selected on the right of the screen to the flight waiting list
selected on the left
Delete (customer)
Deletes the customer selected on the right of the screen from the flight displayed
on the left
498
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Case Study and Preview
Position
Displays the selected customer’s position on the waiting list
Customer Type (optional)
Shows whether the selected customer is a private customer or a business
customer (you will find the relevant information in the CUSTTYPE field of
table SCUSTOM).
Display Customers Moved Up (optional)
Displays all customers from the list who were successfully moved up from the
waiting list to get a seat on the flight
Status Log (optional)
Displays the number of customers from the list who
were successful in getting a seat on a flight.
2005/Q4
© 2005 SAP AG. All rights reserved.
499
Unit 7: Case Study
TAW10_3
SAP Web AS 6.40 is a prerequisite for the following topics. You must mention this
fact at this point.
You can use program SAPBC401_PRJD_SHAREDOBJECT as a demo of shared
objects.
Preview of New Topics: Shared Objects
As 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 this
memory area using the EXPORT and IMPORT statements with the additions
SHARED BUFFER or SHARED MEMORY and instances of classes existed only
in 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 which
shared objects can be stored.
Note: The storage of class instances is currently supported. It is not yet
possible to store any data object directly as a shared object; however, data
objects other than reference variables can be stored as attributes of classes.
500
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Case Study and Preview
Figure 200: Shared Objects: Basics
Prerequisites for Shared Objects
•
•
•
•
•
Cross-program buffering of data with a small number 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 manage
areas and their attributes in transaction SHMA. A prerequisite for storing an object in
the shared memory is that the class of the object must be defined with the addition
SHARED MEMORY ENABLED of the CLASS statement, or the shared memory
enabled“” attribute must be selected in the Class Builder.
2005/Q4
© 2005 SAP AG. All rights reserved.
501
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 own
data and references to other shared-memory-enabled classes. An area is a template for
area instances in the shared memory. Several area instances with different names can
be created for one area.
When you define an area with transaction SHMA, a global and final area class with
the 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 the
generated area class. There are static methods for attaching an ABAP program (or its
internal mode) to area instances in the shared memory (Attach methods).
502
© 2005 SAP AG. All rights reserved.
2005/Q4
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 a
lock is set at the same time. The ABAP program can use the area handle to access
the 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
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 the
relevant ABAP course for advanced developers.
Preview of New Topics: ABAP Unit
As 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 to
check the functionality of the code units of a program (module tests). Individual tests
are implemented in various ABAP programs as test methods of local test classes. The
tests of several ABAP programs can be grouped together in test items.
504
© 2005 SAP AG. All rights reserved.
2005/Q4
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 the
relevant ABAP course for advanced developers.
2005/Q4
© 2005 SAP AG. All rights reserved.
505
Unit 7: Case Study
506
TAW10_3
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
477
Lesson: Case Study and Preview
Exercise 26: Create a UML Class Diagram
Exercise Duration: 20 Minutes
Exercise Objectives
After completing this exercise, you will be able to:
•
Create one possible UML class diagram to meet a technical specification
Business Example
A travel agency wants to offer its customers an additional service. If customers
want to book a flight that is already fully booked, they can have their names put on
a waiting list for this flight. If a seat becomes free at a later date, a customer from
the waiting list can be placed on the flight. This customer's name is then removed
from the waiting list.
Task: Create a UML Class Diagram
You 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 do
this, follow the instructions below to create a class diagram.
1.
The waiting list should be the central class in the model. Use LCL_WAITLIST
as the class name (ZCL_##_WAITLIST if you are using the Class Builder).
The class should have the public attributes CARRID, CONNID, FLDATE and
the private attribute CUSTOMER_LIST.
The following public methods should be defined in the UML:
CONSTRUCTOR, ADD, DELETE, GET_POS, GET_FIRST and
GET_WAIT_LIST.
Hint: It would actually be more in line with the encapsulation concept to
define all of the attributes here as private and then access these attributes
of the waiting list with external methods. We suggest that you define the
attributes 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
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: CONSTRUCTOR
and GET_ATTRIBUTES
3.
As a straightforward solution, you could simply define the buffer for the
waiting lists in the main program as a normal internal table. However, you
want 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 attribute
N_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 concept
to define the BUFFER_LIST attribute as private in this case and then
access this attribute with methods from the main program. In this case,
we suggest that you define this attribute as public and then access it
externally and directly to save time and effort, but this is your choice!
If you follow the model solution for the class diagram, you must use
methods.
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
TAW10_3
Lesson: Case Study and Preview
Solution 26: Create a UML Class Diagram
Task: Create a UML Class Diagram
You 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 do
this, follow the instructions below to create a class diagram.
1.
The waiting list should be the central class in the model. Use LCL_WAITLIST
as the class name (ZCL_##_WAITLIST if you are using the Class Builder).
The class should have the public attributes CARRID, CONNID, FLDATE and
the private attribute CUSTOMER_LIST.
The following public methods should be defined in the UML:
CONSTRUCTOR, ADD, DELETE, GET_POS, GET_FIRST and
GET_WAIT_LIST.
Hint: It would actually be more in line with the encapsulation concept to
define all of the attributes here as private and then access these attributes
of the waiting list with external methods. We suggest that you define the
attributes as public here to save time and effort, but this is your choice!
a)
2.
Refer to the model solution.
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: CONSTRUCTOR
and GET_ATTRIBUTES
a)
3.
Refer to the model solution.
As a straightforward solution, you could simply define the buffer for the
waiting lists in the main program as a normal internal table. However, you
want 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 attribute
N_O_ENTRIES and a private, static reference to itself.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
509
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 concept
to define the BUFFER_LIST attribute as private in this case and then
access this attribute with methods from the main program. In this case,
we suggest that you define this attribute as public and then access it
externally and directly to save time and effort, but this is your choice!
If you follow the model solution for the class diagram, you must use
methods.
a)
4.
Refer to the model solution.
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
TAW10_3
481
Lesson: Case Study and Preview
Exercise 27: Develop a Solution for a Test
Case
Exercise Duration: 300 Minutes
Exercise Objectives
After 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 Example
A customer wants to book a flight through a travel agency but the flight is already
fully booked. However, the customer is offered the option of registering for the
waiting 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 instructions
below. If you have created your own alternate UML class diagram, you can ignore
these instructions.
1.
Use program SAPBC401_PRJT_WAITLIST as a template. Your program
should be called ZBC401_##_PRJS_WAITLIST.
Copy all Include programs from the template and rename them. You should
always 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 be
created. Familiarize yourself with the program structure.
This program contains a screen on which buttons for all of the required functions
are already provided. However, with the exception of the icons in the standard
toolbar, these functions still have to be implemented.
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
511
Unit 7: Case Study
TAW10_3
For the meaning of the individual buttons, refer to the screen shown in the figure
and the explanatory text in your course notes.
Note: If you have no experience with dynamic screens or dialog
programming with ABAP, speak to your course instructor.
Hint: The display of the customer data on the waiting list (function
code SHOW) is not part of this exercise. Therefore, to save time, you
can use function module BC401_DISPLAY_DATA. Later, when you
are implementing this function, you should familiarize yourself with
its interface and use it for display. If you have enough time, you can
also use the ALV Grid Control.
Note: To simplify the scenario, avoid persistent storage of the waiting
list. 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 for
which the existing components should be examined. The main point of
the exercise is not to implement the program in detail.
512
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Case Study and Preview
Solution 27: Develop a Solution for a Test
Case
Task:
Convert the definitions from your class diagram into a program.
If you want to use the suggestions proposed in this unit, follow the instructions
below. If you have created your own alternate UML class diagram, you can ignore
these instructions.
1.
Use program SAPBC401_PRJT_WAITLIST as a template. Your program
should be called ZBC401_##_PRJS_WAITLIST.
Copy all Include programs from the template and rename them. You should
always use the target names specified with your group number (suggested name:
ZBC401_##_PRJS_INC_xxx ).
a)
2.
Carry out this step in the usual manner.
The copied template already contains the parameters for the application to be
created. Familiarize yourself with the program structure.
This program contains a screen on which buttons for all of the required functions
are already provided. However, with the exception of the icons in the standard
toolbar, these functions still have to be implemented.
For the meaning of the individual buttons, refer to the screen shown in the figure
and the explanatory text in your course notes.
Note: If you have no experience with dynamic screens or dialog
programming with ABAP, speak to your course instructor.
Hint: The display of the customer data on the waiting list (function
code SHOW) is not part of this exercise. Therefore, to save time, you
can use function module BC401_DISPLAY_DATA. Later, when you
Continued on next page
2005/Q4
© 2005 SAP AG. All rights reserved.
513
Unit 7: Case Study
TAW10_3
are implementing this function, you should familiarize yourself with
its interface and use it for display. If you have enough time, you can
also use the ALV Grid Control.
Note: To simplify the scenario, avoid persistent storage of the waiting
list. 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 for
which the existing components should be examined. The main point of
the exercise is not to implement the program in detail.
a)
The model solution provided here encapsulates the buffer with the waiting
lists in class LCL_BUFFER. The waiting lists in the buffer can be accessed
with public methods.
It is also possible to create the buffer in the main program directly
as a non-encapsulated internal table. Due to time restrictions, this is
recommended, 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
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
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
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
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
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
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
IMPORTING
im_customer = r_customer
ex_pos
= pos ).
WRITE sdyn_conn-fldate TO fldate.
CONCATENATE sdyn_conn-carrid sdyn_conn-connid fldate
INTO flight SEPARATED BY space.
MESSAGE 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
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
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
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
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:
ENDCLASS.
customer_list TYPE ty_customer_list.
"lcl_waitlist DEFINITION
*---------------------------------------------------------------------*
*
CLASS lcl_waitlist IMPLEMENTATION
Continued on next page
524
© 2005 SAP AG. All rights reserved.
2005/Q4
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.
METHOD add.
"get_wait_list
"--------------------------------------
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
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
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
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
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
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
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
Unit Summary
TAW10_3
Unit 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
532
© 2005 SAP AG. All rights reserved.
2005/Q4
Unit 8
ABAP Certification
503
Unit Overview
This unit contains a certification description and lists the topics tested in the
certification test.
Unit Objectives
After completing this unit, you will be able to:
•
Name all topics about which questions are asked in the ABAP Certification test.
Unit Contents
Lesson: Description of Certification .............................................. 534
2005/Q4
© 2005 SAP AG. All rights reserved.
533
Unit 8: ABAP Certification
Lesson:
504
TAW10_3
Description of Certification
Lesson Duration: 1 Minutes
Lesson Overview
This lesson lists all topics about which questions are asked in SAP Consultant
Certification Development Consultant SAP NetWeaver 2004 – Application
Development Focus ABAP. It also includes a weighting that indicates how many
questions are asked that relate to a particular area.
Lesson Objectives
After completing this lesson, you will be able to:
•
Name all topics about which questions are asked in the ABAP Certification test.
Business Example
Suppose you want to do the ABAP Certification and you want to find out exactly what
you need to know for the test.
SAP Consultant Certification Development Consultant
SAP NetWeaver 2004 – Application Development Focus
ABAP
Software component: SAP Web Application Server 6.40
The Certification is part of the course TAW12, which is offered separately at many
SAP 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
TAW10_3
Lesson: Description of Certification
Courses for preparing for the certification test: TAW10 (ABAP Workbench
Fundamentals), TAW12 (ABAP Workbench Concepts)
Please note that auxiliary materials are not permitted during the certification test (no
access to the online documentation and no access to an SAP system).
The certfication test for Development Consultant SAP NetWeaver 2004 - Application
Development Focus ABAP verifies the participant's knowledge of SAP NetWeaver in
the field of the Application Development Focus ABAP consultant profile. Participants
can use this certificate to prove their basic knowledge in this consultant profile and to
implement this knowledge in projects.
The certification test contains questions from the following content areas:
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 (++)
•
•
•
•
2005/Q4
ABAP Runtime
ABAP Types and Data Objects (Use)
Open SQL (Efficient Programming)
Dynamic Programming
© 2005 SAP AG. All rights reserved.
535
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:
–
–
–
–
536
Simple Lists
Field Catalog
Layout
Event Handling
© 2005 SAP AG. All rights reserved.
2005/Q4
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
Unit 8: ABAP Certification
TAW10_3
Information subject to change. Copyright © SAP AG 2005.
538
© 2005 SAP AG. All rights reserved.
2005/Q4
TAW10_3
Lesson: Description of Certification
Facilitated Discussion
Opportunity to discuss open issues.
Discussion Questions
Use the following questions to engage the participants in the discussion. Feel free to
use your own additional questions.
2005/Q4
© 2005 SAP AG. All rights reserved.
539
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
TAW10_3
Unit Summary
Unit Summary
You 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
Course Summary
TAW10_3
Course Summary
You should now be able to:
•
•
•
•
•
•
•
•
542
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
© 2005 SAP AG. All rights reserved.
2005/Q4
Index
A
abstraction, 20
ACTIVATION, 199
aggregation, 27, 58
alias name, 158–159, 168
ALV Grid Control, 257, 324
association, 24
binary and recursive, 24
attribute, 43
KERNEL_ERRID, 388
PREVIOUS, 402
private, 45
public, 45
static, 47
B
Business Add-Ins, 263
C
CALL METHOD, 60–61
EXCEPTIONS, 49
EXPORTING, 49
IMPORTING, 49
cardinality, 24
CHANGING, 49
class, 19
CL_ABAP_CLASSDESCR, 433
CL_ABAP_STRUCTDESCR, 431
CL_ABAP_TYPEDESCR,
429, 431, 433
CL_GUI_ALV_GRID, 258
CL_GUI_CUSTOM_CONTAINER, 258
definition, 43
2005/Q4
definition part, 43
Class
CL_GUI_ALV_GRID, 325
CL_GUI_CUSTOM_CONTAINER, 325
CLASS, 238
definition, 43
INHERITING FROM, 112
PRIVATE SECTION, 46
PUBLIC SECTION, 46
class attribute, 47
Class Builder
display settings, 250–251
editing class components,
245
class diagram, 23
CLASS EVENTS, 196
class method, 52
CLASS_CONSTRUCTOR, 67
CLASS-METHODS, 51
component interface, 167
composition, 27
compound interface, 167
constructor, 65, 115
static, 67
CONSTRUCTOR, 65
container control, 258
Container control, 325
CREATE OBJECT, 55
D
DATA
TYPE REF TO, 54
DEFAULT, 49
DEFINITION, 43
definition part, 43
© 2005 SAP AG. All rights reserved.
543
Index
TAW10_3
delegation, 31
delegation principle, 13
DESCRIBE FIELD, 429
DESCRIBE TABLE, 429
destructor, 65
downcast, 127, 165
E
encapsulation, 7, 45
Enjoy Demo Center, 262, 327
event
static, 193
Event control, 14
event handler method, 194
EVENTS, 196
exception
class-based, 386
definition, 386
mapping, 402
propagate, 388
propagation, 394
exception chain, 386, 402
exception class, 386
CX_DYNAMIC_CHECK,
387, 401
CX_NO_CHECK, 387, 401
CX_ROOT, 387, 402
CX_STATIC_CHECK, 387,
401
CX_SY_ARITHMETIC_ERROR, 390
CX_SY_ARITHMETIC_OVERFLOW,
390
CX_SY_MOVE_CAST_ERROR, 128, 165
CX_SY_ZERODIVIDE,
388
global, 386
inheritance hierarchy, 401
local, 386
superclass, 401
exception handling, 386
544
© 2005 SAP AG. All rights reserved.
CATCH, 388
CLEANUP, 389, 395
static check, 401
syntax check, 401
TRY, ENDTRY, 388
exception instance, 386
exception texts, 388
F
function group
data management, 7
G
Garbage Collector, 56
generalization, 28, 110
global class
print, 245
test, 245
H
handler table, 200
I
indicator
OO transaction model, 270
information hiding, 45
Inheritance, 14
instance, 19
instance attribute, 47
instance constructor, 65, 115
instance event, 193
instance method, 51
instantiation
class, 53
interface
class, 45
compound, 167
method, 49
INTERFACE, 158
interface resolution operator,
158–159
INTERFACES, 158
IS INITIAL, 56
2005/Q4
TAW10_3
2005/Q4
Index
M
N
ME, 68
MESSAGE, 390
method
call, 60–61
definition, 49
DESCRIBE_BY_DATA,
431
DESCRIBE_BY_OBJECT_REF, 433
functional, 62
GET_RELATIVE_NAME,
433
GET_SOURCE_POSITION, 387
GET_TEXT, 387, 390, 392,
395
parameter, 49
private, 51
public, 51
redefinition, 113
REFRESH_TABLE_DISPLAY, 259
SET_TABLE_FOR_FIRST_DISPLAY, 259
signature, 49
static, 51
Method
REFRESH_TABLE_DISPLAY, 327
SET_TABLE_FOR_FIRST_DISPLAY, 326
METHODS, 51
FOR EVENT, 197
MOVE, 55, 164
widening cast assignment
operator, 127
multiple inheritance, 112
multiple instantiation, 11
multiplicity, 24
namespace
class, 51
narrowing cast, 161
Narrowing cast, 120
null reference, 54
O
object
behavior, 22
classification, 18
identity, 19
status, 19, 22
object diagram, 29
object link, 24
Object Management Group
(OMG), 21
OMG, 21
OO transaction, 269
OO transaction model, 270
OPTIONAL, 49
P
package, 22
polymorphism, 14, 124, 162
PRIVATE SECTION, 46
programming model
object-oriented, 11
procedural, 5
PROTECTED SECTION, 116
PUBLIC SECTION, 46
R
RAISE EVENT, 196
RAISING, 394
READ-ONLY, 44, 46
redefinition, 113
Refactoring Assistant, 254
reference
independent, 56
reference variable, 54
registration, 198, 200
RETURNING, 49
© 2005 SAP AG. All rights reserved.
545
Index
TAW10_3
role, 24
role design pattern, 130
RTTC, 433
RTTI, 429
Run Time Type Creation, 433
runtime error
BCD_ZERODIVIDE, 388
catchable, 387
Runtime Type Identification
(RTTI), 429
S
SAP Control Framework, 257,
323
self-reference, 68
SENDER, 197
sequence diagram, 30
SET HANDLER, 199
ACTIVATION, 199
FOR ALL INSTANCES,
199
signature, 49
specialization, 28, 110
static attribute, 47
static constructor, 67
static method, 51
546
© 2005 SAP AG. All rights reserved.
subclass, 110
SUPER, 113
superclass, 110
T
TABLE_LINE, 58
text ID, 395
transaction code, 269
transaction service, 269
type
dynamic, 120
static, 120
TYPE REF TO, 54
U
UML, 21
Unified Modeling Language, 21
upcast, 120, 161
V
visibility section
protected, 116
W
widening cast, 127, 165
widening cast assignment
operator, 127, 164
2005/Q4
Feedback
SAP AG has made every effort in the preparation of this course to ensure the accuracy
and completeness of the materials. If you have any corrections or suggestions for
improvement, please record them in the appropriate place in the course evaluation.
2005/Q4
© 2005 SAP AG. All rights reserved.
547
Download