Sie sind auf Seite 1von 467

BC401 ABAP Objects

BC401

Release 630 02.09.2003

BC401 ABAP Objects .................................................................................................................................................. 0-1


Copyright .................................................................................................................................................................. 0-2
Course Prerequisites .............................................................................................................................................. 0-3
Target Group ......................................................................................................................................................... 0-4
Course Overview....................................................................................................................................................... 1-1
Course Goal .......................................................................................................................................................... 1-2
Course Objectives ................................................................................................................................................. 1-3
Course Content (1) ................................................................................................................................................ 1-4
Course Content (2) ................................................................................................................................................ 1-5
Course Overview: Integration in Course Content ................................................................................................. 1-6
Main Business Scenario ........................................................................................................................................ 1-7
Technical Names ................................................................................................................................................... 1-8
Data Types and Data Objects in Detail ..................................................................................................................... 2-1
Data Types and Data Objects in Detail: Unit Objectives ...................................................................................... 2-2
Data Types and Data Objects in Detail: Integration in Course Content ................................................................ 2-3
Data Types and Data Objects in Detail (1)............................................................................................................ 2-4
Revision: Defining Data Objects .......................................................................................................................... 2-5
Predefined ABAP Types ....................................................................................................................................... 2-6
Type Groups in the ABAP Dictionary .................................................................................................................. 2-7
Data Types and Data Objects in Detail (2)............................................................................................................ 2-8
Integers and Integer Arithmetic............................................................................................................................. 2-9
Packed Numbers and Fixed Point Arithmetic ..................................................................................................... 2-10
Floating Point Arithmetic .................................................................................................................................... 2-11
Summary: Recommendations for Using Numeric Data Types ........................................................................... 2-12
Arithmetic and Mixed Expressions ..................................................................................................................... 2-13
Predefined ABAP Types for Character Strings ................................................................................................... 2-14
Overview: Character String Processing .............................................................................................................. 2-15
Accessing Parts of Fields .................................................................................................................................... 2-16
Data Types and Data Objects in Detail (3).......................................................................................................... 2-17
Defining Structures with Local Types ................................................................................................................ 2-18
Defining Nested Structures with Local Types .................................................................................................... 2-19
Using Named Includes ........................................................................................................................................ 2-20
Data Types and Data Objects in Detail (4).......................................................................................................... 2-21
Unicode: Overview ............................................................................................................................................. 2-22
Character-Type and Byte-Type Types ................................................................................................................ 2-23
Functions and Comparison Operators ................................................................................................................. 2-24
Compatibility and Conversion ............................................................................................................................ 2-25
Conversion Under Unicode (1) ........................................................................................................................... 2-26

Conversion Under Unicode (2) ........................................................................................................................... 2-27


Example of Using the Conversion Rules ............................................................................................................ 2-28
Offset and Length Accesses and Elementary Data Objects ................................................................................ 2-29
Offset and Length Accesses and Structures ........................................................................................................ 2-30
Data Types and Data Objects in Detail: Summary .............................................................................................. 2-31
Data Types and Data Objects in Detail Exercise 1.............................................................................................. 2-32
Data Types and Data Objects in Detail Solution 1 .............................................................................................. 2-34
Using Internal Tables ................................................................................................................................................ 3-1
Using Internal Tables: Unit Objectives ................................................................................................................. 3-2
Using Internal Tables: Integration in Course Content ........................................................................................... 3-3
Using Internal Tables (1) ...................................................................................................................................... 3-4
The Internal Table - a Data Object of Variable Length......................................................................................... 3-5
Attributes of Internal Tables ................................................................................................................................. 3-6
Link Between Table Kind and Access Type ......................................................................................................... 3-7
Using Internal Tables (2) ...................................................................................................................................... 3-8
Overview: Types of Definitions for Internal Tables ............................................................................................. 3-9
The Data Type of an Internal Table .................................................................................................................... 3-10
Table Attribute: Line Type.................................................................................................................................. 3-11
Table Attribute: Table Kind and Key .................................................................................................................. 3-12
Example: Standard Table with Local Type ......................................................................................................... 3-13
Example: Sorted and Hashed Table .................................................................................................................... 3-14
The Standard Table Type .................................................................................................................................... 3-15
Internal Tables with an Unstructured Line Type ................................................................................................. 3-16
Using Internal Tables (3) .................................................................................................................................... 3-17
Overview: Types of Operation ............................................................................................................................ 3-18
Limiting the Scope of Line Operations: Target Records and Access Type ........................................................ 3-19
Preview: Field SymboIs (1) ................................................................................................................................ 3-20
Preview: Field SymboIs (2) ................................................................................................................................ 3-21
Insert ................................................................................................................................................................... 3-22
Reading a Single Record into a Work Area Using the Line Number .................................................................. 3-23
Reading a Single Record into a Work Area Using the Field Contents ................................................................ 3-24
Reading a Single Record Using a Field Symbol ................................................................................................. 3-25
Changing the Table Using a Work Area ............................................................................................................. 3-26
Changing a Single Record Using a Field Symbol ............................................................................................... 3-27
Delete .................................................................................................................................................................. 3-28
Loop Processing .................................................................................................................................................. 3-29
Overview of Operations ...................................................................................................................................... 3-30
Using Internal Tables (4) .................................................................................................................................... 3-31
Internal Tables with a Header Line ..................................................................................................................... 3-32

Selection Options and Selection Tables .............................................................................................................. 3-33


Using Internal Tables (5) .................................................................................................................................... 3-34
Single Record Access: Completely and Partially Qualified Key ........................................................................ 3-35
Loop Processing and Table Kinds ....................................................................................................................... 3-36
Partial Sequential Loop Through Standard Tables .............................................................................................. 3-37
Access Using Field Symbols ............................................................................................................................... 3-38
Using Internal Tables: Unit Summary ................................................................................................................ 3-39
Using Internal Tables Exercise 1 ........................................................................................................................ 3-40
Using Internal Tables Solution 1 ......................................................................................................................... 3-47
Calling Programs and Passing Data .......................................................................................................................... 4-1
Calling Programs and Passing Data: Unit Objectives ........................................................................................... 4-2
Calling Programs and Passing Data: Integration in Course Content ..................................................................... 4-3
Calling Programs and Passing Data (1)................................................................................................................. 4-4
Calling Programs................................................................................................................................................... 4-5
Calling an Executable Program ............................................................................................................................. 4-6
Calling a Transaction ............................................................................................................................................ 4-7
Calling Programs and Passing Data (2) ................................................................................................................. 4-8
Logical Memory Model ........................................................................................................................................ 4-9
Inserting a Program (1) ....................................................................................................................................... 4-10
Inserting a Program (2) ....................................................................................................................................... 4-11
Terminating the Inserted Program....................................................................................................................... 4-12
Restarting an Executable Program (1) ................................................................................................................ 4-13
Restarting an Executable Program (2) ................................................................................................................ 4-14
Restarting a Transaction (1) ................................................................................................................................ 4-15
Restarting a Transaction (2) ................................................................................................................................ 4-16
Calling Programs and Passing Data (3) ............................................................................................................... 4-17
Overview: Passing Data Between Programs ....................................................................................................... 4-18
Passing Data Using the Program Interface .......................................................................................................... 4-19
Preassigning Values for Input Fields .................................................................................................................. 4-20
ABAP Memory and SAP Memory...................................................................................................................... 4-21
Passing Data Using the ABAP Memory ............................................................................................................. 4-22
Passing Parameters Using the SAP Memory ...................................................................................................... 4-23
Preview: Passing Data Using an Internal Table .................................................................................................. 4-24
Fields of the Global Type bdcdata ...................................................................................................................... 4-25
Example: Passing Data Using an Internal Table ................................................................................................. 4-26
Calling Programs and Passing Data: Unit Summary ........................................................................................... 4-27
Introduction to Object-Oriented Programming ......................................................................................................... 5-1
Introduction to Object-Oriented Programming: Unit Objectives .......................................................................... 5-2
Introduction to Object-Oriented Programming: Integration in Course Content .................................................... 5-3

History of Programming Languages ..................................................................................................................... 5-4


Introduction: Programming Models (1) ................................................................................................................ 5-5
Characteristics of Procedural Programming.......................................................................................................... 5-6
Typical ABAP Program ........................................................................................................................................ 5-7
ABAP Main Memory and Function Groups ......................................................................................................... 5-8
Function Group Example ...................................................................................................................................... 5-9
Use of Function Group ........................................................................................................................................ 5-10
Several Instances of One Function Group ........................................................................................................... 5-11
Instantiation and Object-Oriented Languages ..................................................................................................... 5-12
Introduction: Programming Models (2) .............................................................................................................. 5-13
Programming Models .......................................................................................................................................... 5-14
Characteristics of the Object-Oriented Approach ............................................................................................... 5-15
Technical Implementation of the Object-Oriented Approach ............................................................................. 5-16
Client/Server Behavior ........................................................................................................................................ 5-17
Compatibility and Design Aims .......................................................................................................................... 5-18
ABAP Main Memory and Encapsulation ............................................................................................................ 5-19
The Software Development Process ................................................................................................................... 5-20
Introduction to Object-Oriented Programming: Summary .................................................................................. 5-21
Analysis and Design.................................................................................................................................................. 6-1
Analysis and Design: Unit Objectives .................................................................................................................. 6-2
Analysis and Design: Integration in Course Content ............................................................................................ 6-3
Analysis and Design (1) ........................................................................................................................................ 6-4
Classification of Objects ....................................................................................................................................... 6-5
Different Abstractions of a Class .......................................................................................................................... 6-6
Representation of a Class ...................................................................................................................................... 6-7
Classes and Objects ............................................................................................................................................... 6-8
Analysis and Design (2) ........................................................................................................................................ 6-9
Modeling with UML ........................................................................................................................................... 6-10
Example of a Class Diagram ............................................................................................................................... 6-11
Association .......................................................................................................................................................... 6-12
Aggregation and Composition ............................................................................................................................ 6-13
Generalization and Specialization ....................................................................................................................... 6-14
Sequence Diagrams: Example ............................................................................................................................. 6-15
Sequence Diagram: Delegation ........................................................................................................................... 6-16
Analysis and Design: Summary .......................................................................................................................... 6-17
Analysis and Design Exercises ........................................................................................................................... 6-18
Analysis and Design Solutions ............................................................................................................................ 6-19
Principles of Object-Oriented Programming ............................................................................................................. 7-1
Principles of Object-Oriented Programming: Unit Objectives.............................................................................. 7-2

Principles of Object-Oriented Programming: Integration in Course Content ....................................................... 7-3


Principles (1) ......................................................................................................................................................... 7-4
Example of a Class ................................................................................................................................................ 7-5
Defining Classes ................................................................................................................................................... 7-6
Attributes............................................................................................................................................................... 7-7
Attributes, Types, and Constants: Syntax ............................................................................................................. 7-8
Attributes and Visibility ........................................................................................................................................ 7-9
Accessing Private Attributes ............................................................................................................................... 7-10
Instance Attributes and Static Attributes (1) ....................................................................................................... 7-11
Instance Attributes and Static Attributes (2) ....................................................................................................... 7-12
Methods: Syntax ................................................................................................................................................. 7-13
Accessing Private Methods ................................................................................................................................. 7-14
Methods and Visibility ........................................................................................................................................ 7-15
Instance Methods and Static Methods ................................................................................................................. 7-16
Instance Methods and Static Methods: Example ................................................................................................ 7-17
Summary and UML Notation .............................................................................................................................. 7-18
Principles (2) ....................................................................................................................................................... 7-19
Creating Objects .................................................................................................................................................. 7-20
Reference Variables ............................................................................................................................................ 7-21
Creating Objects: Syntax..................................................................................................................................... 7-22
Garbage Collector ............................................................................................................................................... 7-23
Garbage Collector: Procedure ............................................................................................................................. 7-24
Buffering References .......................................................................................................................................... 7-25
Aggregation Example ......................................................................................................................................... 7-26
Principles (3) ....................................................................................................................................................... 7-27
Calling Methods .................................................................................................................................................. 7-28
Calling Instance Methods: Syntax ....................................................................................................................... 7-29
Calling Static Methods: Syntax ........................................................................................................................... 7-30
Functional Methods............................................................................................................................................. 7-31
Functional Methods: Example ............................................................................................................................ 7-32
External Access to Public Attributes ................................................................................................................... 7-33
Principles (4) ....................................................................................................................................................... 7-34
Constructor .......................................................................................................................................................... 7-35
Constructor: Example ......................................................................................................................................... 7-36
Preview: Static Constructor................................................................................................................................. 7-37
Principles (5) ....................................................................................................................................................... 7-38
Namespace Within a Class .................................................................................................................................. 7-39
The Reference Variable ME ................................................................................................................................ 7-40
Principles of Object-Oriented Programming: Unit Summary ............................................................................. 7-41

Principles of Object-Oriented Programming Exercises ...................................................................................... 7-42


Principles of Object-Oriented Programming Solutions ....................................................................................... 7-48
Inheritance ................................................................................................................................................................. 8-1
Inheritance: Unit Objectives ................................................................................................................................. 8-2
Inheritance: Integration in Course Content ........................................................................................................... 8-3
Inheritance: UML Example................................................................................................................................... 8-4
Multiple Inheritance? ............................................................................................................................................ 8-5
Relationships Between Superclasses and Subclasses ............................................................................................ 8-6
Inheritance: Syntax ............................................................................................................................................... 8-7
Redefining Methods .............................................................................................................................................. 8-8
Inheritance and Redefining the Constructor .......................................................................................................... 8-9
Rules for Calling the Constructor........................................................................................................................ 8-10
Inheritance and Visibility .................................................................................................................................... 8-11
Visibility of Protected Components .................................................................................................................... 8-12
Rules for Redefining Methods ............................................................................................................................ 8-13
Redefining Methods: Example ............................................................................................................................ 8-14
Inheritance: Unit Summary ................................................................................................................................. 8-15
Inheritance Exercises .......................................................................................................................................... 8-16
Inheritance Solutions........................................................................................................................................... 8-18
Casting ...................................................................................................................................................................... 9-1
Casting: Unit Objectives ....................................................................................................................................... 9-2
Casting: Integration in Course Content ................................................................................................................. 9-3
Casting (1) ............................................................................................................................................................. 9-4
Principle of Narrowing Cast .................................................................................................................................. 9-5
Compatibility and Narrowing Cast ....................................................................................................................... 9-6
Generic Access? .................................................................................................................................................... 9-7
Preparations for Generic Access (1)...................................................................................................................... 9-8
Preparations for Generic Access (2) ...................................................................................................................... 9-9
Polymorphism - Generic Access ......................................................................................................................... 9-10
Static and Dynamic Types of References............................................................................................................ 9-11
Comparison to Procedural Programming ............................................................................................................ 9-12
Casting (2) ........................................................................................................................................................... 9-13
Use of Widening Cast ......................................................................................................................................... 9-14
Widening Cast: Example..................................................................................................................................... 9-15
Casting (3) ........................................................................................................................................................... 9-16
Semantics and Use with Inheritance ................................................................................................................... 9-17
Incorrect Use of Inheritance ................................................................................................................................ 9-18
Casting: Unit Summary ....................................................................................................................................... 9-19
Casting Exercises ................................................................................................................................................ 9-20

Casting Solutions ................................................................................................................................................ 9-22


Interfaces ................................................................................................................................................................. 10-1
Interfaces: Unit Objectives .................................................................................................................................. 10-2
Interfaces: Integration in Course Content ........................................................................................................... 10-3
Interfaces (1) ....................................................................................................................................................... 10-4
Interfaces: Use..................................................................................................................................................... 10-5
Interfaces: Services ............................................................................................................................................. 10-6
Interface: UML Example .................................................................................................................................... 10-7
Defining and Implementing an Interface ............................................................................................................ 10-8
Interfaces: Features ............................................................................................................................................. 10-9
Interfaces (2) ..................................................................................................................................................... 10-10
Working with Interface Components ................................................................................................................ 10-11
Interface References: Narrowing Cast .............................................................................................................. 10-12
Using the Interface ............................................................................................................................................ 10-13
Polymorphism and Interfaces ............................................................................................................................ 10-14
Interface References: Widening Cast ................................................................................................................ 10-15
Interfaces (3) ..................................................................................................................................................... 10-16
Compound Interfaces ........................................................................................................................................ 10-17
Compound Interfaces: Example ........................................................................................................................ 10-18
Interfaces: Unit Summary ................................................................................................................................. 10-19
Interfaces Exercises........................................................................................................................................... 10-20
Interfaces Solutions ........................................................................................................................................... 10-25
Events ...................................................................................................................................................................... 11-1
Events: Unit Objectives....................................................................................................................................... 11-2
Events: Integration in Course Content ................................................................................................................ 11-3
Events: Overview ................................................................................................................................................ 11-4
Features ............................................................................................................................................................... 11-5
Triggering and Handling Events: Overview ....................................................................................................... 11-6
Defining and Triggering Events: Syntax ............................................................................................................. 11-7
Handling and Registering Events ........................................................................................................................ 11-8
Event Handler Methods....................................................................................................................................... 11-9
Registering for an Event: Syntax ...................................................................................................................... 11-10
Registration/Deregistration: Handler Tables ..................................................................................................... 11-11
Event Handling: Features .................................................................................................................................. 11-12
Events: Unit Summary ...................................................................................................................................... 11-13
Events Exercises ............................................................................................................................................... 11-14
Solutions ........................................................................................................................................................... 11-16
Global Classes and Interfaces ................................................................................................................................. 12-1
Global Classes and Interfaces: Unit Objectives .................................................................................................. 12-2

Global Classes and Interfaces: Integration in Course Content ............................................................................ 12-3


Global Classes and Interfaces (1) ........................................................................................................................ 12-4
Review: Local Classes and Interfaces ................................................................................................................. 12-5
Global Classes and Interfaces ............................................................................................................................. 12-6
Creating Global Classes in the Object Navigator ............................................................................................... 12-7
Class Builder: Attributes ..................................................................................................................................... 12-8
Class Builder: Methods ....................................................................................................................................... 12-9
Class Builder: Interface Methods ...................................................................................................................... 12-10
Class Builder: Method Interface ....................................................................................................................... 12-11
Class Builder: Method Implementation ............................................................................................................ 12-12
Class Builder: Inheritance ................................................................................................................................. 12-13
Class Builder: Test Environment ...................................................................................................................... 12-14
Global Classes and Interfaces (2) ...................................................................................................................... 12-15
Global Classes in the Object Navigator ............................................................................................................ 12-16
Class Builder: CREATE OBJECT .................................................................................................................... 12-17
Class Builder: CALL METHOD....................................................................................................................... 12-18
Global Classes and Interfaces (3) ...................................................................................................................... 12-19
SAP Grid Control .............................................................................................................................................. 12-20
Including a Grid Control Instance in a Dialog Program.................................................................................... 12-21
Displaying Data with a Grid Control Instance .................................................................................................. 12-22
Global Classes and Interfaces: Unit Summary .................................................................................................. 12-23
Exercises ........................................................................................................................................................... 12-24
Solutions ........................................................................................................................................................... 12-26
Special Techniques ................................................................................................................................................. 13-1
Special Techniques: Unit Objectives .................................................................................................................. 13-2
Special Techniques: Integration in Course Content ............................................................................................ 13-3
Special Techniques (1) ........................................................................................................................................ 13-4
Abstract Classes .................................................................................................................................................. 13-5
Final Classes ....................................................................................................................................................... 13-6
Special Techniques (2) ........................................................................................................................................ 13-7
Who Can Instantiate Classes? ............................................................................................................................. 13-8
Special Techniques (3) ........................................................................................................................................ 13-9
Friends............................................................................................................................................................... 13-10
Special Techniques (4) ...................................................................................................................................... 13-11
Persistence Service ............................................................................................................................................ 13-12
Features of the Persistence Service ................................................................................................................... 13-13
Class Agent ....................................................................................................................................................... 13-14
Special Techniques: Unit Summary .................................................................................................................. 13-15
Exercises - optional ........................................................................................................................................... 13-16

Solutions - optional ........................................................................................................................................... 13-19


Exception Handling................................................................................................................................................. 14-1
Exception Handling: Unit Objectives ................................................................................................................. 14-2
Exception Handling: Integration in Course Content ........................................................................................... 14-3
Class-Based Exceptions: Overview .................................................................................................................... 14-4
Exception Classes: The Inheritance Hierarchy ................................................................................................... 14-5
Handling Exceptions ........................................................................................................................................... 14-6
Example: Handling a Predefined Exception ....................................................................................................... 14-7
Example: Using Your Own Exceptions .............................................................................................................. 14-8
Creating Your Own Exception Classes ............................................................................................................... 14-9
Maintaining Your Own Attributes and Exception Texts ................................................................................... 14-10
Raising and Handling Exceptions You Have Written ....................................................................................... 14-11
Passing Exceptions Along ................................................................................................................................. 14-12
Example: Passing Exceptions Along ................................................................................................................. 14-13
Exceptions That Must Be Declared ................................................................................................................... 14-14
Exception Handling: Unit Summary ................................................................................................................. 14-15
Exception Handling Exercise 1 ......................................................................................................................... 14-16
Exception Handling Solution 1 ......................................................................................................................... 14-18
Dynamic Programming ........................................................................................................................................... 15-1
Dynamic Programming: Unit Objectives ............................................................................................................ 15-2
Dynamic Programming: Integration in Course Content ...................................................................................... 15-3
Dynamic Programming (1) ................................................................................................................................. 15-4
Field Symbols ..................................................................................................................................................... 15-5
The CASTING Addition ..................................................................................................................................... 15-6
Dynamic Programming (2) ................................................................................................................................. 15-7
Using Dynamic Attributes in Statements ............................................................................................................ 15-8
Calling Methods Dynamically ............................................................................................................................ 15-9
Dynamic Programming (3) ............................................................................................................................... 15-10
Data Reference Variables .................................................................................................................................. 15-11
Example: Using Data Reference Variables in Dynamic Method Calls ............................................................. 15-12
Generating Data Objects at Runtime ................................................................................................................. 15-13
Dereferencing Data References ......................................................................................................................... 15-14
Example: Generating Data Objects at Runtime ................................................................................................ 15-15
Dynamic Programming (4) ............................................................................................................................... 15-16
Ascertaining Internal Table Attributes .............................................................................................................. 15-17
Dynamic Type Descriptions for RTTI Classes ................................................................................................. 15-18
Declaring Types Dynamically: Example .......................................................................................................... 15-19
Dynamic Programming: Unit Summary ........................................................................................................... 15-20
Exercise 1 Optional ........................................................................................................................................ 15-21

Solution 1 - Optional ......................................................................................................................................... 15-24

BC401 ABAP Objects

BC401
ABAP Objects
SAP AG 2002

System: SAP R/3

System requirements: SAP R/3, Basis Release 6.10 or later

2002/Q3

Material number: 50054667

Copyright

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

SAP AG 2002

Notes on Trademarks:
Some software products marketed by SAP AG and its distributors contain proprietary software
components of other software vendors.

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.

TM
INFORMIX -OnLine for SAP and INFORMIX Dynamic Server are registered trademarks
of Informix Software Incorporated.

UNIX , X/Open , OSF/1 and Motif are registered trademarks of the Open Group.

HTML, DHTML, XML, and 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
developed and implemented by Netscape.
SAP, SAP Logo, R/2, RIVA, R/3, ABAP, 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 several other countries all over the
world. All other products mentioned are trademarks or registered trademarks of their respective
companies.

Course Prerequisites

Programming experience
SAPTEC
(mySAP Technology Solution Overview)
BC400
(ABAP Workbench: Foundations and Concepts)
Programming experience in ABAP

SAP AG 2002

Target Group

Participants: Developers, consultants


Duration: 5 days

SAP AG 2002

Notes to the user


The training materials are not appropriate for self-study. They complement the course instructor's
explanations. There is space for you to write down additional information on the sheets.
There may not be enough time during the course to complete all the exercises. The exercises are
intended as additional examples of the topics discussed during the course. Participants can also use them
as an aid to enhancing their knowledge after the course has finished.

Course Overview

Contents:
Course goal
Course objectives
Course content
Course overview diagram
Main business scenario

SAP AG 2002

(C) SAP AG

BC401

1-1

Course Goal

This course will enable you to:


Learn the principles of object-oriented

programming
Learn the structure and application of

ABAP Objects

SAP AG 2002

(C) SAP AG

BC401

1-2

Course Objectives

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


Describe and use the most important principles:
Internal tables
Classes/inheritance/interfaces
Polymorphism, inheritance, and interfaces
Events
Exception handling
Dynamic programming

Develop programs in ABAP Objects

SAP AG 2002

(C) SAP AG

BC401

1-3

Course Content (1)

Preface
Unit 1

Course Overview

Unit 2

Data Types and Data Objects in Detail

Unit 3

Using Internal Tables

Unit 4

Calling Programs and Passing Data

Unit 5

Introduction to Object-Oriented Programming

Unit 6

Analysis and Design

Unit 7

Principles of Object-Oriented Programming

Unit 8

Inheritance

Unit 9

Casting

Unit 10

Interfaces

SAP AG 2002

(C) SAP AG

BC401

1-4

Course Content (2)

Unit 11

Events

Unit 12

Global Classes and Interfaces

Unit 13

Special Techniques

Unit 14

Exception Handling

Unit 15

Dynamic Programming

Appendix

SAP AG 2002

(C) SAP AG

BC401

1-5

Course Overview: Integration in Course Content

rview
Course Ove
SAP AG 2002

(C) SAP AG

BC401

1-6

Main Business Scenario

A travel agent maintains its connections to

business partners - such as airlines, car hire


companies, and hotels

SAP AG 2002

(C) SAP AG

BC401

1-7

Technical Names

Package: BC401
Naming conventions for program objects:
Demonstrations:

SAPBC401_xxxD_...

Copy templates:

SAPBC401_xxxT_...

Model solutions:

SAPBC401_xxxS_...

xxx is the individual unit code

SAP AG 2002

Unit codes:
Unit 2: DTO
Unit 3: TAB
Unit 4: CAL
Unit 7: AIR
Unit 8: INH
Unit 9: CAS
Unit 10: INT
Unit 11: EVE
Unit 12: CLS
Unit 13: SPC
Unit 14: EXC
Unit 15: DYN

(C) SAP AG

BC401

1-8

Data Types and Data Objects in Detail

Contents:
Data objects in programs
Elementary data objects
Structures
Character string processing in Unicode

SAP AG 2002

(C) SAP AG

BC401

2-1

Data Types and Data Objects in Detail: Unit Objectives

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


Use elementary data objects and structures
appropriately
Use numeric data types appropriately
Use automatic type conversions appropriately
Take the special features of character string
processing in Unicode into account

SAP AG 2002

(C) SAP AG

BC401

2-2

Data Types and Data Objects in Detail:


Integration in Course Content

and
Data Types
in
ts
ec
O
bj
Data
Detail

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

2-3

Data Types and Data Objects in Detail (1)

Introduction
Introduction
Elementary
Elementary Data
Data Objects
Objects
Structures
Structures
Special
Special Features
Features in
in Unicode
Unicode

SAP AG 2002

(C) SAP AG

BC401

2-4

Revision: Defining Data Objects

Local types
TYPES type_name TYPE ...

Predefined
ABAP types
d
t
i
f
string
xstring

DATA do_name TYPE type_name.

p
n
c
x

Global
types

DATA do_name_new LIKE do_name.

SAP AG 2002

Data objects are usually defined with the DATA statement as follows. After the name of the data object, a
a fully-specified type is assigned to it using the TYPE addition. The type is linked to the data object
statically and cannot be changed at runtime.
There are other syntax variants available (for historical reasons). Note however, that some of these
historical variants are no longer supported in ABAP Objects. For further information, refer to the
keyword documentation for the DATA statement.
All types are based on predefined ABAP types, which will be discussed in greater detail in the following
slide. Some of these ABAP types are fully specified and can be used to type data objects directly. Other
types need to be modified to include the length, and in some cases the number of decimal places so that
they are fully specified. These are the simplest examples of user-defined types.
You can create complex structured types of any level of complexity, based on elementary types.
You can also define types centrally in the ABAP Dictionary. You can then use these global types in all
appropriate Repository objects in the system.

(C) SAP AG

BC401

2-5

Predefined ABAP Types


Data
type
Numeric

Fixed length

i
f
p

Description

Integer

Length in bytes

Float. point number 8


Packed number
1 .. 16

Attributes
Differ in:
Rules for storage
Value range
Arithmetic used

Character string type

n
c
d
t

Number sequence
1 .. 65535
Character sequence 1 .. 65535
Date
8
Time
6

Character string operations


(allowed for all types)
+ date calculations
+ time calculations

Hexadecimal

Variable
length

Hexadecimal code

1 .. 65535

Bit operations

Character string type / hexadecimal

string
xstring

Runtime system adjusts length


dynamically

Character sequence
Hexadecimal code

SAP AG 2002

The following ABAP types are fully specified and can be used directly to type data objects: d, t, i, f,
string, and xstring. A special feature of the string and xstring types is that their length is
adjusted dynamically at runtime. Thus, for these two types, length is not a component of the type.
The following ABAP types are not fully specified, so you must include additional information before
you use them to define data objects:
c, n, and x
Length needs to be added. Permitted values: 1 to 65535 characters.
If you do not declare a length when you define a data object, the system assigns the default length of
1.
p
You must extend the type to include the length, and number of decimal places, Permitted length: 1 to
16 bytes. If you do not declare a length when you define a data object, the system assigns the default
length of 8 bytes (that is, 15 digits) and 0 decimal places.
The type also contains information on how the data is stored, what range of values is allowed, what
operations can be performed on the data, and what sort of arithmetic is used (if the data object is suitable
for use in calculations). We will deal with this topic in greater detail later in this unit.

(C) SAP AG

BC401

2-6

Type Groups in the ABAP Dictionary


Name of type group:
Up to 5 characters;
each type name and
constant name
starts with the name of
the type group.

Each type group, whose


types and constants you
want to use, must be specified
in the ABAP program

Type group zmytp


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

Using a constant:
ABAP program

TYPE-POOLS:
TYPEzmytp
TYPE-POOLS zmytp.
[ DATA var TYPE zmytp
zmytp_type1. ]
IF var = zmytp
zmytp_const_name.
...
ENDIF.
SAP AG 2002

You must use a type group to define global constants. The name of the type group can contain up to 5
characters.
You define constants in the type group using the CONSTANTS statement, just as in an ABAP program.
You only have to adhere to the following namespace convention:
All constants (and type names) must have the name of the type group as a prefix.
You can use either a global Dictionary type or a predefined ABAP type as a valid type.
To be able to use the types of a type group in a program, you must refer to the type group using the
TYPE-POOLS statement.
After this line in the program, you can then use all the constants in the type group.
You can also define global data types in a type group. Before SAP R/3 Basis Release 4.5, this was the
only way to define complex global data types.

(C) SAP AG

BC401

2-7

Data Types and Data Objects in Detail (2)

Introduction
Introduction
Elementary
Elementary Data
Data Objects
Objects
Structures
Structures
Special
Special Features
Features in
in Unicode
Unicode

SAP AG 2002

(C) SAP AG

BC401

2-8

Integers and Integer Arithmetic

DATA: counter TYPE i VALUE 1.

int1 = int2 / int3 + int4.

Length: 4 bytes

Value range [-2147483648; 2147483647]

Integer Arithmetic

All internal auxiliary fields are integers


Interim results are rounded

int2 =

int1

int3 =
4

3
3

/
1

int4 =

Arithmetic operations for


integers:

Integer auxiliary variable

+
*
/
DIV
MOD
**

Addition
Subtraction
Multiplication
Division
Integer division
Remainder integer div.
Power

SAP AG 2002

In integer arithmetic, the system always rounds to the appropriate decimal place. So, for example:
DATA int TYPE i.
int = 4 / 10.
" result: 0
int = 5 / 10.
" result: 1
Calculations performed using integer arithmetic are faster than calculations using fixed point or floating
point arithmetic.
For further information on calculations performed on integers, refer to the keyword documentation for
the COMPUTE statement.

(C) SAP AG

BC401

2-9

Packed Numbers and Fixed Point Arithmetic


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

Length in bytes:
n bytes correspond to
2n - 1 digits

Number of decimal
places

Fixed point arithmetic:


"like using paper and pencil"
Number 12,34

1234,56
78,5
1313,06

Internal representation
0 1 2 3 4 +
1 digit per
half-byte

Sign

Permitted length: 1 to 16 bytes (= 1 to 31 digits)


Number of decimal places < number of digits, max. 15
Example: Length 3 bytes, 2 decimal places
Value range: [-999.99,+999.99]

SAP AG 2002

The length of packed numbers is given in bytes. The connection between value range and length is
derived from the internal representation: Each decimal digit is represented by a half-byte. The last byte is
reserved for the plus or minus sign.
The number of decimal places is defined using the DECIMALS addition. The maximum number of
decimal places is either 15 or the length of the number minus 1 (that is, there must be at least one digit
before the comma).
In user dialogs, decimal numbers are formatted according to the settings in the user master record.
Decimal point-aligned fixed point arithmetic is used as default for calculations. Packed numbers are thus
well-suited to business calculations, where the correct rounding for the specified number of decimal
places is very important. The algorithm for this arithmetic is similar to using "pencil and paper".
The system always uses packed numbers of maximum length for interim results.
You can switch off fixed point arithmetic in the program attributes. If you do, the DECIMALS addition
when defining a packed number only affects the output of the number. Internally, all numbers are
interpreted as integers, regardless of the position of the decimal point. The fixed point arithmetic option
is always selected by default. You should always accept this value and use packed numbers for business
calculations.

(C) SAP AG

BC401

2-10

Floating Point Arithmetic


|

1,5 = 120 + 12 1
1
=1 +
2

Only 53 bits available

| 0 0 |

| ...

| 0 0 |

0,15 = 12 3 + 12 6 + 12 7 + 12 10 + 12 11 +
1
1
1
1
1
=
+
+
+
+
+
8
128 1024 2048
64

= 0,125 +
=
=
=

0,140625 +

Only for
approximations

0,1484375 +
0,1494140625 +

0,1499023437

SAP AG 2002

Unlike packed numbers, floating point numbers are represented using sums of binary fractions. Floating
point numbers are also normalized, and both the exponent and the mantissa are stored in binary form.
This representation complies with the IEEE norm for double precision floating point numbers. The
floating point operations of the relevant processors are used for calculations.
Since algorithms are converted to binary, inaccuracies can occur. Therefore, floating point numbers are
not suitable for business calculations.
Example:
You want to calculate 7.72% of 73050 and display the result accurate to two decimal places. The answer
should be 5310.74 (73050 * 0.0727 = 5310.7735). The program, however:
DATA: float TYPE f, pack TYPE p DECIMALS 2.
float = 73050 * '0.0727'. " result: 5.3107349999999997E+03
pack = float. WRITE pack. " result: 5310.73
You should therefore only use floating point numbers for approximations. When you compare
numbers, always use intervals, and always round at the end of your calculations.
The advantage of floating point numbers is the large value range: It comprises numbers from is, from
2,2250738585072014E-308 to 1,7976931348623157E+308 including both positive and negative
numbers as well as zero. In addition, you must use floating point numbers for special aggregation
functions of the SELECT statement.

(C) SAP AG

BC401

2-11

Summary: Recommendations for Using Numeric


Data Types

Required:

Integers only

Recommended predefined ABAP data type:


Type i,
since calculations using integer arithmetic are
fastest

Decimal numbers for


business calculations

Type p

Decimal numbers for


rough calculations
performed on very small
or very large numbers

Type F

SAP AG 2002

Note:
The results of the following functions have the data type f:
Trigonometric functions: cos, acos, sin, asin, tan, atan
Hyperbolic functions: tanh, sinh, cosh
Exponential functions (base e): exp
Natural logarithms (base e): log
Logarithms (base 10): log10
Square root: sqrt

(C) SAP AG

BC401

2-12

Arithmetic and Mixed Expressions

Fixed point arithmetic is the default


Integer arithmetic is only used if all the components are integers
Floating point arithmetic is used if at least one component is a floating point number
All components are converted to the relevant data type
After the calculation, all are converted to the result type

Example:
p DECIMALS 3
r

i
=

a
201

i
/

0.0000...E+000

1.004999...E+000 +

0.0000...E+000

200

Float. point arithmetic

+
+

Conversion after f
and calculation

Interim result:
=

1.004999...E+000

1.005

Conversion after
p DECIMALS 3

SAP AG 2002

An arithmetic expression may contain any data types that are convertible into each other and into the
type of the result field.
The system converts all the values into one of the three numeric data types (i, p, or f), depending on the
data types of the operands. The ABAP runtime system contains an arithmetic for each of the three data
types. The system then performs the calculation and converts it into the data type of the result field.
This may mean that the same arithmetic expression leads to different results when performed on
different combinations of data types.
It is also possible for an arithmetic expression to have only character string type data objects, as long
as their contents are appropriate. The values are converted to numeric type objects. Bear in mind that
conversions affect performance. Wherever possible, choose a data type that does not require runtime
conversion.
If an arithmetic expression contains numeric literals, the choice of arithmetic depends on the size of the
number: If the number is within the value range for the data type i, the numeric literal is interpreted as
an integer. If the value of the literal is greater than 2147483647, it is interpreted as a packed number.
Example:
DATA int TYPE i. int = 1000000000 / 300000000 * 3. "result: 9
int = 10000000000 / 3000000000 * 3. "result: 10

(C) SAP AG

BC401

2-13

Predefined ABAP Types for Character Strings

Type t

Type d

Type n

Time

Date

6 digits
HHMMSS

8 digits
1 .. 65535
YYYYMMDD characters

Description

Length

Value range

Calculations

Formatting
options

By clock

Time
arithmetic
HH:MM:SS

Type c

Sequence FixedFixed-length
of digits
char. string

By Gregorian
calendar

Date
arithmetic

Digits

Conversion

1 .. 65535
characters

Type string
Char. string
of variable
length
Variable

Depends on codepage
Conversion

Conversion

Based on
user default
values

SAP AG 2002

The value range of each string depends on the code page, which contains all the supported characters in
form of a table. Internally, each character is represented by a code number. When the system outputs the
character, it uses the code page to convert this number. To find the code page valid in a given system,
choose Tools CCMS Spool Administration Full Administration Character Sets.
The initial value of each character string with fixed length is a space character.
Numeric strings are represented internally as character strings. Note, however, that only digits are
permissible as characters. When character strings are assigned to numeric strings, the system ignores
letters and only copies the digits (right-aligned). Missing characters are filled with zeros.
The initial value of each character in a numeric string is a zero.
Only sequences of digits are valid for values of type d. These digits form a meaningful date, which
complies with the Gregorian calendar. The first four digits represent the year, the next two the month
and the last two the date. For performance reasons however, the object is only checked if it is an input
field on a screen or selection screen.
The initial value of a date is '000000'. The formatting options are determined by the user settings.
For values of type t, a sequence of digits is only valid if it can be interpreted as a time on the 24-hour
clock. The rules for interpreting the value are analogous to those used for dates.
The initial value of a time is '000000'.

(C) SAP AG

BC401

2-14

Overview: Character String Processing


Description and notes
Found: sy-subrc = 0

FIND

ABAP

Search in a character string


Position of search string
using MATCH OFFSET off addition

REPLACE

ABAP

BBAP

Replace first occurrence

TRANSLATE

ABAP

a b ap

Replace all occurrences

SHIFT

ABAP
AP
AB P

BAP
AP

Move

CONDENSE
OVERLAY

ABAP

Overwrite : Spaces are overwritten


by characters from the second
character string

A B +A P

ABAP

Concatenate several
character strings

ABCAP

AB

Split a character string

AAAA
CONCATENATE
SPLIT

Remove space characters

AP

SAP AG 2002

Note for FIND statement (search in a character string):


There are special comparison operators for strings, which you can use in logical expressions in a query
(IF) to search more flexibly for character sequences in a character string. For more information, see the
keyword documentation for IF.
For every statement, the operands are treated like type c fields, regardless of their actual field type. No
internal type conversions take place.
All of the statements apart from TRANSLATE and CONDENSE set the system field sy-subrc.
(SEARCH also sets the system field sy-fdpos with the offset of the character string found.)
All of the statements apart from SEARCH are case-sensitive.
To find out the occupied length of a string, use the standard function STRLEN().
For the SPLIT statement there is the variant SPLIT ... INTO TABLE <itab>, which you can
use to split the character string dynamically. You do not need to specify the number of parts into which
the string should be split.

(C) SAP AG

BC401

2-15

Accessing Parts of Fields

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

Possible with any


character-type field

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

19991231ttA235959

000000

SAP AG 2002

In any statement that operates on a character-type field, you can address part of the field or structure by
specifying a starting position and a number of characters. If the field lengths are different, the system
either truncates the target or fills it with initial values. The source and target fields must have the type x,
c, n, d, t, or STRING. You can also use structures.
Example
MOVE <field1>+<off1>(<len1>) TO <field2>+<off2>(<len2>).
This statements assigns <len1> characters of field <field1> starting at offset <off1> to <len2>
characters of <field2> starting at offset <off2>.

(C) SAP AG

BC401

2-16

Data Types and Data Objects in Detail (3)

Introduction
Introduction
Elementary
Elementary Data
Data Objects
Objects
Structures
Structures
Special
Special Features
Features in
in Unicode
Unicode

SAP AG 2002

(C) SAP AG

BC401

2-17

Defining Structures with Local Types


Definition of a structure type

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

Definition of a structure with


implicit type construction

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

Definition of a structure with


reference to a user-defined type

DATA:
s_name TYPE s_name_type .
Alternatives

START-OF-SELECTION.
s_name-prename
= 'Smith'.
s_names_name-surname
= 'John'.
s_nameSAP AG 2002

As with elementary data objects, you can define structures in two ways:
First, define a structure type explicitly using the TYPES statement.
To do this, enter the name of the structure after BEGIN OF and then list the definitions of all the
components. End the definition of the structure type using END OF.
You then define the structured data object with the DATA statement, using your own user-defined
structure type.
Define the data object directly using the DATA statement. The syntax is similar to the definition of a
structure type. If you use this option, the corresponding structure type is defined implicitly at the same
time.
In both cases, the type is defined locally. Bear in mind that you can also use globally defined types
instead.
You address components of structures using:
structure_name-comp_name.
For this reason, you should avoid using hyphens in variable names.

(C) SAP AG

BC401

2-18

Defining Nested Structures with Local Types


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

Structure type
s_name_type
prename
surname
title

DATA:
BEGIN OF s_address,
name
TYPE s_name_type
s_name_type,
street(15) TYPE c,
city(25)
TYPE c,
END OF s_address.

Nested structure
s_address
name
prename
surname
title
street
city

s_address-name-surname
= 'Smith'.
s_address-city
= 'London'.
-

Application:
Logical subgrouping
of data

SAP AG 2002

You can define nested structures by assigning a structure type to a component within a structure type.
You can address this substructure as a whole using the component name:
structure_name-substructure_name.
You can also address individual components in the substructure:
structure_name-substructure_name-comp_name.
Structures can be nested to any level you wish.
You can also integrate components of a dynamic type in a structure. This can either be an elementary
data object of variable length (string or xstring),an internal table, or a reference. These structures
are known as deep structures.
There are constraints on how such deep structures can be used. For instance, a deep structure cannot be
used as a whole in the INTO clause of the SELECT statement. (Instead, each component must be listed
separately). Offset operations are also not appropriate. For more information, refer to SAP Note 176336.

(C) SAP AG

BC401

2-19

Using Named Includes


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

Structure type
s_name_type
prename
surname
title

DATA
BEGIN OF s_address.
INCLUDE
INCLUDE STRUCTURE
STRUCTURE s_name_type
AS name.
DATA:
street(15) TYPE c,
city(25)
TYPE c,
END OF s_address.
s_address-name-surname
= 'Smith'.
* or:
s_address-surname
= 'Smith'.

Structure with named include


s_address
prename
surname
title
street
city

name

Use:
Logical subgroup desired, but nested
structures not technically possible

SAP AG 2002

In some cases, you cannot use nested structures, for example:


Because you can only define database tables with flat line types
In situations where user dialogs with a table-type display can only contain simple structures (such as
in the SAP List Viewer or Table Control)
In situations like these, you may still want to group parts of the structure and address it as a whole. You
do this using named includes:
You can include a substructure in another structure, and give this substructure a name:
DATA: BEGIN OF structure_name,
... .
INCLUDE STRUCTURE substructure_type AS name.
DATA: ... ,
END OF structure_name.
You can address this substructure using structure_name-name. You can address the fields in the
substructure using structure_name-name-comp_name or directly using structure_namecomp_name. Technically, however, this structure is not nested.
If naming conflicts occur - for example, if you want to include the same substructure twice - you can
append another name to the component names using RENAMING. For further information, refer to the
keyword documentation for the INCLUDE STRUCTURE statement.

(C) SAP AG

BC401

2-20

Data Types and Data Objects in Detail (4)

Introduction
Introduction
Elementary
Elementary Data
Data Objects
Objects
Structures
Structures
Special
Special Features
Features in
in Unicode
Unicode

SAP AG 2002

(C) SAP AG

BC401

2-21

Unicode: Overview

Previous problems

Mixture of different incompatible character sets in one central


system

Data exchange between systems with incompatible character sets

a
Solution: Unicode

a
Unicode

ONE codepage that


comprises all known
characters

Every character is generally


displayed by two bytes

SAP AG 2002

To be able to work with Unicode, you must have a Unicode-compatible SAP System installed that itself
has a corresponding operating system and database. The ABAP programs must also be Unicodecompatible.
In Unicode programs, other syntax rules apply than in non-Unicode programs. This is due to the
difference between the length in bytes and the number of characters in a character set in Unicode.
Existing programs are affected by a conversion to Unicode if an explicit or implicit assumption is made
about the internal length of a character. To execute the relevant syntax checks, you must check Unicode
Checks Active under program attributes.
In a Unicode system, you can only execute programs that have the Unicode flag set. If the Unicode flag
is set for a program, the syntax check and program are executed in accordance with the rules described
in the Unicode online help (irrespective of whether it is a Unicode or a non-Unicode system).
If the Unicode flag is not set, the program can only be executed in a non-Unicode system. For such
programs, the Unicode-specific changes of syntax and semantics do not apply. However, you can use all
language enhancements introduced in connection with the conversion to Unicode.

(C) SAP AG

BC401

2-22

Character-Type and Byte-Type Types

Character-type types in Unicode programs


byte-type
Only components
with the types
c, n, d, and t

d
c
t

Character-type
structure types

xstring

string

Difference between byte processing and character processing


c_field

DATA: c_field(4) TYPE c VALUE 'HUGO',


x_field(4) TYPE x VALUE 'E391B9A2'.

SHIFT c_field BY 2 PLACES [IN CHARACTER MODE].


SHIFT x_field BY 2 PLACES IN BYTE MODE.

x_field
G

O
E391B9A2

_
B9A20000

SAP AG 2002

In Unicode programs, the following data types are interpreted as character-type:


c, n, d, t, string as well as structure types, that directly or in substructures only contain components
with types c, n , d and t. In non-Unicode systems, a character of this type is one byte and in Unicode
systems, it is as long as corresponds with the length of a character on the relevant platform. Variables of
the types x and xstring are described as byte-type.
The character string processing (for which, previously, all arguments were implicitly interpreted as type
c fields) is separated into string processing for character-type and byte-type arguments.
In the case of the string processing for character-type arguments, the single fields must be type c, n, d,
t, or string; character-type structures are also permitted. If arguments of another type are transferred,
this triggers a syntax or runtime error.
The X variants of the string statement are distinguished from the character string commands by the IN
BYTE MODE addition. For the character string variants, IN CHARACTER MODE is an optional
addition. If the IN BYTE MODE addition is specified, only X fields and X strings are permitted as
arguments. If arguments of another type are transferred, this triggers a syntax or runtime error.

(C) SAP AG

BC401

2-23

Functions and Comparison Operators


Length in
bytes

Length in
characters
Character-type type

Functions

STRLEN
STRLEN

Byte-type type

XSTRLEN
BYTE-CO, BYTE-CA,

Comparison
operators

CO, CA, CS, CP,


CN, NA, NS, NP

BYTE-CS, BYTE-CN,
BYTE-NA, BYTE-NS

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

DATA: x_field(4) TYPE x


VALUE 'E391B9A2',
len TYPE i.
len = XSTRLEN( x_field ).

SAP AG 2002

The operators CO, CN, CA, NA, CS, NS, CP, NP are available for comparing the contents of character
string type data objects (for syntax and semantics, see keyword documentation). As with the statements
for string processing, these operators require single fields of type c, n, d, t, or string as arguments.
Again, character-type structures are also permitted.
The X variants of the string comparison operators are distinguished from the character string variants by
the BYTE- prefix. For this operation, only X fields and fields of the type xstring are allowed as
arguments.
The STRLEN function only works with character-type fields and returns the length in characters. With c
fields, only the so-called occupied length is relevant, that is, unlike with strings, trailing blanks are not
counted.
The XSTRLEN function is available for the length of byte sequences. For X strings, XSTRLEN returns
the current length and for X fields, the defined length in bytes, where null bytes at the end of fields are
counted.

(C) SAP AG

BC401

2-24

Compatibility and Conversion


MOVE a TO b.
b = a.

When are two types compatible?


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

Two table types are compatible if their row types are


compatible
compatible and their key
key definitions
definitions and table types
are the same.

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

If non-type-compatible data objects are assigned, conversion does take


place if a conversion rule is defined

SAP AG 2002

If two data types are not compatible but there is a conversion rule, the system converts the source object
into the type of the target object when you assign values, perform calculations, or compare values.
For a full list of all conversion rules, refer to the ABAP syntax documentation for the MOVE statement.
If there is no conversion rule defined for a particular assignment, the way in which the system reacts
depends on the program context.
If the types of the objects involved are defined statically, a syntax error occurs.
Example:
DATA: date TYPE d VALUE '19991231', time TYPE t.
FIELD-SYMBOLS: <fs_date> TYPE d, <fs_time> TYPE t.
ASSIGN: date TO <fs_date>, time TO <fs_time>.
<fs_time> = <fs_date>.
In the case of dynamic typing a runtime error occurs, because the field symbols are not assigned types
until the assignment of the data objects at runtime.
Example:
...
FIELD-SYMBOLS: <fs_date> TYPE ANY, <fs_time> TYPE ANY.
...
(Rest as above)

(C) SAP AG

BC401

2-25

Conversion Under Unicode (1)


Conversion between flat structures
MOVE struc1 TO struc2.

struc1
C(6)

Under what condition


is this assignment
possible?

N(4)

X(3)

N(4)

C(3) C(3) X(3)

C(4)

C(4)

P(8)

struc2
C(4)

struc1

Decisive criterion:
Fragment view

struc2

C(10)

Assignment is possible

X(3)

P(8)

Conversion between flat structures is possible if the fragments of


the source and target structures match both in type and length in
the length of the shorter structure.

SAP AG 2002

For some data types there are, for technical reasons, specific alignment requirements that depend on the
individual platforms. (In the memory, fields of this type must begin and end on specific addresses - for
example, a memory address divisible by four.)
Within a structure, the runtime system, if necessary, inserts bytes before or after these components with
alignment requirements to achieve the alignment needed. These bytes are known as Alignment.
To check whether the conversion is even permitted, the system first creates the Unicode fragment view
of the structures by grouping adjacent components and alignment gaps (one group each for charactertype types [c, n, d, t], byte-type types, and types i, f, and p).
Adjacent character-type components of a structure are therefore only grouped together if there are no
alignment gaps between these components. Adjacent byte-type components are grouped in the same
way.
If the fragments of the source and initial structures match the type and length in the length of the shorter
structure, the conversion is allowed.
If the target structure is longer than the source structure, the character-type components of the
remainder are filled with space characters. All other components in the remainder are filled with the
type-specific initial value, alignment gaps are filled with null bytes.

(C) SAP AG

BC401

2-26

Conversion Under Unicode (2)


Conversion between structures and single fields
MOVE c_field TO struc.

c_field
C(9)

Under what condition


is this assignment
possible?

struc
C(6)

N(4)

X(3)

C(4)

c_field

Decisive criterion:
Fragment view
struc

Assignment is possible

Conversion between
.
structures and single fields is possible if
the structure begins with a character-type fragment and this
fragment is at least as long as the single field.

SAP AG 2002

The following rules apply for the conversion of a structure to a single field and vice versa:
If the single field is type c, but the structure isn't completely character-type, the conversion is only
allowed if the structure begins with a character-type group and this group is at least as long as the
single field. The conversion then takes place between the first character-type group of the structure and
the single field. If the structure is the target field, the character-type parts of the remainder are filled
with space characters and all other components with the type-specific initial value.
The conversion is not allowed if the structure is not purely character-type and the single field is not type
c.
Internal tables can be converted if their row type can be converted.

(C) SAP AG

BC401

2-27

Example of Using the Conversion Rules

PARAMETERS p_date LIKE sy-datum.


DATA: BEGIN OF s_date,
year(4) TYPE n,
Character-type
month(2) TYPE n,
single field
day(2)
TYPE n,
END OF s_date.
MOVE p_date TO s_date.
s_date-day = '01'.
MOVE s_date TO p_date.

p_date

Character-type
structure

s_date

Since the structure s_date is purely character-type, it is treated like


a type c data object during conversion.

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

SAP AG 2002

s_date is structured in such a way that the first four characters of a variable specify the year, the next
two specify the month, and the last two the day. If a date is assigned to this structure using the MOVE
statement, the characters are then copied left-aligned. You can then determine the year, month, and day
directly using the components of the structure, without having to use offsets.

(C) SAP AG

BC401

2-28

Offset and Length Accesses and Elementary Data


Objects
Access to single fields specifying offset and length
<statement> <field>+<off>(<len>) ...

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


x_field(6) TYPE x VALUE 'E391B9A203F6'.

c_field

x_field

WRITE: c_field+1(4),

E391B9A203F6

x_field+3(2).

For character-type fields, offset and length are interpreted character


by character.

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

SAP AG 2002

Offset/length accesses are permitted on character-type single fields, single fields with the type
string, and single fields of the types x and xstring.
For character-type fields and type string fields, offset and length are interpreted character by
character. Only with types x and xtring are the values for offset and length taken in bytes.

(C) SAP AG

BC401

2-29

Offset and Length Accesses and Structures

Accessing structures by specifying offset and length


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

DATA: BEGIN OF member,


title(5)
TYPE
prename(15) TYPE
surname(15) TYPE
age
TYPE
city(20)
TYPE
END OF member.

c,
c,
c,
i,
c,

member
C(5)

C(15)

C(15)

C(20)

+off(len)

PERFORM use_name USING member+5(30).

Structure must start with a character-type fragment.

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

Offset and length specifications are interpreted as characters.

SAP AG 2002

Offset and length accesses to structures are only permitted in Unicode programs if the structure is flat
and the offset and length specifications only contain character-type fields from the beginning of the
structure. This means, the access will cause an error if the offset and length area contains both
character-type and non-character-type components.
If an offset/length access is allowed in a Unicode program, both offset and length specifications are
interpreted as characters.
Recommendation:
Only use offset and length accesses if it is necessary or useful. Bear in mind that processing component
by component and using character string operations is generally safer and more readable.

(C) SAP AG

BC401

2-30

Data Types and Data Objects in Detail: Summary

You are now able to:


Use elementary data objects and structures
appropriately
Use numeric data types appropriately
Use automatic type conversions appropriately
Take the special features of character string
processing in Unicode into account

SAP AG 2002

(C) SAP AG

BC401

2-31

Data Types and Data Objects in Detail Exercise 1


Unit: Data Types and Data Objects in Detail
Topic: Defining Data Types and Data Objects
Basic Statements
Processing Character Strings
At the conclusion of these exercises, you will be able to:
Define structure types locally in the program
Define elementary and complex data objects
Split strings
Use conversion rules
Display the contents of data objects in lists
In this exercise, you will use a template to create a program that
receives a single data record from the database table SFLIGHT in
form of a character string. The program will split the this
character string into its components and display it formatted in a
list.
Because the focus of this exercise is not on the transfer of data as
a character string, we will use a function module that will provide
us with the required database. This will simulate actual cases,
such as data transfer from an external system.
ZBC401_##_SPLIT_STRING

Program:
Template:

SAPBC401_DTOT_SPLIT_STRING

Model solution:

SAPBC401_DTOS_SPLIT_STRING

## is your two-digit group number


1-1

Copy the program, SAPBC401_DTOT_SPLIT_STRING and give it the new name


ZBC401_##_SPLIT_STRING.

1-2

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

1-3

To be able to split the character string into its components you must first remove the ##
characters. Remove the two leading separators from the character string first. Then

(C) SAP AG

BC401

2-32

copy the initial part up to the closing separators to the auxiliary variable
set_string. For this, set_string has to be defined appropriately.
1-4

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

1-5

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

1-6

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

(C) SAP AG

BC401

2-33

Data Types and Data Objects in Detail Solution 1


Unit: Data Types and Data Objects in Detail
Topic: Defining Data Types and Data Objects
Basic Statements
Processing Character Strings
REPORT

sapbc401_dtos_split_string.

TYPES:
BEGIN OF st_flight_c,
mandt(3)

TYPE c,

carrid(3)

TYPE c,

connid(4)

TYPE n,

fldate(8)

TYPE n,

price(20)

TYPE c,

currency(5)

TYPE c,

planetype(10)

TYPE c,

seatsmax(10)

TYPE n,

seatsocc(10)

TYPE n,

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

TYPE c,

connid(4)

TYPE n,

fldate

TYPE d,

price(9)

TYPE p DECIMALS 2,

currency(5)

TYPE c,

planetype(10) TYPE c,
seatsmax

TYPE i,

seatsocc

TYPE i,

END OF st_flight.
(C) SAP AG

BC401

2-34

DATA:
datastring

TYPE string,

set_string

TYPE string,

wa_flight_c TYPE st_flight_c,


wa_flight

TYPE st_flight.

START-OF-SELECTION.
CALL FUNCTION 'BC401_GET_SEP_STRING'
* EXPORTING
*

IM_NUMBER

= '1'

IM_TABLE_NAME

= 'SFLIGHT'

IM_SEPARATOR

= '#'

IM_UNIQUE

= 'X'

IMPORTING
ex_string

= datastring

EXCEPTIONS
no_data

= 1

OTHERS

= 2.

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

SHIFT datastring BY 2 PLACES.


FIND '##' IN datastring.
IF sy-subrc <> 0.
MESSAGE a702(bc401).
ENDIF.
SPLIT datastring AT '##' INTO set_string datastring.

SPLIT set_string AT '#' INTO


wa_flight_c-mandt
(C) SAP AG

BC401

2-35

wa_flight_c-carrid
wa_flight_c-connid
wa_flight_c-fldate
wa_flight_c-price
wa_flight_c-currency
wa_flight_c-planetype
wa_flight_c-seatsmax
wa_flight_c-seatsocc
wa_flight_c-paymentsum
wa_flight_c-seatsmax_b
wa_flight_c-seatsocc_b
wa_flight_c-seatsmax_f
wa_flight_c-seatsocc_f.

MOVE-CORRESPONDING wa_flight_c TO wa_flight.


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

(C) SAP AG

BC401

2-36

Using Internal Tables

Contents:
Introduction and advantages of internal tables
Defining internal tables
Internal table operations
Notes on performance
Special internal tables

SAP AG 2002

(C) SAP AG

BC401

3-1

Using Internal Tables: Unit Objectives

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


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

SAP AG 2002

(C) SAP AG

BC401

3-2

Using Internal Tables: Integration in Course


Content

and
Data Types
ts in
Data Objec
Detail

Using
Internal
Tables
rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

3-3

Using Internal Tables (1)

Introduction
Introduction and
and advantages
advantages of
of internal
internal tables
tables
Definition
Definition
Operations
Operations
Special
Special situations
situations
Notes
Notes on
on performance
performance

SAP AG 2002

(C) SAP AG

BC401

3-4

The Internal Table - a Data Object of Variable Length

Elementary data objects

Structures

ABAP
program

Static data objects


(except for
types STRING, XSTRING)

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

SAP AG 2002

Internal tables are data objects that allow you to store datasets with a fixed structure in memory. The
data is stored line by line in memory. Each line has the same structure.
You can also refer to each component in a line as a column in the internal table. You refer to each line in
the internal table as a table line or table entry.
Internal tables are dynamic data objects - that is, they can hold any number of lines of a fixed type. The
number of lines in an internal table is limited only by the capacity of the specific system with which you
are working.
You can define the line type of an internal table to include elementary, structured, or even table types,
and can be as complex as you want to make it.

(C) SAP AG

BC401

3-5

Attributes of Internal Tables

Line type

CARRID CONNID DISTANCE DISTID


Line
index

AA

0017

2.572

MI

LH

0400

6.162

KM

LH

0402

5.136

KM

QF

0005

10.000

MI

SQ

0866

1.625

MI

UA

0007

2.572

MI

Index access
2

Key access
SQ 0866

Table kind
Standard table
Sorted table
Hashed table

Key definition
Key fields
Sequence
Uniqueness
SAP AG 2002

Each internal table has the following attributes:


Line type:
You use the line type to specify which columns are to be included in your internal table. You must
assign a name and type to each column. You generally define a line type using a structure type.
Key:
Internal tables have a key, just like database tables. The key is defined by: Specifying the columns
that should belong to the key; the sequence; and whether or not the key should be unique or nonunique.
Depending on how you define your internal table, the runtime system may create an additional
unique key (the index) for some internal tables (this will be discussed in more detail later). For
simplicity's sake you can think of the index as a line number.
Table kind:
There are three table kinds in ABAP. Each kind has different attributes, which specify whether the key
is unique, how the index is managed, and how the table data is addressed internally. The table kind
specifies the possible accesses. The purpose of this is to provide particular support for special access
types from the runtime system (will be discussed later).

(C) SAP AG

BC401

3-6

Link Between Table Kind and Access Type

Index tables
Table kind

STANDARD TABLE

Hashed table

SORTED TABLE

HASHED TABLE

Index access
n

Key access

Binary
search

Table scan

Hash
function

Uniqueness

NON- UNIQUE

UNIQUE | NON-UNIQUE

UNIQUE

Access by

Mostly index

Mostly key

Key only

SAP AG 2002

The table kind is linked to the access type as follows:


You can only perform an index access (the fastest type of access) on STANDARD and SORTED tables.
The runtime system implements key accesses of SORTED and HASHED tables in a way that optimizes
runtime performance. Key access of STANDARD tables is by table scan - that is, comparing the field
contents with the search key line by line, in a loop.
The runtime system implements key accesses of SORTED tables, for fully or partly qualified keys (leftaligned, no gaps, all fields filled with an "=") in a special way to optimize runtime.
The same applies to partial sequential loops, where the loop condition is specified using the key fields.
With the runtime-optimizing access, the runtime system keeps SORTED tables sorted by key fields,
In all other cases, the system performs a table scan.
The runtime optimizes key accesses of HASHED tables for fully qualified keys only. The table entries
are addressed by means of a special hash algorithm. This minimizes access time for reading single
records with fully qualified keys. The access time is thus independent of the number of lines in the table.
In all other cases, the system performs a table scan. This means that you should only use HASHED tables
if you want to access table entries using a fully-qualified key.

(C) SAP AG

BC401

3-7

Using Internal Tables (2)

Introduction
Introduction and
and advantages
advantages of
of internal
internal tables
tables
Definition
Definition
Operations
Operations
Special
Special situations
situations
Notes
Notes on
on performance
performance

SAP AG 2002

(C) SAP AG

BC401

3-8

Overview: Types of Definitions for Internal Tables

With local table type

Implicit table type

Local table type

With global table type

Global table type

TYPES:
local_type ...

global_type

Table
attributes

Table
attributes

Internal table

Internal table

Internal table

DATA:
t_list TYPE

DATA:
t_list TYPE ...

DATA:
t_list TYPE
global_type
global_type.

local_type
local_type.

Table
attributes

SAP AG 2002

There are several ways to define an internal table in ABAP:


Use the TYPES statement to define a table type. Then use this to assign a type to one or more data
objects or interface variables.
Alternatively, declare the table attributes directly when you define the data object (that is, use a bound
type).
The third option is to define an internal table using a global table type (defined in the ABAP
Dictionary).
The tables you define using the first or second option are visible only in the program in which you define
them. Whenever you need table type visible from all programs, create a global table type (that is, use the
third option).

(C) SAP AG

BC401

3-9

The Data Type of an Internal Table


Local table type/internal table
TYPES

Attributes

DATA

or

name TYPE table_kind


table_type
OF
OF

Table kind

line_type

Line type (columns)

WITH key_def
key_def

Key

[ INITIAL SIZE n ].

Initial size (optional)

Global table type


Attributes

global_type

Table kind
Input on screen used
to specify attributes

Line type (columns)


Key

SAP AG 2002

To define a table type (explicitly or implicitly), you must give the type (or data object) a name, as well as
specifying a table kind, line type, and key.
If you are defining a local table type, enter the kind after TYPE and the line type after OF. You must list
the key fields after WITH.
You create and edit global types in the ABAP Dictionary. If you are defining a global table type, specify
the same information on the maintenance screens.
For table types defined in a program, you can enter the number of lines that the runtime system should
reserve when it initializes the data object, after the INITIAL SIZE addition. This makes sense if you
know exactly how many lines you will want in your table when you create it. However, if your table
needs more lines at runtime, it will not be limited in size by this addition, since the runtime system frees
the necessary memory dynamically.
(Internal tables are dynamic data objects).

(C) SAP AG

BC401

3-10

Table Attribute: Line Type


Line type
Global structure type

Local structure type

TYPES
TYPES:
BEGIN OF line_type
line_type,
...
END OF line_type.

line_type

Local structure

DATA
DATA:
structure
structure TYPE ...

Table type
... name LIKE table_kind

... name TYPE


TYPE table_kind
OF
OF

OF

line_type
line_type

structure

WITH key_def

WITH key_def

[ INITIAL SIZE n ].

[ INITIAL SIZE n ].

SAP AG 2002

To specify the line type of an internal table, you can use all the local and global data types or data
objects.
Internal tables are most frequently used to display contents of the database tables. Normally, non-nested
structured data types are used for this.
If you use a line type, you must use a statement in the form: TYPE table_kind OF line_type,
where table_kind is the kind of table (to be discussed later) and line_type is the name of the
structure type you are using.
If you use structure (data object), you must use a statement in the form: LIKE table_kind OF
line_type, where structure is the name of the structure object you are using.

(C) SAP AG

BC401

3-11

Table Attribute: Table Kind and Key

TYPES:
itabtype TYPE table_kind
OF

line_type

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

table_kind
STANDARD TABLE
SORTED
HASHED

TABLE
TABLE

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

SAP AG 2002

There are three parameters that you use to specify a table kind for your internal table: STANDARD
TABLE, SORTED TABLE and HASHED TABLE
You specify the table key with the WITH key_def addition. key_def includes the names of all the
key fields in order and specifies whether the key is to be UNIQUE or NON-UNIQUE.
The combination of the table kind and the key definition is very significant, because of the special
support that certain table kinds receive with specific types of read access. You can use any of the
following combinations:
For STANDARD tables:
Either create a user-defined key by naming the key fields after NON-UNIQUE KEY, or specify the
standard key using the WITH DEFAULT KEY addition. The standard key consists of all the fields
with character-type data types (c, n, d, t, x, string, xstring).
For SORTED tables:
List the key fields after WITH UNIQUE KEY or NON-UNIQUE KEY as appropriate.
For HASHED tables:
List the key fields after WITH UNIQUE KEY.
Alternatively, use the pseudo-component table_line, if you are specifying a table without a
structured line type, or if the entire table line is being used as the key. This will be discussed in more
detail later in the unit.

(C) SAP AG

BC401

3-12

Example: Standard Table with Local Type


Line type:

TYPES:
BEGIN OF s_distance_ty
s_distance_ty,
carrid
TYPE s_carr_id,
connid
TYPE s_conn_id,
distance TYPE s_distance,
distid
TYPE s_distid,
END OF s_distance_ty.
Table type:

TYPES:
tt_distance_ty TYPE STANDARD TABLE
OF s_distance_ty
WITH NON-UNIQUE
KEY distance distid.
Internal table

DATA:
tt_distance_ty
tt_distance
tt_distance TYPE tt_distance_ty.

Internal table
of the table kind
STANDARD TABLE

SAP AG 2002

The above example shows the definition of an internal table (tt_distance) using a local table type
(tt_distance_ty), which itself uses a local line type (s_distance_ty).
The internal table defined here is a STANDARD table with the line type s_distance_ty. It contains
the columns carrid, connid, distance and distid.
The distance and distid fields are key fields. The key is not unique.

(C) SAP AG

BC401

3-13

Example: Sorted and Hashed Table


Sequence
Sorted table

carrid

DATA:
distance_ranc
TYPE SORTED TABLE
s_distance_ty
OF s_distance_ty
WITH NON-UNIQUE KEY
distid distance.

connid

distance distid
2

1
2
3
4

Sequence

LH
LH
AA
QM

0402
0400
0017
0005

6.162
6.162
2.572
10.000

KM
KM
MI
MI

Sequence

Hashed table:
carrid

DATA:
distance_buffer
distance_buffer
TYPE HASHED TABLE
s_distance_ty
OF s_distance_ty
WITH UNIQUE KEY
carrid connid.

LH
AA
QM
LH

connid

distance distid

0400
0017
0005
0402

6.162
2.572
10.000
6.162

KM
MI
MI
KM

SAP AG 2002

The above example shows the definition of a SORTED table and a HASHED table. Both tables have the
same line type as the STANDARD table on the previous slide.
Note that the contents of the table are in a different order. For SORTED tables, the sequence of the
entries in the internal table is determined by the sequence of fields in the key definition.

(C) SAP AG

BC401

3-14

The Standard Table Type

DATA:
t_name TYPE TABLE
OF line_type.

Interpreted by
the system as:

Definition by
standard table type

DATA:
t_name TYPE STANDARD
STANDARD TABLE
OF line_type
WITH DEFAULT KEY

Example:
DATA:
t_sflight TYPE TABLE OF sflight.

SAP AG 2002

A standard type exists for defining standard tables with bound types. (Table type STANDARD TABLE,
key WITH DEFAULT KEY). When you create such a table, you can omit the STANDARD and WITH
DEFAULT KEY additions, since the runtime system supplies them automatically.
Note however, that the standard table type exists for data objects only. If you are defining a table type
that you want to use to provide a type for data objects, you must specify all its attributes completely.
Incomplete table types are known as generic. You can only use them to assign types to table-type
interface parameters.

(C) SAP AG

BC401

3-15

Internal Tables with an Unstructured Line Type


Definition: DATA:

it_fields TYPE STANDARD TABLE OF dd03l-fieldname


WITH KEY table_line,
table_line
wa_field

TYPE dd03l-fieldname.

SELECT fieldname FROM dd03l "table of transp. tables

Fill:

INTO TABLE it_fields


WHERE tabname = 'SPFLI'.
Key
access:

READ TABLE it_fields INTO wa_field


_line = 'CITYFROM'.
WITH KEY table_
table
table_line

SAP AG 2002

Use an unstructured line type if you need a single-column internal table. The slide shows an example of
a single-column table with the line type field_name.
To declare an explicit key, you must use the pseudo-component table_line.
You can use internal tables with an unstructured line type in the following ABAP statement (among
others):
SET PF-STATUS .. EXCLUDING itab. (deactivate function codes dynamically)
SPLIT .. INTO TABLE itab. (split a string dynamically)
You can use a key access, for example, to ascertain whether a specific entry exists.

(C) SAP AG

BC401

3-16

Using Internal Tables (3)

Introduction
Introduction and
and advantages
advantages of
of internal
internal tables
tables
Definition
Definition
Operations
Operations
Special
Special situations
situations
Notes
Notes on
on performance
performance

SAP AG 2002

(C) SAP AG

BC401

3-17

Overview: Types of Operation

Internal table
as a data object

Operations on one or
more lines

Editing lines
in a loop

or
( MOVE )

Insert

( INSERT )

( CLEAR )
Keep memory available

Read

( READ

Copy
Initialize

( FREE )
Release memory

Initialize

Compare using operators

( DELETE )

Insert summated

LOOP ...
* command block
ENDLOOP.

( COLLECT )

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

sequentially
)

Change ( MODIFY )
Delete

Edit lines

( SORT )

Array Fetch ( SELECT ...


INTO TABLE )
SAP AG 2002

You can perform three different types of operations on internal tables:


Operations on the whole data object:
Elementary operations available include MOVE (copy the content line by line), CLEAR (delete the
content, but keep the memory allocated), and FREE (delete the content and release the memory). You
can also use all the numerical comparison operators with internal tables in logical expressions. With
these operators, the number of lines is compared first and then, if necessary, the line contents. (This is
recursive for deep types). For more information, refer to the documentation on internal tables.
You can use the SORT statement to sort the content of STANDARD and HASHED tables. This statement
allows you to sort the table by one or columns, specifying ascending or descending for each column. For
more details, refer to the keyword documentation for the SORT statement.
You can use the SELECT ... INTO TABLE statement to copy the contents of database tables
directly into internal tables.
Operations on lines:
You can use the INSERT, READ, MODIFY, DELETE, and COLLECT statements to perform operations
on one or more lines in the internal table. The syntax of the first four of these statements is dealt with in
the slides that follow. For the syntax of the COLLECT statement, refer to the online documentation.
Loop processing:
You can use the LOOP AT ... ENDLOOP statement to process the lines of the internal table
sequentially. The exact syntax for this is dealt with in the slides that follow.

(C) SAP AG

BC401

3-18

Limiting the Scope of Line Operations: Target


Records and Access Type
Specify set of target records
Table key
Line index (for index tables)

n
<condition>

Condition applied to any number of columns

[ n1 ... n2 ]

Index interval (for index tables)

Specify access type / data transfer type


Table
Work area

Copying process

Field symbol

Direct access by
dereferenced pointer

Insert
using table

SAP AG 2002

Almost all line operations and loop processing statements offer you several options for specifying the
target set of records to be processed. You can specify these target records by declaring a key or index, by
formulating a condition that applies to some of the columns, or by specifying an index interval. Your use
of these options is limited only by the table kind you have chosen.
Example: You cannot specify a line in a hashed table using an index.
When accessing table rows, you have two possibilities for a number of line operations and for loop
processing: You can either copy the data into a structure with the same type as the line type of the
internal table, or you can set a pointer to a table line and access the data in that line directly.
In particular, when you insert table lines, you can pass the data to be inserted using another internal
table.
Note that all statements either set a return value or trigger a runtime error. If a return code has been set, it
is stored in the sy-subrc field after the statement has been executed. Runtime errors are only triggered
if the data passed at runtime are crucial in determining whether or not the operation can be performed.
Example:
You try to insert a new line into a SORTED table using an index. If you insert the new line in exactly the
right place in a sorted table, the system performs the operation. If not, the system returns a runtime error.

(C) SAP AG

BC401

3-19

Preview: Field SymboIs (1)


Data objects in the ABAP program
Defining a field symbol:

DATA: var_a TYPE i VALUE 4.


FIELD-SYMBOLS:
FIELDFIELD-SYMBOLS <fs> TYPE i.

Assigning a data object to a


field symbol:

<fs>
var_a

<fs>

ASSIGN var_a TO <fs>.

var_a
Assigning a value to a data object
using a field symbol:

<fs>

<fs> = 77.
var_a

77

Time
SAP AG 2002

You can create a pointer to a data object in ABAP using a field symbol.
First, declare a data object using the FIELD-SYMBOLS statement. This data object can contain a pointer
to another data object at runtime. Where possible, you should give the field symbol the same type as the
data object (TYPE i, in this example).
Note that the angle brackets (<>) are part of the name of the field symbol: In this example, the name is
<fs>.
To point a field symbol at a data object, you must assign it to the object data_object using the
ASSIGN data_object TO <fs> statement.
You can use the field symbol to access the content of the data object to which it points - either to read or
to change this content.
You can "redirect" a field symbol to a different data object at runtime using the ASSIGN statement.

(C) SAP AG

BC401

3-20

Preview: Field SymboIs (2)


Defining the field symbol:

Data objects in the ABAP program

DATA: it_sflight TYPE TABLE OF


sflight.
FIELD-SYMBOLS: <fs> TYPE sflight.

<fs>
it_sflight

Assigning a line to the field symbol:


<fs>

* ... to be continued ...


it_sflight

Accessing the line content using the field symbol:

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

<fs>
it_sflight

SAP AG 2002

In the above example, a field symbol is assigned the line type of an internal table. This makes it possible
to assign a table line to this field symbol. The syntax required for this is discussed later in this unit.
After a field symbol has been assigned a line, it is also possible to access the individual column values of
the assigned line.
As well as being able to read the data contents, you can also change the contents of the individual
components.

(C) SAP AG

BC401

3-21

Insert
Key from "wa"
specifies the line
itab

* fill workarea "wa"

wa

INSERT
INSERT wa INTO TABLE itab.
itab
wa

* fill workarea "wa"


n

INSERT
INSERT wa INTO itab INDEX n.
INSERT
INSERT LINES
LINES OF
OF itab1

itab1
[n1]
[n2]

itab2

[ FROM n1 TO n2 ]
target.
n

Only if itab1 is
an index table

target
INTO TABLE itab2.
n

INTO itab2 [ INDEX n ].

SAP AG 2002

To insert lines into a table, use the INSERT statement:


Using INSERT wa INTO TABLE itab, you insert the line whose data are stored in wa into the
internal table. The record is inserted with reference to the table key. In STANDARD tables, the new line is
appended to the end of the table.
Using INSERT wa INTO itab INDEX n, you insert the data from wa into the internal table at the
line with the index n. If n is an index value within the internal table, the lines with the index value
greater than or equal to n are pushed downwards. If n-1 is greater than the number of lines in the
internal table, the line is not inserted.
Always add new lines to a SORTED table using the key. If you try to insert a line into a SORTED table
using the index, you will not succeed unless the line has exactly the same index number as it would have
when correctly sorted. Otherwise, a runtime error occurs.
Use INSERT LINES OF itab1 INTO TABLE itab2 to insert the lines of the internal table
itab1 into the internal table itab2. Also, if itab1 is an index table, you can limit the number of
lines to be inserted using an index interval (FROM n1 TO n2).
If your target table is an index table, you can use INSERT LINES OF itab1 INTO itab2 to
insert the lines of the internal table itab1 into the internal table itab2. You can then specify the line
index from which the lines are to be inserted using INDEX n. Also, if itab1 is an index table, you can
limit the number of lines to be inserted using an index interval (FROM n1 TO n2).

(C) SAP AG

BC401

3-22

Reading a Single Record into a Work Area Using


the Line Number
itab
wa
n

Index

INTO wa [ options ].
READ TABLE itab INDEX
INDEX n INTO
[ options ]
COMPARING

Beliebige
Any field
Feldliste
list

comp_list

TRANSPORTING trans_list

comp_list
f1 ... fm
ALL FIELDS
trans_list
f1 ... fk
NO FIELDS

SAP AG 2002

You can read single table lines from index tables using the READ TABLE itab INDEX n INTO
wa statement. After INDEX, enter the index of the line you want to read. If the system was able to read
the line, it sets the return code to sy-subrc = 0 and stores the data from the line in wa. The total
number of lines is then in sy-tfill, the length of the lines in sy-tleng. If the system could not
read the line, the return code sy-subrc is unequal to 0. In this case, the content of wa is not changed.
Use the option TRANSPORTING addition to specify the columns for which you want to transport data:
If you do not want to read any data, but simply want to ascertain whether or not line n exists
(evaluating the return value sy-subrc), use the TRANSPORTING NO FIELDS addition.
If you want to read some of the columns in the line only, specify them after TRANSPORTING.
Separate each column name with a space.
You can use the optional addition COMPARING f1 ... fm to ascertain whether or not the line to be
read n has specific column contents: To do this, copy the value of all columns that point to the records
you want to read, into wa and list the columns after the COMPARING addition to the READ statement. If
the system was able to read the line and if all the columns listed contain the values stored in wa, it sets
the return code sy-subrc to zero. If the system was able to read the line, but if one or more of the
columns does not contain the value stored for it in wa, it sets the return code sy-subrc to two. If it
could not read the line, it sets the return code to greater than two.
The COMPARING ALL FIELDS addition provides a shorter syntax for comparing all the columns.

(C) SAP AG

BC401

3-23

Reading a Single Record into a Work Area Using


the Field Contents
Key
wa1

itab

Table key from wa1

wa
Explicit table key
Any content from field list

READ TABLE itab search_clause INTO wa [ options ].


As in index
access

search_clause
Table key

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

Any field
contents

WITH KEY col1 = f1 ... colm = fm


[BINARY SEARCH]

SAP AG 2002

You can read individual lines from any kind of table using READ TABLE itab key INTO wa. Use
either a table key, or a comparison for some of the columns, as the search criterion key.
If you want to use a table key, you have two options:
Copy the key field values of the entry you want to read into the work area wa1 and use READ TABLE
itab FROM wa1 INTO wa. Provided sy-subrc = 0, the system stores the result of the READ
statement in the work area wa. Note that the values in wa1 that you have not explicitly filled contain
appropriately-typed initial values. Thus, the READ TABLE itab FROM wa1 statement searches
for a line that has initial values in the key fields that were not declared explicitly.
Note:
You can also use a single work area wa for both declaring the key fields and receiving the result:
READ TABLE itab FROM wa INTO wa.
Evaluate the key fields explicitly using the call READ TABLE itab WITH TABLE KEY k1 =
f1 ... kn = fn statement. In this case, you must fill all the key fields.
You can specify a formulated search condition to be applied to any columns using READ TABLE itab
WITH KEY ....
However, you can only use dynamically formulated read accesses using the key and the READ TABLE
itab FROM wa statement.

(C) SAP AG

BC401

3-24

Reading a Single Record Using a Field Symbol

itab

Key

<fs>
or

Index

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

READ TABLE itab

INDEX n

Index

ASSIGNING <<fs>.
>
key

Key

-field_1 ...
<fs>
WRITE: / <fs><FS>-field_1,
Same as when reading into a work area

SAP AG 2002

You can use either a work area or a field symbol to access the individual lines in a table you want to
read.
To use a field symbol, first define it using FIELD-SYMBOLS <fs>. Give it the same type as the line
type of the internal table that you want to read.
Example: FIELD-SYMBOLS <fs> LIKE LINE OF itab.
Set the pointer to the correct line using the ASSIGNING <fs> addition instead of INTO. You can use
any search criterion you want.
You can access the components of the structure directly using the component names in the line type:
You can directly address elementary components in the line type using <fs>-field_1.
If the line type contains structured components (a structure or internal table),
<fs>-component_name points to the entire structured component. To access the sub-components
of this structured component, you need another field symbol.
Note:
If you are searching for a specific string in an internal table, you can also use the SEARCH statement. For
more details, refer to the keyword documentation for the SEARCH statement.

(C) SAP AG

BC401

3-25

Changing the Table Using a Work Area


Key from "wa"
specifies the line

* fill workarea "wa"

itab

MODIFY TABLE itab FROM


FROM wa

wa

[ TRANSPORTING
TRANSPORTING f1 ... fn ].

itab
wa

* fill workarea "wa"


n

MODIFY itab FROM wa INDEX


INDEX n
[ TRANSPORTING f1 ... fn ].

itab

MODIFY itab FROM wa

WHERE
log_expr.

wa

TRANSPORTING f1 f2 ...
WHERE log_expr.

SAP AG 2002

The MODIFY TABLE itab FROM wa statement allows you to change the content of one line of the
internal table itab. The runtime system specifies the line to be changed using the key values from the
work area wa and changes the non-key fields using the other fields. If your table has a non-unique key,
the system changes the first entry only (using a linear search algorithm in STANDARD tables, and a
binary search algorithm in SORTED tables). If you want to change only some of the fields (that is,
columns) in a line, you must specify these after TRANSPORTING.
You can change the nth line in an index table using MODIFY itab FROM wa INDEX n. Note that
all the fields of the structure wa will be copied. Since changes to key fields in SORTED and HASHED
tables can cause non-catchable runtime errors, you must use the TRANSPORTING addition in this case.
If you want to make the same changes to several lines in a table, use the MODIFY itab FROM wa
TRANSPORTING f1 f2 ... WHERE log_expr statement. Specify all the columns to be changed
after TRANSPORTING. You must place the new values for these columns in the work area wa. Specify a
condition for the line using the WHERE clause.

(C) SAP AG

BC401

3-26

Changing a Single Record Using a Field Symbol

Key

itab
<fs>
1

or
2

<fs>-field_1 = ...

Index

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


INDEX n
1

READ TABLE itab

key
2

<
fs>-field_1 =
<FS>-field_1

Index

ASSIGNING <fs>.
Key

...

Cannot be key field in


sorted or hashed tables

Same as when reading


into a work area

SAP AG 2002

Instead of changing an individual line in a table using MODIFY, you can also change it using field
symbols. First use READ TABLE ... ASSIGNING <fs> to assign a field symbol to the line to be
changed. Then change the components directly using the field symbol components <fs>-field_1 =
....
When you assign the field symbol using READ TABLE ... ASSIGNING you can specify the line to
be read using a key (WITH TABLE KEY), index (for index tables), or a condition (WITH KEY).
Note that you cannot change key fields in SORTED or HASHED tables. - trying to do so causes a runtime
error.

(C) SAP AG

BC401

3-27

Delete
* fill workarea "wa"
Table key

itab

DELETE TABLE itab key.

wa

key
Explicit

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

itab
n

WHERE
log_expr.

DELETE itab INDEX n.

Delete using a condition

DELETE itab WHERE log_expr.

SAP AG 2002

Use the READ TABLE itab INDEX n INTO wa statement to delete single table lines from index
tables. Specify the line you want to delete using the table key. There are two ways of doing this:
Copy the key field values of the entry you want to delete into the work area wa and use DELETE
TABLE itab FROM wa.
Fill the key fields directly in the DELETE statement using the WITH TABLE KEY k1 = f1 ...
kn = fn addition.
You can delete the nth line from the index table itab using DELETE itab INDEX n
If you want to delete several lines from an internal table, use the DELETE itab WHERE log_expr
statement. The condition that specifies the lines you want to delete is declared in log_expr, in the
WHERE clause (where log_expr is any logical expression applied to the columns).

(C) SAP AG

BC401

3-28

Loop Processing
result
itab

wa

result
INTO wa
ASSIGNING <fs>

<fs>

LOOP AT itab result


[TRANSPORTING NO FIELDS]
{ [ FROM n1 ] [ TO n2 ] |

Index tables only

[ WHERE log_expr ] } .
...
ENDLOOP.
ENDLOOP

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

SAP AG 2002

Use the LOOP AT itab result ... ENDLOOP statement to perform loop processing on the lines
of the internal table itab. The system then executes the statement block between LOOP AT itab
... and ENDLOOP for each loop pass. result stands for:
INTO wa:
The system copies the table line it has processed in each loop pass into the work area wa
ASSIGNING <fs>:
The relevant line is assigned to the field symbol <fs>.
With both variants you can use the TRANSPORTING NO FIELDS addition. No data is copied. Use this
addition if, for example, you simply want to determine the number or indexes of the lines processed by
the loop.
Specify the number of lines that the loop is to process using a WHERE clause (condition for any
columns).
In an index table, limit the number of lines processed in the loop by declaring an index interval.
While the loop is being processed, the system field sy-tabix contains the index of the table row of the
current loop pass. The total number of lines is in sy-tfill, the length of the lines in sy-tleng.
Note that in index tables, you can perform all the line operations (which you previously performed on
the line specified in the INDEX n addition) without this addition in the loop. The operation is then
performed on the current line.

(C) SAP AG

BC401

3-29

Overview of Operations
Standard table

Sorted table

Hashed table

SORT
Index access

INSERT

Sort
sequence
could be
violated

READ TABLE
MODIFY
DELETE
LOOP AT
Key access

No index
accesses to
hashed
tables

Append to end of
table

INSERT
READ TABLE
MODIFY
DELETE
LOOP AT
SAP AG 2002

Index accesses (such as APPEND, INSERT ... INDEX, LOOP AT ... FROM ... TO) are
possible for standard and sorted tables. However, caution is advised when using INSERT or APPEND on
sorted tables; this would violate the sort sequence and cause a runtime error.
You can use the SORT statement to sort standard and hashed tables. Sorted tables are sorted by the
runtime system.
You can use key accesses with any table type, but their effect differs. A key access with INSERT has the
same effect on standard tables as an APPEND, that is the relevant line is appended to the end of the table.
In a sorted table however, the record is inserted in accordance with the sort sequence. In the case of a
hashed table, the line is appended, but the system also changes the hash index internally.

(C) SAP AG

BC401

3-30

Using Internal Tables (4)

Introduction
Introduction and
and advantages
advantages of
of internal
internal tables
tables
Definition
Definition
Operations
Operations
Special
Special situations
situations
Notes
Notes on
on performance
performance

SAP AG 2002

(C) SAP AG

BC401

3-31

Internal Tables with a Header Line


DATA: Syntax variant 1
Work area =
header

itab TYPE TABLE OF scarr


WITH DEFAULT KEY
Data object itab

WITH HEADER LINE


LINE.

itab

DATA: Syntax variant 2 (obsolete)


itab TYPE scarr OCCURS
OCCURS 0

itab

WITH HEADER LINE


LINE.
Body

DATA: Syntax variant 3 (obsolete)


BEGIN OF itab OCCURS 0,
carrid TYPE s_carr_id,
...
url
TYPE s_carrurl,
END OF itab.
SAP AG 2002

As well as the internal tables we have discussed, you can define internal tables with a header. These
consist of a pair of components - the internal table itself (the body) and the work area (header), with the
same line type. The header and the body have the same name, which sometimes simplifies the syntax for
table accesses.
There are several possible syntax variants used to define internal tables with header lines, some of which
are shown in the slide.
Internal tables with header lines are the oldest form of internal table.
However, note that
Many statements have a different effect on internal tables with a header than they would on normal
internal tables. You can then address the body separately using "[]" .
Example:
The CLEAR itab statement initializes only the header line, whereas in an internal with no header, it
initializes the content of the entire table.
You can delete the body of an internal table with a header using CLEAR itab[] or REFRESH
itab.
You cannot use internal tables with a header line in an object-oriented environment - that is, within
classes or interfaces.

(C) SAP AG

BC401

3-32

Selection Options and Selection Tables


DATA:
carrid TYPE s_carr_id.
SELECT
-OPTIONS
SELECT-OPTIONS:
so_carr FOR carrid.
Link to selection screen
so_carr
Data object so_carr
Identically-typed data object without
header or link to selection screen

DATA:
so_carr LIKE
RANGE
RANGE OF
OF carrid.
sign(1)
TYPE c
option(2)
TYPE c

low LIKE
carrid
high LIKE
carrid

SAP AG 2002

Use the SELECT-OPTION statement to create an internal table with a header, for which the runtime
system automatically creates an input dialog for value sets for a selection screen. The system
automatically inserts the appropriate entries in the internal table, from the user input. For more details,
refer to the keyword documentation for the SELECT-OPTIONS statement.
As of SAP R/3 Basis Release 4.6A onwards, you can use the RANGE OF addition to the TYPES and
DATA statements to define a corresponding (internal) table without a header line.

(C) SAP AG

BC401

3-33

Using Internal Tables (5)

Introduction
Introduction and
and advantages
advantages of
of internal
internal tables
tables
Definition
Definition
Operations
Operations
Special
Special situations
situations
Notes
Notes on
on performance
performance

SAP AG 2002

(C) SAP AG

BC401

3-34

Single Record Access: Completely and Partially


Qualified Key
READ TABLE itab INTO wa
WITH
WITH TABLE
TABLE KEY
KEY key.

Table kind

STANDARD

SORTED

HASHED

Table scan

Binary
search

Hash
algorithm

key
Must be completely
qualified

READ TABLE itab INTO wa


WITH
WITH KEY
KEY key.

Table kind

STANDARD

SORTED

HASHED

key
Complete/part key
leftleft-aligned without gaps
By qualified key

Binary
search
Table scan

Table
scan

Table
scan

Any component
condition
SAP AG 2002

Whenever you want to read individual table lines by declaring a complete key, use the READ TABLE
... WITH TABLE KEY statement (fastest single record access by key). The runtime system supports
this syntax variant especially for SORTED and HASHED tables. If the table is a STANDARD table, the
runtime system performs a table scan.
The same applies if you have copied the values from all key fields of the entry to be read into the work
area wa and are then use READ TABLE itab FROM wa.
The runtime system carries out the syntax variant READ TABLE ... WITH KEY (read an entry after
applying any condition) using a table scan.
The only exception to this rule applies to SORTED tables, if you fill the first n key fields with "=" (no
gaps), where n <= number of key fields.
With standard tables however, you can also sort correspondingly using SORT and then use the BINARY
SEARCH addition.
Summary:
Whenever possible, use READ TABLE ... WITH TABLE KEY or the variant with a
correspondingly-filled work area.
If you need to use READ TABLE ... WITH KEY, make your internal table a SORTED table.

(C) SAP AG

BC401

3-35

Loop Processing and Table Kinds


LOOP AT itab INTO wa
log_expr
WHERE log_expr.
log_expr
...
ENDLOOP.

Table kind

STANDARD

SORTED

HASHED

log_expr
First n key fields filled
with "=" without gaps

Table scan

Any logical expression


for columns

Binary search for


starting point,
then loop only
through group
level

Table scan

Table scan

SAP AG 2002

The runtime system generally processes loops with a WHERE clause by performing a table scan - that is,
determining whether the condition in the WHERE clause is true for each line in the table.
SORTED tables are the only exception to this rule. For these, the runtime system optimizes the runtime
under the following condition:
In the WHERE clause, the first n key fields are filled with a "=" (no gaps). (n is less than or equal to the
number of all key fields). As a result, the loop is only performed on the lines that match the condition in
the WHERE clause. Since the table is sorted, the first line can be specified to optimize performance at
runtime (using a binary search).

(C) SAP AG

BC401

3-36

Partial Sequential Loop Through Standard Tables


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

CONNID CITYFROM

AA
LH
LH
UA
UA

64
400
2407
941
3516

SAN FRANCISCO
FRANKFURT
BERLIN
FRANKFURT
NEW YORK

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

Ascertain starting point:


READ TABLE ...
WITH KEY cityfrom = 'FRANKFURT'
TRANSPORTING NO FIELDS
BINARY SEARCH.
startline = sy-tabix.
Ascertain end point:
READ TABLE ... INTO ...
WITH KEY cityfrom = 'NEW YORK'
TRANSPORTING NO FIELDS
BINARY SEARCH.
endline = sy-tabix.

SORT ... BY cityfrom


STABLE.

CARRID
LH
LH
UA
UA
AA

CONNID CITYFROM
2407
400
941
3516
64

BERLIN
FRANKFURT
FRANKFURT
NEW YORK
SAN FRANCISCO

Index-controlled loop:
LOOP AT ... INTO ...
FROM startline to endline.
...
ENDLOOP.

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

SAP AG 2002

To recap:
If you program a loop through a standard table to match a specific field criterion, the runtime system
always executes a table scan.
You can use the algorithm described here to program the runtime behavior of sorted tables:
First you must sort the standard table by the desired criterion, so that you can subsequently ascertain the
starting and end points in a binary search.
(The line indexes are available in the system field sy-tabix.)
Finally, you can use these values to program an index-controlled loop.
Since the SORT and READ TABLE statements require additional runtime, this procedure is only useful
if the loop can be repeated several times according to the field criterion.
Summary:Use SORTED tables if you want to implement partial sequential loops on internal tables
(where the first n key fields are filled with "=") or use the above algorithm.

(C) SAP AG

BC401

3-37

Access Using Field Symbols


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

READ TABLE itab


INTO wa1
WITH TABLE KEY ... .

READ TABLE <fs1>-col3


ASSIGNING <fs2>
WITH TABLE KEY ... .

READ TABLE wa1-col3


INTO wa2
WITH TABLE KEY ... .
wa2

<fs2>

Copy

wa1
<fs1>

Copy

col1

col2

col3

col4

itab

col1

col2

col3

col4

SAP AG 2002

Instead of READ TABLE ... INTO, you can use the READ TABLE ... ASSIGNING variant.
This offers better performance at runtime for pure read accesses with a line width greater than or equal to
1000 bytes. If you then change the read line using MODIFY, READ ... ASSIGNING already
improves runtime with a line width of 100 bytes.
The same applies to LOOP ... INTO in comparison with LOOP ... ASSIGNING. The LOOP
... ASSIGNING variant offers better performance at runtime for any loop of five loop passes or more.
Both field symbol variants are much faster than work area variants, in particular when you use nested
internal tables. This is because, if you use work areas instead, the whole inner internal table is copied
(unless you prevent this by using a TRANSPORTING addition).
Always assign a type to field symbols, if you know their static type (again, for performance reasons).
Note:
If you use READ TABLE ... ASSIGNING the field symbol points to the originally assigned table
line, even after the internal table has been sorted.
Note that when using field symbols, you cannot change key fields in SORTED or HASHED tables. Trying
to do so causes a runtime error.
The following restrictions apply to LOOP ... ASSIGNING <fs>:
You cannot use the SUM statement in control level processing.
You cannot reassign field symbols within the loop. The statements ASSIGN do TO <fs> and
UNASSIGN <fs> will cause runtime errors.

(C) SAP AG

BC401

3-38

Using Internal Tables: Unit Summary

You are now able to:


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

SAP AG 2002

(C) SAP AG

BC401

3-39

Using Internal Tables Exercise 1


Unit: Using Internal Tables
Topic:

Single-Column Tables of the Type string

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


Define single-column tables of the data type string
Split character strings with internal tables
Process internal tables in loops
Now, the character string will contain more than one data
record.
Extend your program in such a way that the various data records
in the rows of an internal table are split. Then separate the
individual data records into single components and output them
as before.
Program:

ZBC401_##_SPLIT_ITAB

Template:

SAPBC401_DTOS_SPLIT_STRING

Model solution:

SAPBC401_TABS_SPLIT_ITAB

## is your two-digit group number


1-1

Copy your solution for the exercise in the chapter Data Types and Data Objects in
Detail, ZBC401_##_SPLIT_STRING, or the corresponding model solution
SAPBC401_DTOS_SPLIT_STRING and give it the new name
ZBC401_##_SPLIT_ITAB.

1-2

Ensure that the function module BC401_GET_SEP_STRING creates a character


string consisting of 30 data records. For this you must assign a suitably typed constant
(suggested name c_number) to the parameter im_number.

1-3

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

1-4

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

(C) SAP AG

BC401

3-40

1-5

(C) SAP AG

Ensure that your internal table containing the partial character strings is used for the
subsequent splitting of the individual data record and output of the components in a
loop.

BC401

3-41

Exercise 2 - Optional
Unit: Using Internal Tables
Topic:

Table Types

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


Select the appropriate types of internal table
Process data using internal tables
Now the character string will contain duplicate data records.
Extend your program in such a way that the various data records
are kept sorted in internal tables. Those data records that appear
twice are to be sorted into a separate internal table.
ZBC401_##_TABKIND

Program:
Template:

SAPBC401_TABS_SPLIT_ITAB

Model solution:

SAPBC401_TABS_TABKIND

## is your two-digit group number


2-1

Copy your solution to the last exercise ZBC401_##_SPLIT_ITAB or the


corresponding model solution SAPBC401_TABS_SPLIT_ITAB and give it the new
name ZBC401_##_TABKIND.

2-2

Ensure that the function module BC401_GET_SEP_STRING creates a character


string containing duplicate data records. For this, assign the parameter im_unique
the value space.
Test your program.

2-3

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

(C) SAP AG

BC401

3-42

2-4

(C) SAP AG

Display the contents of both internal tables with the flight data.

BC401

3-43

Exercise 3 - Optional
Unit: Using Internal Tables
Topic:

Processing Data Using Internal Tables

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


Select the appropriate types of internal table
Process data using internal tables
Extend your program so that it displays the flight data sorted by
the flight date. The data is to be displayed in different colors,
according to a key date selected by the user.
If desired, the data is to be displayed using the SAP Grid Control.
ZBC401_##_PROCESS_DATA

Program:
Template:

SAPBC401_TABS_TABKIND

Model solution:

SAPBC401_TABS_PROCESS_DATA

## is your two-digit group number


3-1

Copy your solution to the last exercise ZBC401_##_TABKIND or the corresponding


model solution SAPBC401_TABS_TABKIND and give it the new name
ZBC401_##_PROCESS_DATA.

3-2

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

3-3

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

3-4

Ensure that the individual flight dates of the internal table it_flights are displayed
in color according to the following criteria: Use the FORMAT COLOR col_...
statement and load the type group col. (You can reverse any color set using the
FORMAT RESET statement.)
Display flights that occurred in the past with the background color
col_negative.

(C) SAP AG

BC401

3-44

Display flights that occurred between todays data and the key date with the
background color col_total.
Display flights that occurred in the past with the background color
col_positive.
3-5

Define a selection screen check box for displaying the data with the standard tool SAP
Grid Control (suggested name pa_alv, addition AS CHECKBOX).
Ensure that the data is only displayed in the usual ABAP list if the user does not check
the SAP Grid Control box.
Otherwise, proceed as follows:
3-5-1 Call the function module BC401_ALV_LIST_OUTPUT. Terminate the
program if the function module raises an exception. (In this case, there is a
problem with the system configuration.)
Detailed information on using the SAP Grid Control is not
part of this course. For this reason, you use a function
module that encapsulates all the necessary technical details,
which you can treat as a black box.
For more information on the SAP Grid Control, see:
The online documentation
The example programs under
Environment Examples

Control Examples

The training course BC412: ABAP Dialog Programming


with EnjoySAP Controls
3-5-2 Find out about the types of the two internal tables that can/must be transferred
to the function module as a parameter.
Define two corresponding internal tables and an appropriate work area in your
program (suggested names it_col_flights, it_col_doubles, and
wa_col_flight).
3-5-3 The line type of the internal table that you must/can transfer contains a column
COLOR, in which you can set the color values col_negative, col_total,
col_positive, and col_background for every single line.
Copy the contents of the tables it_flights and it_doubles to the
internal tables it_col_flights and it_col_doubles respectively. Use
two loops to do this, and to fill the COLOR column.
it_flights:

(C) SAP AG

Logical condition

Color value

fldate < sy-datum

col_negative

fldate BETWEEN sy-

col_total
BC401

3-45

datum AND p_date


fldate > p_date

col_positive

Always use col_background to display it_doubles.

(C) SAP AG

BC401

3-46

Using Internal Tables Solution 1


Unit: Using Internal Tables
Topic:

REPORT

Single-Column Tables of the Type string

sapbc401_tabs_split_itab.

TYPES:
BEGIN OF st_flight_c,
mandt(3)

TYPE c,

carrid(3)

TYPE c,

connid(4)

TYPE n,

fldate(8)

TYPE n,

price(20)

TYPE c,

currency(5)

TYPE c,

planetype(10)

TYPE c,

seatsmax(10)

TYPE n,

seatsocc(10)

TYPE n,

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

TYPE c,

connid(4)

TYPE n,

fldate

TYPE d,

price(9)

TYPE p DECIMALS 2,

currency(5)

TYPE c,

planetype(10) TYPE c,
seatsmax

TYPE i,

seatsocc

TYPE i,

END OF st_flight.
CONSTANTS c_number TYPE i VALUE 30.
(C) SAP AG

BC401

3-47

DATA:
datastring

TYPE string,

set_string

TYPE string,

wa_flight_c TYPE st_flight_c,


wa_flight

TYPE st_flight.

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

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

= c_number

IM_TABLE_NAME

= 'SFLIGHT'

IM_SEPARATOR

= '#'

IM_UNIQUE

= 'X'

IMPORTING
ex_string

= datastring

EXCEPTIONS
no_data

= 1

OTHERS

= 2.

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

SHIFT datastring BY 2 PLACES IN CHARACTER MODE.


FIND '##' IN datastring.
IF sy-subrc <> 0.
MESSAGE a702(bc401).
ENDIF.

(C) SAP AG

BC401

3-48

SPLIT datastring AT '##' INTO TABLE it_sets.

LOOP AT it_sets INTO set_string.


SPLIT set_string AT '#' INTO
wa_flight_c-mandt
wa_flight_c-carrid
wa_flight_c-connid
wa_flight_c-fldate
wa_flight_c-price
wa_flight_c-currency
wa_flight_c-planetype
wa_flight_c-seatsmax
wa_flight_c-seatsocc
wa_flight_c-paymentsum.
MOVE-CORRESPONDING wa_flight_c TO wa_flight.
WRITE: /
wa_flight-carrid,
wa_flight-connid,
wa_flight-fldate DD/MM/YYYY,
wa_flight-price CURRENCY wa_flight-currency,
wa_flight-currency,
wa_flight-planetype,
wa_flight-seatsmax,
wa_flight-seatsocc.
ENDLOOP.

(C) SAP AG

BC401

3-49

Solution 2 - Optional
Unit: Using Internal Tables
Topic:

REPORT

Table Types

sapbc401_tabs_tabkind.

TYPES:
BEGIN OF st_flight_c,
mandt(3)

TYPE c,

carrid(3)

TYPE c,

connid(4)

TYPE n,

fldate(8)

TYPE n,

price(20)

TYPE c,

currency(5)

TYPE c,

planetype(10)

TYPE c,

seatsmax(10)

TYPE n,

seatsocc(10)

TYPE n,

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

TYPE c,

connid(4)

TYPE n,

fldate

TYPE d,

price(9)

TYPE p DECIMALS 2,

currency(5)

TYPE c,

planetype(10) TYPE c,
seatsmax

TYPE i,

seatsocc

TYPE i,

END OF st_flight.
(C) SAP AG

BC401

3-50

CONSTANTS c_number TYPE i VALUE 30.


DATA:
datastring

TYPE string,

set_string

TYPE string,

wa_flight_c TYPE st_flight_c,


wa_flight

TYPE st_flight.

DATA:
it_sets TYPE STANDARD TABLE OF string
WITH NON-UNIQUE DEFAULT KEY
INITIAL SIZE c_number,
it_flights TYPE SORTED TABLE OF st_flight
WITH UNIQUE KEY carrid connid fldate
INITIAL SIZE c_number,
it_doubles TYPE SORTED TABLE OF st_flight
WITH NON-UNIQUE KEY carrid connid fldate
INITIAL SIZE c_number.

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

= c_number

IM_TABLE_NAME

= 'SFLIGHT'

IM_SEPARATOR

= '#'

IM_UNIQUE

= space

IMPORTING
ex_string

= datastring

EXCEPTIONS
no_data
(C) SAP AG

= 1
BC401

3-51

OTHERS

= 2.

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

SHIFT datastring BY 2 PLACES IN CHARACTER MODE.


FIND '##' IN datastring.
IF sy-subrc <> 0.
MESSAGE a702(bc401).
ENDIF.
SPLIT datastring AT '##' INTO TABLE it_sets.

LOOP AT it_sets INTO set_string.


SPLIT set_string AT '#' INTO
wa_flight_c-mandt
wa_flight_c-carrid
wa_flight_c-connid
wa_flight_c-fldate
wa_flight_c-price
wa_flight_c-currency
wa_flight_c-planetype
wa_flight_c-seatsmax
wa_flight_c-seatsocc
wa_flight_c-paymentsum.
MOVE-CORRESPONDING wa_flight_c TO wa_flight.
INSERT wa_flight INTO TABLE it_flights.
IF sy-subrc <> 0.
INSERT wa_flight INTO TABLE it_doubles.
ENDIF.
ENDLOOP.

(C) SAP AG

BC401

3-52

* output:
*********
LOOP AT it_flights INTO wa_flight.
WRITE: /
wa_flight-carrid,
wa_flight-connid,
wa_flight-fldate DD/MM/YYYY,
wa_flight-price CURRENCY wa_flight-currency,
wa_flight-currency,
wa_flight-planetype,
wa_flight-seatsmax,
wa_flight-seatsocc.
ENDLOOP.
SKIP.
WRITE: / 'duplicate data records:'(dob) COLOR COL_HEADING.
LOOP AT it_doubles INTO wa_flight.
WRITE: /
wa_flight-carrid,
wa_flight-connid,
wa_flight-fldate DD/MM/YYYY,
wa_flight-price CURRENCY wa_flight-currency,
wa_flight-currency,
wa_flight-planetype,
wa_flight-seatsmax,
wa_flight-seatsocc.
ENDLOOP.

(C) SAP AG

BC401

3-53

Solution 3 - Optional
Unit: Using Internal Tables
Topic:

Processing Data Using Internal Tables

REPORT sapbc401_tabs_process_data.
TYPE-POOLS col.
TYPES:
BEGIN OF st_flight_c,
mandt(3)

TYPE c,

carrid(3)

TYPE c,

connid(4)

TYPE n,

fldate(8)

TYPE n,

price(20)

TYPE c,

currency(5)

TYPE c,

planetype(10)

TYPE c,

seatsmax(10)

TYPE n,

seatsocc(10)

TYPE n,

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

TYPE c,

connid(4)

TYPE n,

fldate

TYPE d,

price(9)

TYPE p DECIMALS 2,

currency(5)

TYPE c,

planetype(10) TYPE c,
seatsmax
(C) SAP AG

TYPE i,
BC401

3-54

seatsocc

TYPE i,

END OF st_flight.
CONSTANTS c_number TYPE i VALUE 30.
DATA:
datastring

TYPE string,

set_string

TYPE string,

wa_flight_c TYPE st_flight_c,


wa_flight

TYPE st_flight.

DATA:
it_sets TYPE STANDARD TABLE OF string
WITH NON-UNIQUE DEFAULT KEY
INITIAL SIZE c_number,
it_flights TYPE SORTED TABLE OF st_flight
WITH UNIQUE KEY fldate carrid connid
INITIAL SIZE c_number,
it_doubles TYPE SORTED TABLE OF st_flight
WITH NON-UNIQUE KEY fldate carrid connid
INITIAL SIZE c_number,

it_col_flights TYPE bc401_t_flights_color,


it_col_doubles LIKE it_col_flights,
wa_col_flight LIKE LINE OF it_col_flights.
PARAMETERS:
pa_date LIKE sy-datum,
pa_alv

AS CHECKBOX DEFAULT 'X'.

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

(C) SAP AG

BC401

3-55

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

" date in the past

ENDIF.

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

= c_number

IM_TABLE_NAME

= 'SFLIGHT'

IM_SEPARATOR

= '#'

im_unique

= space

IMPORTING
ex_string

= datastring

EXCEPTIONS
no_data

= 1

OTHERS

= 2.

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

SHIFT datastring BY 2 PLACES IN CHARACTER MODE.


FIND '##' IN datastring.
IF sy-subrc <> 0.
MESSAGE a702(bc401).
ENDIF.
SPLIT datastring AT '##' INTO TABLE it_sets.

LOOP AT it_sets INTO set_string.


SPLIT set_string AT '#' INTO
wa_flight_c-mandt
wa_flight_c-carrid
(C) SAP AG

BC401

3-56

wa_flight_c-connid
wa_flight_c-fldate
wa_flight_c-price
wa_flight_c-currency
wa_flight_c-planetype
wa_flight_c-seatsmax
wa_flight_c-seatsocc
wa_flight_c-paymentsum.
MOVE-CORRESPONDING wa_flight_c TO wa_flight.
INSERT wa_flight INTO TABLE it_flights.
IF sy-subrc <> 0.
INSERT wa_flight INTO TABLE it_doubles.
ENDIF.
ENDLOOP.

* output:
*********
IF pa_alv = 'X'.
LOOP AT it_flights INTO wa_flight.
MOVE-CORRESPONDING wa_flight TO wa_col_flight.
IF wa_col_flight-fldate < sy-datum.
wa_col_flight-color = col_negative.
ELSEIF wa_col_flight-fldate < pa_date.
wa_col_flight-color = col_total.
ELSE.
wa_col_flight-color = col_positive.
ENDIF.
INSERT wa_col_flight INTO TABLE it_col_flights.
ENDLOOP.
LOOP AT it_doubles INTO wa_flight.
MOVE-CORRESPONDING wa_flight TO wa_col_flight.
wa_col_flight-color = col_background.
INSERT wa_col_flight INTO TABLE it_col_doubles.
(C) SAP AG

BC401

3-57

ENDLOOP.
CALL FUNCTION 'BC401_ALV_LIST_OUTPUT'
EXPORTING
it_list1

= it_col_flights

it_list2

= it_col_doubles

EXCEPTIONS
control_error = 1
OTHERS

= 2.

IF sy-subrc <> 0.
MESSAGE a702(bc401).
ENDIF.
ELSE.
LOOP AT it_flights INTO wa_flight.
IF wa_flight-fldate < sy-datum.
FORMAT COLOR = col_negative.
ELSEIF wa_flight-fldate < pa_date.
FORMAT COLOR = col_total.
ELSE.
FORMAT COLOR = col_positive.
ENDIF.
WRITE: /
wa_flight-carrid,
wa_flight-connid,
wa_flight-fldate DD/MM/YYYY,
wa_flight-price CURRENCY wa_flight-currency,
wa_flight-currency,
wa_flight-planetype,
wa_flight-seatsmax,
wa_flight-seatsocc.
ENDLOOP.
FORMAT RESET.
SKIP.
WRITE: / 'duplicate data records:'(dob) COLOR COL_HEADING.

(C) SAP AG

BC401

3-58

LOOP AT it_doubles INTO wa_flight.


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

(C) SAP AG

BC401

3-59

Calling Programs and Passing Data

Contents:
Techniques for calling programs
Memory model
Techniques for passing data
Use

SAP AG 2002

(C) SAP AG

BC401

4-1

Calling Programs and Passing Data: Unit Objectives

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


Describe the SAP R/3 memory model
Call executable programs
Call transactions
Use the various memory areas to pass data

SAP AG 2002

(C) SAP AG

BC401

4-2

Calling Programs and Passing Data:


Integration in Course Content

and
Data Types
ts in
Data Objec
Detail

al
Using Intern
Tables

Calling
d
Programs an
at
Passing D a

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

4-3

Calling Programs and Passing Data (1)

Calling
Calling programs
programs
Memory
Memory management
management
Passing
Passing data
data

SAP AG 2002

(C) SAP AG

BC401

4-4

Calling Programs

Time

Main
memory

Main
memory

1
New program

Insert program
Insertion

2
Restart

End insert

Program 1

Program 2

SAP AG 2002

There are two ways of starting an ABAP program from another ABAP program that is already running:
The called

program is inserted, that is the current program is interrupted to run the new one. The called
program is executed, and afterwards, processing returns to the program that called it.
The current program is terminated and the called program is started.
Complete ABAP programs within a single user session can only run sequentially. We refer to this
technique as sequential calling.
If you want to run functions in parallel, you must use function modules. For further information about this
technique, refer to the course BC415 (Communication Interfaces in ABAP) or the documentation for the
CALL FUNCTION ... STARTING NEW TASK ... statement.

(C) SAP AG

BC401

4-5

Calling an Executable Program


Program 1

...
SUBMIT prog_name_2.
...

Program 2
Restart

prog_name_2
PROGRAM ...
...

List

F3
...
SUBMIT prog_name_2
AND RETURN.
...

Insertion

prog_name_2
PROGRAM ...
...

List

F3

Insertion
...
SUBMIT prog_name_2
VIA SELECTION-SCREEN
AND RETURN.
...

Selection Screen

prog_name_2
Liste

PROGRAM ...
...

F3

F3

SAP AG 2002

To start an executable program, use the SUBMIT statement.


If you use the VIA SELECTION-SCREEN addition, the system displays the standard selection screen of
the program (if one has been defined).
If you use the AND RETURN addition, the system resumes processing with the first statement after the
SUBMIT statement once the called program has finished.
For further information, refer to the documentation for the SUBMIT statement.

(C) SAP AG

BC401

4-6

Calling a Transaction
Program 1

Program 2: Transaction

TCODE

Restart
...
LEAVE TO TRANSACTION 'T_CODE'
[AND SKIP FIRST SCREEN].
...

1. Screen

2. Screen
F15

Insertion
...
CALL TRANSACTION 'T_CODE'
[AND SKIP FIRST SCREEN].
...

1. Screen

2. Screen
F15

SAPM t_name
...
LEAVE PROGRAM.
...

SAPM t_name
...
LEAVE PROGRAM.
...

SAP AG 2002

With the LEAVE TO TRANSACTION 'T_CODE' statement you terminate the current program and start
the transaction with transaction code T_CODE. The statement is the equivalent to entering /n<T_CODE>
in the command field.
CALL TRANSACTION 'T_CODE' allows you to insert ABAP programs that have a transaction code.
To terminate an ABAP program, use the LEAVE PROGRAM statement. If the statement is used in a
program that you called using CALL TRANSACTION 'T_CODE' or SUBMIT prog_name AND
RETURN, the system resumes processing at the next statement after the call in the calling program.
Otherwise, the user returns to the application menu from which he or she started the program.
If you use the ... AND SKIP FIRST SCREEN addition, the system does not display the screen
contents of the first screen. However, it does process the flow logic.
If the transaction T_CODE you called with CALL TRANSACTION uses update techniques, you can use the
UPDATE... addition to specify the update technique (asynchronous (default), synchronous, or local) that
the program should use. For further information, refer to course BC414 (Programming Database
Updates) and the online documentation.

(C) SAP AG

BC401

4-7

Calling Programs and Passing Data (2)

Calling
Calling programs
programs
Memory
Memory management
management
Passing
Passing data
data

SAP AG 2002

(C) SAP AG

BC401

4-8

Logical Memory Model


User terminal session
External session (window) 1

External session (window) 2

ABAP memory 2

ABAP memory 1

Internal session 1.2

Program 1.2

Internal session 1.1

Program 1.1

Internal session 2.1

Program 2.1

SAP memory
SAP AG 2002

The way in which the main memory is organized from the program's point of view can be represented in
the above logical model. There is a distinction between internal and external sessions:
Generally,

an external session is connected to an R/3 window. You can create a new session by choosing
System New Session or by entering /o<T_CODE> in the command field. You can have up to six
external sessions open simultaneously in one terminal session.
External sessions are subdivided into internal sessions (placed on a stack). Each program that you run
occupies its own internal session. Each external session can contain up to nine internal sessions.
Data for a program is only visible within an internal session. The visibility of the data is generally
restricted to the relevant program.
The following slides illustrate how the stack inside an external session changes with various program calls.

(C) SAP AG

BC401

4-9

Inserting a Program (1)

External session (window) 1

External session (window) 2

ABAP memory 1

ABAP memory 2

User terminal session

Internal session 1.1

Program 1.1

Internal session 2.1

Program 2.1

SAP memory
SAP AG 2002

(C) SAP AG

BC401

4-10

Inserting a Program (2)


User terminal session
Insertion

External session (window) 1

External session (window) 2

ABAP memory 2

ABAP memory 1

Internal session 1.2

Program 1.2

Internal session 1.1

Program 1.1

Internal session 2.1

Program 2.1

SAP memory
SAP AG 2002

When you insert a program, the system creates a new internal session, which in turn creates a new program
context.
The new session is placed on the stack The program context of the calling program also remains intact.

(C) SAP AG

BC401

4-11

Terminating the Inserted Program

External session (window) 1

External session (window) 2

ABAP memory 1

ABAP memory 2

User terminal session

Internal session 1.1

Program 1.1

Internal session 2.1

Program 2.1

SAP memory
SAP AG 2002

When the called (inserted) program finishes, its internal session (the top one in the stack) is deleted.
Processing is resumed in the next-highest internal session in the stack.

(C) SAP AG

BC401

4-12

Restarting an Executable Program (1)


User terminal session
External session (window) 1

External session (window) 2

ABAP memory 2

ABAP memory 1

Internal session 1.3


Program 1.3
Internal session 1.2
Program 1.2
Internal session 1.1

Internal session 2.1


Program 2.1

Program 1.1

SAP memory
SAP AG 2002

When you end a program and start a new one, there is a distinction between calling an executable program
and calling a transaction, with regard to memory areas.

(C) SAP AG

BC401

4-13

Restarting an Executable Program (2)


User terminal session
Restart
External session (window) 1

External session (window) 2

ABAP memory 2

ABAP memory 1

Internal session 1.3'


Programm 1.3'
Internal session 1.2
Program 1.2
Internal session 1.1

Internal session 2.1


Program 2.1

Program 1.1

SAP memory
SAP AG 2002

If you call an executable program using its program name (terminating the calling program), the system
deletes the internal session of the program that you are terminating (the top one from the stack).
The system creates a new internal session, which in turn creates the program context of the called program.
The new session is placed on the stack Existing program contexts remain intact. The topmost internal
session on the stack is replaced.

(C) SAP AG

BC401

4-14

Restarting a Transaction (1)


User terminal session
External session (window) 1

External session (window) 2

ABAP memory 2

ABAP memory 1

Internal session 1.3


Program 1.3
Internal session 1.2
Program 1.2
Internal session 1.1

Internal session 2.1


Program 2.1

Program 1.1

SAP memory
SAP AG 2002

(C) SAP AG

BC401

4-15

Restarting a Transaction (2)


User terminal session
External session (window) 2

ABAP memory 2

ABAP memory 1'

External session (window) 1'

Interner Modus 1'.1

Program 2.1

Program 1'.1

Restart
(complete
initialization)

Internal session 2.1

SAP memory

SAP AG 2002

If you start a program using its transaction code (that is, if one was defined), all of the internal sessions on
the stack are deleted.
The system creates a new internal session, which in turn creates the program context of the called program.
After the call, the ABAP memory is initialized.

(C) SAP AG

BC401

4-16

Calling Programs and Passing Data (3)

Calling
Calling programs
programs
Memory
Memory management
management
Passing
Passing data
data

SAP AG 2002

(C) SAP AG

BC401

4-17

There are various ways of passing data to programs running in separate internal sessions:
You can use:
The interface of the called program (usually a standard selection screen)
ABAP memory
SAP memory
Database tables
Local files on your presentation server
The following slides deal with the first three of these methods.
For further information regarding the passing of data using database tables or the shared buffer, refer to the
documentation for the EXPORT and IMPORT statements.
For further information on transferring data between an ABAP program and a presentation server, refer to
the documentation for the function modules GUI_UPLOAD and GUI_DOWNLOAD.

(C) SAP AG

BC401

4-18

Passing Data Using the Program Interface

Program A

Data

Standard selection screen

Program B

SAP AG 2002

When you call ABAP programs that have a standard selection screen, you can pass data for the input fields
in the call.
There are two ways to do this:
By specifying a variant for the selection screen when you call the program
By specifying values for the input fields when you call the program

(C) SAP AG

BC401

4-19

Preassigning Values for Input Fields

Insert pattern

Pattern for SUBMIT


statement inserts the
appropriate frame for the
program call into the
source code

...
...
...

Other pattern

SUBMIT

DATA set TYPE|LIKE RANGE OF type|dataobject}.


SUBMIT prog_name AND RETURN [VIA SELECTION-SCREEN]
WITH parameter
EQ|NE|... val
WITH sel_opt
EQ|NE|... val
SIGN 'I'|'E'}
WITH sel_opt
BETWEEN val1 AND val2 SIGN 'I'|'E'}
WITH sel_opt NOT BETWEEN val1 AND val2 SIGN 'I'|'E'}
WITH sel_opt IN set
... .

SAP AG 2002

The WITH addition to the SUBMIT statement allows you to preassign values for parameters and selection
options on a standard selection screen of the called executable program. The abbreviations "EQ, NE, ...; I,
E" have the same meanings as with selection options.
If you want to pass several selections for a selection option, you can use the RANGE statement instead of
individual WITH additions. The RANGES statement creates a selection table, which you can fill as though
it were a selection option. You then pass the whole table to the executable program.
If you want to display the standard selection screen when you call the program, use the VIA
SELECTION-SCREEN addition.
When you use the SUBMIT statement, use the Pattern function in the ABAP Editor to insert an appropriate
statement pattern for the program you want to call. It automatically supplies the names of the parameters
and selection options that are available on the standard selection screen.
For further information about working with variants and about other syntax variants of the WITH addition,
refer to the documentation for the SUBMIT statement.

(C) SAP AG

BC401

4-20

ABAP Memory and SAP Memory


User terminal session

Internal session 1.2

Internal session 2.2

ABAP memory 2

External session (window) 2

ABAP memory 1

External session (window) 1

Program 1.2

Internal session 1.1

Program 1.1

Program 2.2

Internal session 2.1

Program 2.1

SAP memory (SET /GET parameters)


SAP AG 2002

You can use SAP memory and ABAP memory to pass data between programs.

SAP memory is a user-specific memory area for storing field values. It is only of limited value for
passing data between internal sessions. Values in SAP memory are retained for the duration of the user's
terminal session. The memory can be used between sessions in the same terminal session. You can use
the contents of SAP memory as default values for screen fields. All external sessions can use the SAP
memory.
ABAP memory is also user-specific. There is a local ABAP memory for each external session. You can
use it to exchange any ABAP variables (fields, structures, internal tables, complex objects) between the
internal sessions in any one external session.
When the user exits an external session (/i in the command field), the corresponding ABAP memory is
automatically initialized or released.

(C) SAP AG

BC401

4-21

Passing Data Using the ABAP Memory

Internal session 1

ABAP memory

PROGRAM p1 ... .
DATA: p1_spfli TYPE spfli,
it_spfli TYPE STANDARD TABLE
OF spfli.
...
EXPORT

EXPORT
wa_fli FROM p1_spfli
it_spfli
TO MEMORY ID 'MY_ID'.

MY_ID
wa_fli
it_spfli

Internal session 2

MY_ID1

...

PROGRAM p2 ... .
DATA: p2_spfli TYPE spfli,
it_spfli TYPE STANDARD TABLE
OF spfli.
...
IMPORT

IMPORT
wa_fli TO p2_spfli
it_spfli
FROM MEMORY ID 'MY_ID'.

SAP AG 2002

The EXPORT ... TO MEMORY statement allows you to copy any number of ABAP data objects with
their current values to the ABAP memory (data cluster).
The ID ... addition enables you to identify different clusters (maximum of 60 characters).
If you use a new EXPORT TO MEMORY statement for an existing data cluster, the new one will overwrite
the old.
The IMPORT ... FROM MEMORY ID ... statement allows you to copy the data from the ABAP
memory into corresponding data objects of your ABAP program.
It is also possible to only import parts of data clusters using IMPORT.
The data objects that are to receive the data from the ABAP memory cluster must have the same types in
both the calling and the called programs.
To release a data cluster, use the FREE MEMORY ID ... statement.
Bear in mind that when you call programs using transaction codes, you can only use the ABAP memory to
pass data when inserting (CALL TRANSACTION).

(C) SAP AG

BC401

4-22

Passing Parameters Using the SAP Memory

SET PARAMETER ID
'CON' FIELD sdyn_conn-connid.

Program A
Airline

LH

or

Connection 400

CALL TRANSACTION ... .

SET

SAP memory
CAR
CON

LH
400

Program B
Airline

LH

GET

Connection 400

or

GET PARAMETER ID
'CON' FIELD sdyn_conn-connid.

SAP AG 2002

You can define memory areas (parameters) in the SAP memory in various ways:
By creating input/output fields with reference to the ABAP Dictionary. These take the parameter name
of the data element to which they refer.
Alternatively, you can enter a name in the attributes of the input/output fields.
Here, you can also choose whether the entries from the field should be transferred to the parameter
(SET), or whether the input field should be filled with the value from the parameter (GET).
To find out about the names of the parameters assigned to input fields, display the field help for the field
(F1), then choose Technical info.
You can also fill the memory areas directly using the SET PARAMETER ID 'PAR_ID' FIELD
var. statement and read them using GET PARAMETER ID 'PAR_ID' FIELD var.
Finally, you can define parameters in the Object Navigator and let the user fill them with values.

(C) SAP AG

BC401

4-23

Preview: Passing Data Using an Internal Table


Program 1

Program 2: Transaction

...
DATA:
bi_itab TYPE TABLE OF bdcdata,
bi_wa
TYPE bdcdata.

T_CODE

bi_itab

* fill bi_itab
...
* call other program
CALL TRANSACTION 'T_CODE'
USING bi_itab.
IF sy-subrc = 0.
...
ELSE.
...

1st screen

2nd screen
F15

SAPM t_name
...
LEAVE PROGRAM.
...

SAP AG 2002

The CALL TRANSACTION 'T_CODE' USING bi_itab statement allows you to insert the
transaction T_CODE, and the screens are processed according to the internal table bi_itab.
This internal table must be typed according to the structure bdcdata and filled appropriately.
The MODE addition allows you to specify whether the screen contents should all be displayed ('A' - the
default setting), only when an error occurs ('E'), or not at all ('N').
The MESSAGES INTO mess_itab addition is used to specify where the system messages sent during
the execution of the called transaction are written.
The internal table must be typed according to the structure bdcmsgcoll.
You can find out if the transaction was executed successfully from the system field sy-subrc.
This technique is useful if, for example:
You are processing in the foreground, but the input fields have not been filled using GET parameters
You want to process the transaction in the background. In this case, you normally have to pass function
codes as well.
This technique is also one of the possible ways of transferring data from non-SAP systems.
To do so the internal table in the bdcdata format must be filled completely.
(C) SAP AG

BC401

4-24

Fields of the Global Type bdcdata

Field name
Length
Description

Note when
filling

program

dynpro

dynbegin

fnam

fval

40

132

132

Screen number

First record

Field name

Program name

Only in 1st
Only in 1st
record on screen record on screen

'X' for 1st


record on
screen,
otherwise ' '

Field value
Casesensitive

SAP AG 2002

Filling the internal table in batch input format:

Each screen that is to be processed and filled automatically in the transaction must be identified by a
line, in which only the fields program, dynpro and dynbegin are filled.

After the record that identifies the screen, use a separate bdcdata record for each field you want to
fill. These records use the table fields fnam and fval. The following fields can be filled:
Input/output fields, with data
The command field (bdc_okcode), with function codes
The cursor position field (bdc_cursor), with field names.

You also use the CALL TRANSACTION technique to transfer data from external systems.
Further information on this topic is available in the course BC420 (Data Transfer) and in the online
documentation.

(C) SAP AG

BC401

4-25

Example: Passing Data Using an Internal Table


program

dynpro

dynbegin

0100

SAPBC401_CALD_CREATE_CUSTOMER

fnam

fval

SCUSTOM-NAME <current_name>
SCUSTOM-CITY <current_city>
BDC_OKCODE

DATA:
bdcdata
wa_bdcdata TYPE bdcdata,
it_bdcdata LIKE TABLE OF wa_bdcdata.
* fill the bdcdata-table ...
CALL TRANSACTION 'BC401_CALD_CRE_CUST'
USING it_bdcdata
MODE 'N'.
IF sy-subrc <> 0.
MESSAGE ... WITH sy-subrc.
ENDIF.

SAVE

Save

ID for command
field

SAP AG 2002

This example refers to the transaction BC401_CALD_CTA_U. If you request the creation of a new
customer entry here, the transaction BC401_CALD_CRE_CUST is inserted. This transaction has not
implemented an import from the ABAP memory, and its input fields are not set as GET parameters. The
customer data is therefore passed using an internal table and the transaction processed in the background.
If the operation is successful, the new customer data record can be entered in the waiting list.

The relevant internal table in bdcdata format is shown above. current_name is the customer
name adopted from the input field at runtime, current_city is the city.
You address the command field using BDC_OKCODE. Here you enter the function code that is triggered by
the user choosing a function key, pushbutton, or menu entry during the dialog flow (or by entering a code
directly in the command field).

(C) SAP AG

BC401

4-26

Calling Programs and Passing Data: Unit Summary

You are now able to:


Describe the SAP R/3 memory model
Call executable programs
Call transactions
Use the various memory areas to pass data

SAP AG 2002

(C) SAP AG

BC401

4-27

Introduction to Object-Oriented Programming

Contents:
Procedural programming
Object-oriented programming
Aims of the ABAP Objects programming language

SAP AG 2002

(C) SAP AG

BC401

5-1

Introduction to Object-Oriented Programming: Unit


Objectives

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


Name the most significant differences between
procedural and object-oriented programming
State the aims behind developing the ABAP
Objects programming language

SAP AG 2002

(C) SAP AG

BC401

5-2

Introduction to Object-Oriented Programming:


Integration in Course Content

ing
Programm
d
te
n
e
ri
O
cttion to Obje Internal
Introduc
Using
and
Data Types
ts in
Data Objec
Detail

rams
Calling Prog
Data
and Passing

Tables

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

5-3

History of Programming Languages

Machine language
Assembler

C++

ABAP

Java

ABAP Objects

SAP AG 2002

Before ABAP, SAP used a macro assembler.


ABAP was created with the intention of improving reporting. ABAP developed almost independently as
an in-house programming language, although it was influenced by other programming languages, for
example, COBOL and PASCAL.
ABAP Objects is a true extension of ABAP. ABAP Objects unites the most promising aspects of other
object-oriented programming languages, such as Java, C++, and Smalltalk.

(C) SAP AG

BC401

5-4

Introduction: Programming Models (1)

Procedural
Procedural programming
programming
Object-oriented
Object-oriented programming
programming

SAP AG 2002

(C) SAP AG

BC401

5-5

Characteristics of Procedural Programming

Data

Data

Characteristics:

Data

Data

Separation of functions and data

Possibility of encapsulating
functions using modularization

Direct access to data possible visibility?

Data

Function
Function

Function

Function

Function

Function
Function

Function
Function

Function
Function

Function

SAP AG 2002

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

(C) SAP AG

BC401

5-6

Typical ABAP Program

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

Type definitions

DATA:
DATA: ...
...

Data declarations

Main program

...
...
PERFORM
PERFORM form1
form1 ...
...

Calling subroutines

CALL
CALL FUNCTION
FUNCTION 'FB1'
'FB1'
...
...
CALL
CALL FUNCTION
FUNCTION 'FB2'
'FB2'
...
...
*---------------------*---------------------FORM
FORM f1
f1 ...
...
...
...
ENDFORM.
ENDFORM.

Calling function modules

Definition of subroutines

SAP AG 2002

A typical ABAP program consists of type definitions and data declarations, which describe the blueprint
of the data the program uses when it is executed.
To make your program more readable and for better program structure, it is recommended that you work
with modularization units (encapsulated units with functions), such as form routines or function
modules. These components can be reused in many different programs.

(C) SAP AG

BC401

5-7

ABAP Main Memory and Function Groups


Internal session
Global data objects in
main program

Function groups

Function group 1
Global data

Function module 1
Function module 2
Function module ...

Function group 2
Global data
Subroutines
Interface

Function module 1
Function module 2

Interface

SAP AG 2002

This slide provides an overview of the main program components during program execution in an
internal session (main memory area on application server).
The loaded main program and the two function groups with their encapsulated modules (the function
modules) are both in separate memory areas.
From the main program, you can use function modules to access function group components, for
example their global data. Therefore, a function group is a unit consisting of data and functions that
manage this data.
A user "client" (here, the main program) can only access the function groups and their services using the
interface, that is the function modules. The function group acts as a "server", because it provides
services.

(C) SAP AG

BC401

5-8

Function Group Example

FUNCTION-POOL
FUNCTION-POOL s_vehicle.
s_vehicle.

Function group with


functions for controlling
the speed of a car

** speed
speed is
is aa global
global variable
variable
** used
used in
in the
the funtion-pool
funtion-pool
DATA:
DATA: speed
speed TYPE
TYPE I.
I.
...
...
FUNCTION
FUNCTION INC_SPEED.
INC_SPEED.
...
...
ADD
ADD imp_speed
imp_speed TO
TO speed.
speed.
ENDFUNCTION.
ENDFUNCTION.

S_VEHICLE
speed

FUNCTION
FUNCTION DEC_SPEED.
DEC_SPEED.
...
...
SUBTRACT
SUBTRACT IMP_SPEED
IMP_SPEED from
from speed.
speed.
ENDFUNCTION.
ENDFUNCTION.

inc_speed
dec_speed
get_speed
stop

FUNCTION
FUNCTION GET_SPEED.
GET_SPEED.
exp_speed
exp_speed == speed.
speed.
ENDFUNCTION.
ENDFUNCTION.
...
...
SAP AG 2002

The function group s_vehicle provides a user or client with the services inc_speed,
dec_speed, and get_speed.
These services make up the function group interface and access the internally encapsulated component
speed.

(C) SAP AG

BC401

5-9

Use of Function Group

REPORT
REPORT zvehicledemo.
zvehicledemo.

Main program that uses


function modules of this
function group

TYPES:
TYPES: ...
...
DATA:
DATA: wa_car
wa_car TYPE
TYPE ...
...
** no
no direct
direct access
access to
to speed
speed

S_VEHICLE

** use
use functions
functions of
of pool
pool
speed

CALL
CALL FUNCTION
FUNCTION 'INC_SPEED'
'INC_SPEED'
...
...

inc_speed

CALL
CALL FUNCTION
FUNCTION 'GET_SPEED'
'GET_SPEED'
...
...

dec_speed
get_speed
stop

CALL
CALL FUNCTION
FUNCTION 'STOP'
'STOP'
...
...

SAP AG 2002

The main program cannot access speed directly.

(C) SAP AG

BC401

5-10

Several Instances of One Function Group

Displaying a number of
vehicles and their speed is
only possible with
additional administration

S_VEHICLE
speed
inc_speed
dec_speed
get_speed
stop

SAP AG 2002

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

(C) SAP AG

BC401

5-11

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

(C) SAP AG

BC401

5-12

Introduction: Programming Models (2)

Procedural
Procedural programming
programming
Object-oriented
Object-oriented programming
programming

SAP AG 2002

(C) SAP AG

BC401

5-13

The left part of the slide shows that, with procedural software systems, data and functions are often:
Created separately
Stored separately
Linked with input-output relations
Objects form capsules containing the data itself and the behavior of that data. Objects enable you to draft
a software solution that is a one-to-one reflection of the real-life problem area.

(C) SAP AG

BC401

5-14

Characteristics of the Object-Oriented Approach

Real world

Objects are an abstraction of the real


world

Processes can be implemented


realistically

Objects are units made up of data and the


functions belonging to that data

Improves software structure and


consistency in the development process

Maintenance requirements are reduced

Modeler, end user, and developer are all


included in analysis and design process

SAP AG 2002

In object-oriented programming, data and functions are developed together. Object orientation focuses
on objects that represent either abstract or concrete things in the real world. They are first viewed in
terms of their characteristics, which are displayed using the object's internal structure and attributes
(data).
The behavior of objects is described through methods (functions) and events.
Consistency throughout the software development process:
The "language" used in the various phases of software development (analysis, specification, design, and
implementation) is uniform. Ideally, changes made to the design during the implementation phase will
flow back into the design automatically.
The aim is to use this concept to:
Implement processes realistically and, at the same time, better involve the modeler and developer in
the software design
Achieve optimized structuring and maintenance of the software and hence reduce the work required

(C) SAP AG

BC401

5-15

Encapsulation
Encapsulation means that the implementation of an object is hidden from other components in the
system, so that they cannot make assumptions about the internal status of the object and therefore
dependencies on specific implementations do not arise.
Polymorphism
Polymorphism (ability to have multiple forms) in the context of object technology signifies that objects
in different classes react differently to the same messages.
Inheritance
Inheritance defines the implementation relationship between classes, in which one class (the subclass)
shares the structure and the behavior defined in one or more other classes (superclasses).
Note: ABAP Objects only allows single inheritance.

(C) SAP AG

BC401

5-16

Objects behave like client/server systems: When an object calls a method of another object, it
automatically becomes the client of the other (server) object. This gives rise to two conditions:
- The client object must adhere to the protocol of the server object

- The protocol must be clearly described so that a potential client can follow it without problem
Objects normally adopt both roles Every object is a potential server object, and when it is called by a
method of another object, it becomes a client object too.
Establishing logical business and software/technical responsibilities between classes results in a true
client/server software system in which redundancy is avoided.

(C) SAP AG

BC401

5-17

Compatibility and Design Aims


Compatibility:

** ABAP
ABAP Objects
Objects Programm
Programm

DATA:
DATA: counter
counter TYPE
TYPE i,
i,
wa
wa type
type KNA1.
KNA1.
...
...

ABAP Objects is a true,


compatible extension of ABAP

CLASS
CLASS lcl_car
lcl_car DEFINITION.
DEFINITION.
...
...
ENDCLASS.
ENDCLASS.

ABAP Objects statements can


be used in procedural ABAP
programs

Objects (classes) themselves


contain classic ABAP
statements

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

Design aims were:


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

As simple as possible

Only object-oriented concepts


that have proved useful

Increased use of type checks

SAP AG 2002

ABAP Objects is not a new language, but has been developed as an extension of ABAP. It integrates
seamlessly into ABAP syntax and the ABAP programming model. All enhancements are strictly upward
compatible.
In ABAP objects, types have to be assigned more strictly than in ABAP. - for example, when defining
interface parameters for methods, you must type the parameters. The correct pass by value is then
checked by the system when the method is called.
In ABAP Objects, the ABAP language has been cleaned up. As part of this language clean up, the
system sometimes executes stricter syntax checks for previously permitted constructions and obsolete
statements are not allowed. The stricter syntax checks usually result in a syntax that should also be used
outside ABAP Objects, but where the old forms cannot be prohibited for compatibility reasons.
For further information, refer to the ABAP Objects documentation under Replacement of Obsolete
Statements.

(C) SAP AG

BC401

5-18

One feature and design aim of object-oriented languages is that business functions are held separately.
The client (in this case, the main program) uses the addresses of the objects (pointers or reference
variables) to access their encapsulated functions. Amongst other things, this concept is to improve the
structuring, reusability, and maintainability of the software.

(C) SAP AG

BC401

5-19

The Software Development Process

Requirement,
idea

Test

Already specified for the


purposes of this course

Iteration

Analysis and
design

Implementation
(ABAP Objects)

SAP AG 2002

In object-oriented programming, the analysis and design phase is even more important than it is for
procedural programming. The reason for this is that in object-oriented programming, decisions taken
during the analysis and design phase have even more pronounced effects on implementation than they do
in procedural programming.

(C) SAP AG

BC401

5-20

Introduction to Object-Oriented Programming:


Summary

You are now able to:


Name the most significant differences between
procedural and object-oriented programming
State the aims behind developing the ABAP
Objects programming language

SAP AG 2002

(C) SAP AG

BC401

5-21

Analysis and Design

Contents:
Classification of objects
UML
Class diagrams
Sequence diagrams

SAP AG 2002

(C) SAP AG

BC401

6-1

Analysis and Design: Unit Objectives

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


List some important diagram types in UML
Create a class diagram
Create a sequence diagram

SAP AG 2002

(C) SAP AG

BC401

6-2

Analysis and Design: Integration in Course Content

nd Design
Analysis a ted Programming

and
Data Types
ts in
Data Objec
Detail

t-Orien
n to Objec
Introductio
al
Using Intern
Tables

rams
Calling Prog
Data
and Passing

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

6-3

Analysis and Design (1)

Classification
Classification
UML
UML -- the
the modeling
modeling standard
standard

SAP AG 2002

(C) SAP AG

BC401

6-4

Classification of Objects

Real world

lcl_people

lcl_vehicle

Class creation / modeling


SAP AG 2002

In the real world, there are objects, such as various airplanes , cars, and people. Some of these objects are
very similar, that is, they can be described using the same attributes or characteristics and provide the
same functions.
Similar objects are grouped together in classes. Each class is described once, and each object is then
created in accordance with this blueprint.
A class is therefore a description of a quantity of objects characterized by the same structure and the
same behavior. For example, the vehicle "make x, ... serial number xxx" is an object of the class
"vehicle". This object is therefore a concrete instance of the class.

(C) SAP AG

BC401

6-5

Different Abstractions of a Class

Car enthusiast

Scrap merchant

Price

Make

price

make

lcl_vehicle

Equipping
equipping

- make

Color

- ...

color

- price

Type
model

Weight
weight

Doors
lcl_vehicle

doors

Wheels
wheels

PS

- equipping

Scrap value
scrapvalue

- make
- ...
- weight
- scrapvalue

- color

SAP AG 2002

In this context, abstractions are a simplified representations of complex relationships in the real world.
An actually existing object is abstracted to the significant dimensions that are to be mapped.
Insignificant details are left out in order to aid understanding of the overall system.
This example concerns cars. Software for a car enthusiast and software for a scrap merchant contain
different abstractions (classes) for these objects.
A class can contain very different objects depending on the abstraction.
While in one software system the class lcl_vehicle describes all transport vehicles (including
bikes), in another system it describes all motorized machines with wheels.
Both classes have the same name but describe different objects.
In our examples, the class lcl_vehicle describes all motorized vehicles with 4 wheels.

(C) SAP AG

BC401

6-6

Representation of a Class

lcl_vehicle

Class name

make
modell

Attributes

...

Optional, does
not have to be
Assoziationsme
specified

price
color
set_make

Methods

display_attributes

(functions)

increase_speed
...

SAP AG 2002

UML notation:
A class is represented with its name, attributes, and methods. With UML, you also have the option of
omitting either the attribute or the method part.
Attributes describe the data that can be stored in the objects in a class.
They define the state of an object.
Methods describe the functions that can be executed on the data of the object.
They contain the executable source code and therefore also represent an object's "behavior".
ABAP Objects events are not included in class diagrams.

(C) SAP AG

BC401

6-7

A class is a set of objects that have the same structure and the same behavior. A class is therefore like a
blueprint, in accordance with which all objects in that class are created.
Every object has an identity, a status (set of attribute values), and behavior (set of methods and events).
The structure and behavior of similar objects are defined in their shared class.
Identity is an attribute that distinguishes each object from all other objects. Identity is often confused
with having the same attribute values or with a unique name. Two different objects can have identical
attribute values and still not be identical.
Example:
Two coffee cups are the same height and diameter, have the same handle and are both white. Although
they look exactly the same, they are still two separate cups.
In German literature on the subject of object orientation, we often speak of instances. In object
orientation an instance is simply an object. Another synonym of object is instance.

(C) SAP AG

BC401

6-8

Analysis and Design (2)

Classification
Classification
UML
UML -- the
the modeling
modeling standard
standard

SAP AG 2002

(C) SAP AG

BC401

6-9

Modeling with UML

UML stands for Unified Modeling Language


It is a global standard
It is a language and form of notation for the specification,
construction, visualization, and documentation of models
for software systems

Diagram types:

Class diagram
Behavior diagram, such as a sequence diagram
Component diagram
Distribution diagram
...

SAP AG 2002

UML (Unified Modeling Language) is a standardized modeling language. It is used for the specification,
construction, visualization, and documentation of models for software systems and enables uniform
communication between various users. UML does not describe the steps in the object-oriented
development process.
UML is an industry standard and has been standardized by the OMG (Object Management Group) since
September 1997 as UML Version 1.1. The members of the OMG are continuously developing it further.
SAP uses UML as the company-wide standard for object-oriented modeling.
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.
Class diagrams show the static view of a model.
Behavior diagrams demonstrate the relationships and method calls between objects. They emphasize
the timing sequence of method calls.
Component diagrams show the organization and dependencies of components.
Distribution diagrams represent the dependencies of software and hardware.

(C) SAP AG

BC401

6-10

Example of a Class Diagram

lcl_rental

0..*

lcl_booking

0..* 1

lcl_customer

1..*

lcl_vehicle

lcl_car

lcl_truck

1..*

lcl_wheel

lcl_bus

SAP AG 2002

A class diagram describes the elements contained in the model and their various static relationships.
There are two basic forms of static relationships:
Associations (for example, a car rental customer books a car)
Generalization / specialization (for example, a car and a bus are both vehicles)
In class diagrams, classes can also be shown with their attributes and methods.

(C) SAP AG

BC401

6-11

Association

A customer can rent


several cars

lcl_booking 0..*

A booking refers to
a customer

books

lcl_customer

Association name

Common cardinalities
* or 0..*
1
1..*
0..1

Many
Exactly one
One or more
Zero or one

SAP AG 2002

An association describes a semantic relationship between classes. The specific relationship between
objects in these classes is known as an object link. Object links are therefore the instances of an
association.
An association is usually a relationship between different classes. However, an association can also be
recursive; in this case, the class would have a relationship with itself. In most cases, recursive
associations are used to link two different objects in one class.
The points below assume that the associations are binary.
Each association has two roles, one for each direction of the association (booking
customer, customer
booking). Roles can have names (for example, the association car reservation could be called
"reservation").
Each role has a cardinality that shows how many instances participate in this relationship. The
multiplicity is the number of participating objects in one class that have a relationship to an object in the
other class.
UML notation:
An association is represented by a line between the class symbols
The cardinality of the relationship can be shown at each end of the line
Associations can be given a name for ease of identification (a verb or a short text). This name is
written in italics above the line and may have an arrow to show the read direction. Both are
optional.

(C) SAP AG

BC401

6-12

Aggregation and Composition

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

Aggregation symbol

lcl_vehicle

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

0..*

lcl_wheel

Composition symbol

lcl_rental

1..*

lcl_booking

SAP AG 2002

Aggregation is a special kind of association. Aggregation describes one object that contains another or
consists of other objects (whole-part). A vehicle consists of wheels. The relationship can be described by
the words "consists of" or "is a part of".
UML notation for aggregation:
An aggregation, like an association, is represented by a line between two classes, which then additionally
has a small rhombus at one end. The rhombus is always at the aggregate end, that is, the whole object
end. Otherwise the notation conventions are the same as for associations.
Composition is a special kind of aggregation. Composition describes the fact that the object contained
cannot exist without the aggregate (for example, a car reservation cannot exist without the car rental).
Differences to aggregation:
The cardinality on the aggregate side can only be one. Each part is only part of one composite object,
otherwise the existence dependency would be contradictory. The lifetime of the individual parts is linked
to the lifetime of the aggregate: Parts are created either with or immediately after the aggregate, and they
are destroyed either with or immediately before the aggregate.
UML notation for composition:
Like aggregation, composition is shown as a line between two classes and marked with a small rhombus
on the aggregate side. However, in contrast to aggregation, the rhombus is filled in.

(C) SAP AG

BC401

6-13

Generalization and Specialization

lcl_car

lcl_truck

Generalization

Inheritance arrow

Specialization

lcl_vehicle

lcl_vehicle

lcl_car

lcl_truck

Generalization

Specialization

or

SAP AG 2002

UML notation:
Generalization and specialization are denoted by triangular arrows that point from the subordinate class
to the superclass.
Several arrows can be combined into a tree.

(C) SAP AG

BC401

6-14

Sequence Diagrams: Example

lcl_driver

lcl_car

1:Method (parameter)
Time

Process
description
(optional)

Life line
of object

Return value

Control focus

SAP AG 2002

Sequence diagrams, unlike class diagrams, show the dynamics between objects. They are used to
represent a particular process or a particular situation. Sequence diagrams focus on the time sequence of
the information exchange:
a) Creation and deletion of objects
b) Message exchange between objects
Sequence diagrams have no notation for representing static methods.
The object life line is represented by vertical dotted lines.
The control focus is shown as a vertical rectangle on the object life line. The control focus shows the
object's "active" period:
An object is active when actions are executed
An object is indirectly active if it is waiting for a subordinate procedure to end.
Messages are shown as horizontal arrows between the object lines. The message is written above the
arrow in the form method (parameter). There are various ways of representing the reply; in this example,
the arrow is shown as a returning arrow.
You can also include a description of the process and add comments to the object life line as required.

(C) SAP AG

BC401

6-15

Sequence Diagram: Delegation

lcl_driver

lcl_car

lcl_tank

1: get_fuel_level( )
2: get_fuel_level( )
re_level
re_level

re_level =
tank->get_fuel_level( ).

re_level =
fuel / fuel_max * 100.

SAP AG 2002

In delegation, two objects are involved in handling a request: The recipient of the request delegates the
execution of the request to a delegate.
Example:
The driver (lcl_driver) calls the method get_fuel_level for the class car (lcl_car). The car
cannot carry out this task itself. Therefore, the car calls the get_fuel_level method for the class
(lcl_tank), that is the car delegates the execution of the method to the tank.
The main advantage of delegation (as a re-use mechanism) lies in the option of changing the behavior of
the recipient by substituting the delegate (at runtime). For example, delegation enables the car to be
equipped with a new tank, without the call changing for the client or for the car class.
Good encapsulation often forces the use of delegation: If tank in the above example were a private
attribute of the class lcl_car, the user could not address the tank directly, but only through the car.

(C) SAP AG

BC401

6-16

Analysis and Design: Summary

You are now able to:


List some diagram types in UML
Create a class diagram
Create a sequence diagram

SAP AG 2002

(C) SAP AG

BC401

6-17

Analysis and Design Exercises


Unit: Analysis and Design
Topic: UML Class Diagrams
At the conclusion of these exercises, you will be able to:
Create a UML class diagram

An airline needs to manage its airplanes.

1-1

Use a pencil and paper to create a UML class diagram that contains the following
classes:
- Airline:
lcl_carrier
Airplane (general): lcl_airplane
Passenger airplane: lcl_passenger_plane
Cargo plane:
lcl_cargo_plane
1-1-1 Include some appropriate attributes and methods for every class.
1-1-2 Draw lines to represent the relationships between the classes and indicate
possible cardinalities.

(C) SAP AG

BC401

6-18

Analysis and Design Solutions


Unit: Analysis and Design
Topic: UML Class Diagrams

(C) SAP AG

BC401

6-19

Principles of Object-Oriented Programming

Contents:
Classes
Objects
Attributes
Methods
Visibility/encapsulation
Instantiation
Constructor
Garbage collector

SAP AG 2002

(C) SAP AG

BC401

7-1

Principles of Object-Oriented Programming: Unit


Objectives

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


Create classes
Create objects
Call methods
Explain how the garbage collector works

SAP AG 2002

(C) SAP AG

BC401

7-2

Principles of Object-Oriented Programming:


Integration in Course Content

mming
ted Progra
n
e
ri
O
tc
of Obje
ign
s and Des
Principles
Analysi

and
Data Types
ts in
Data Objec
Detail

ammin
ted Progr
ect-Orien
bj
O
to
n
Introductio
al
Using Intern
Tables

rams
Calling Prog
Data
and Passing

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

7-3

Principles (1)

Classes,
Classes, attributes,
attributes, and
and methods
methods
Objects,
Objects, instances
instances of
of classes
classes
Accessing
Accessing attributes
attributes and
and methods
methods
The
The constructor
constructor
Additional
Additional principles
principles

SAP AG 2002

(C) SAP AG

BC401

7-4

Example of a Class

lcl_vehicle

Represented in
course by

Private
components

Public
components
get_make

make

set_make

model

Methods:
Implementation

Private access
Encapsulation
Normally attributes

Public access
Interface
Normally methods, events

SAP AG 2002

In the graphic, the public component of the class is accessed using the green node or starting point
displayed on the left. A user or client can use this node to access the public components and hence also
indirectly access the private components. However, the private components of the class cannot be
addressed directly . They are not visible to the outside user.
Why are the private components of a class hidden?
This principle is called information hiding or encapsulation and is used to protect the user.
Let us assume that a class changes its private components, while its interface remains unchanged. Any
user who simply needs to access the interface of the class can carry on working with the class as usual.
The user does not notice the change.
However, if an class changes its public components, then any user who accesses these public
components must take these changes into account.

(C) SAP AG

BC401

7-5

Defining Classes

ABAP code
CLASS lcl_vehicle DEFINITION.

lcl_vehicle
Public
components

ENDCLASS.

Private
components

CLASS lcl_vehicle IMPLEMENTATION.


Method
implementation

ENDCLASS.

SAP AG 2002

A class is a set of objects that have the same structure and the same behavior. A class is therefore like a
blueprint, in accordance with which all objects in that class are created.
The components of the class are defined in the definition part. The components are attributes, methods,
events, constants, types, and implemented interfaces. Only methods are implemented in the
implementation part.
The CLASS statement cannot be nested, that is, you cannot define a class within a class.

(C) SAP AG

BC401

7-6

Attributes

Attributes can have any kind of


data type:

(5) lcl_car

C, N, I, P, ..., STRING
Dictionary types

Public

User-defined types
TYPE REF TO
defines a reference to an
object, in this case r_car

Private
make TYPE STRING,
...
r_motor
TYPE REF TO ...

(3) lcl_rental

r_car

SAP AG 2002

Attributes describe the data that can be stored in the objects of a class.
Class attributes can be of any type:
Data types: scalar (for example data element), structured, in tables
ABAP elementary types (C, I, ...)
Object references
Interface references
Examples of attributes for the class lcl_car are:
make
(car make)
modell
(type , model)
ser_no
(serial number)
color
(color)
car_type(estate, convertible, ...)
max_seats (number of seats)
r_motor
(reference to class lcl_motor)
...

(C) SAP AG

BC401

7-7

Attributes, Types, and Constants: Syntax

CLASS <classname> DEFINITION.


...
TYPES: <normale Typdefinition>.
CONSTANTS: constant TYPE <type> VALUE <value>.
DATA: variable1
variable2
variable3
variable4
variable5
variable6
variable7

TYPE
TYPE
LIKE
TYPE
TYPE
TYPE
TYPE

<type>,
<ddic_type>,
variable1,
<type> VALUE <value>,
<type> READ-ONLY,
REF TO <classname>,
REF TO <interface>.

CLASS-DATA: only_once TYPE ... .


ENDCLASS.

SAP AG 2002

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 declared with DATA can be read from outside,
but can only be changed by methods of the 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.

(C) SAP AG

BC401

7-8

Attributes and Visibility

CLASS lcl_vehicle DEFINITION.

Public attributes

Can be viewed and


changed by all users and
in all methods

PUBLIC SECTION.
DATA: make TYPE string.
PRIVATE SECTION.
ENDCLASS.

Direct access
CLASS lcl_vehicle DEFINITION.

Private attributes

Can only be viewed and


changed from within the
class
No direct access
from outside the class

PUBLIC SECTION.
...

PRIVATE SECTION.
DATA: make

TYPE string.

ENDCLASS.

SAP AG 2002

You can protect attributes against access from outside by characterizing them as private attributes
(defined in the PRIVATE SECTION).
Attributes and their values that may be used directly by an external user are public attributes and are
defined in the PUBLIC SECTION.
In the above example for the class lcl_car, the attribute make is defined as a public attribute.
Public attributes belong to the interface of the class, that is their implementation is publicized. If you
want to hide the internal implementation from users, you must define internal and external views of
attributes.
As a general rule, you should define as few public attributes as possible.

(C) SAP AG

BC401

7-9

Accessing Private Attributes

Client

(5) lcl_vehicle
Public

Private
make

set_make
get_make
r_vehicle

...

SAP AG 2002

You can access an object's private attributes using public methods, which in turn output this attribute or
change it.
It is not possible to directly access private attributes from outside (for example, main program or other
object). The only exception lies in the so-called "friend" concept, which will be dealt with later in the
course.

(C) SAP AG

BC401

7-10

Instance Attributes and Static Attributes (1)

Instance attributes

CLASS lcl_vehicle DEFINITION.

One per instance

PUBLIC SECTION.

Statement: DATA

PRIVATE SECTION.
DATA: make

...

Static attributes

Only one per class

Statement: CLASS-DATA

Also known as class


attributes

TYPE string,

...

CLASS-DATA: n_o_vehicles TYPE i.


ENDCLASS.

SAP AG 2002

There are two kinds of attributes:


Static attributes
Instance attributes
Instance attributes are attributes that exist separately for each object.
Instance attributes are defined using the ABAP keyword DATA.
Static attributes exist only once for each class and are visible for all (runtime) instances in that class.
Static attributes usually contain information that applies to all instances, such as:
Data that is the same in all instances
Administrative information about the instances in that class (for example, counters, ...)
Static attributes are defined using the CLASS-DATA keyword.
You may come across the expression "class attributes" in documentation, however, the official term in
ABAP Objects (as in C++, Java) is "static" attributes.

(C) SAP AG

BC401

7-11

Instance Attributes and Static Attributes (2)

Internal session
Global data objects
n_o_vehicles

Static attributes
only exist once

Static attributes
(1) lcl_vehicle

r_vehicle1

(2) lcl_vehicle

Instances /
objects

r_vehicle2
(3) lcl_vehicle

r_vehicle3
...

...

SAP AG 2002

The graphic shows the static attribute n_o_vehicles.


It exists only once, regardless of how many instances there are of lcl_vehicle.
Therefore, you can say that instances share their common attributes.

(C) SAP AG

BC401

7-12

Methods: Syntax

Methods can have


a signature
CLASS <classname> DEFINITION.
...
METHODS: <method_name>
[ IMPORTING <im_var> TYPE <type>
EXPORTING <ex_var> TYPE <type>
CHANGING <ch_var> TYPE <type>
RETURNING VALUE(<re_var>) TYPE <type>
EXCEPTIONS <exception>
RAISING
<class_exception> ].
ENDCLASS.
CLASS <classname> IMPLEMENTATION.
METHOD <method_name>.
...
ENDMETHOD.
ENDCLASS.

Methods contain the


source code, and hence
define the behavior of an
object

SAP AG 2002

Methods are internal procedures in classes that determine the behavior of an object. They can access all
attributes in their class and can therefore change the state of an object.
Methods have a parameter interface (called signature) that enables them to receive values when they are
called and pass values back to the calling program.
In ABAP Objects, methods can have IMPORTING, EXPORTING, CHANGING, and RETURNING
parameters as well as exception parameters. All parameters can be passed by value or reference. (As of
SAP R/3 Basis Release 6.10, you should no longer use the EXCEPTIONS parameter for exceptions but
use the RAISING addition instead; this will be discussed in more detail later.)
You can define a return code for methods using RETURNING. You can only do this for a single
parameter, which additionally must be passed as a value. Also, you cannot then define EXPORTING and
CHANGING parameters. You can define functional methods using the RETURNING parameter (this will
be explained in more detail).
All input parameters (IMPORTING, CHANGING parameters) can be defined as optional parameters in
the declaration using the OPTIONAL or DEFAULT additions. These parameters then do not necessarily
have to be passed when the object is called. If you use the OPTIONAL addition, the parameter remains
initialized according to type, whereas the DEFAULT addition allows you to enter a start value.

(C) SAP AG

BC401

7-13

Accessing Private Methods

Client

(5) lcl_vehicle
Public

Private
make
...

r_vehicle

...
set_make

init_make

SAP AG 2002

Methods also have to be assigned to a visibility area. This determines whether the methods can be called
from outside or only from within the class.
It is not possible to directly access private methods from outside. However, a private method can be
called by a public method.
Both method types can access the public and private attributes.

(C) SAP AG

BC401

7-14

Methods and Visibility

Public methods

Can be called from


anywhere

Private methods

Can only be called


within the class

CLASS lcl_vehicle DEFINITION.


PUBLIC SECTION.
METHODS: set_make importing
im_make TYPE string.
PRIVATE SECTION.
METHODS: init_make.
DATA: make TYPE string.
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
METHOD init_make.
make = 'no make'.
ENDMETHOD.
METHOD set_make.
IF im_make IS INITIAL.
*
Calling init_make
...
ELSE.
make = im_make.
ENDIF.
ENDMETHOD.
ENDCLASS.

SAP AG 2002

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

(C) SAP AG

BC401

7-15

Instance Methods and Static Methods

Rules:
Instance methods

Can use both static and instance components in their


implementation part

Can be called using an instance

Static methods

Can only use static components in their implementation


part

Can be called using the class

SAP AG 2002

Static methods are defined at class level. They are similar to instance methods, but with the restriction
that they can only use static components (such as static attributes) in the implementation part. This
means that static methods do not need instances and can be called from anywhere. They are defined
using the CLASS-METHODS statement, and they are bound by the same syntax and parameter rules as
instance methods.
The term "class method" is common, but the official term in ABAP Objects (as in C++, Java) is "static
method".

(C) SAP AG

BC401

7-16

Instance Methods and Static Methods: Example

CLASS lcl_vehicle DEFINITION.


PUBLIC SECTION.
METHODS:
set_make IMPORTING im_make TYPE string.
CLASS-METHODS: get_count EXPORTING ex_count TYPE i.
PRIVATE SECTION.
DATA:
make TYPE string.
CLASS-DATA: n_o_vehicles TYPE i.
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
...
METHOD get_count.
ex_count = n_o_vehicles.
ENDMETHOD
ENDCLASS.

SAP AG 2002

In the static method get_count, you can only use the static attribute n_o_vehicles. All other
attributes of the class are instance attributes and can only appear in instance methods.

(C) SAP AG

BC401

7-17

Summary and UML Notation

lcl_vehicle
- make
- model
- n_o_vehicles
...

+ refers to public components


- refers to private components
_ static components are underlined

+ set_make
- init_make
+ get_count
...
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS:
set_make IMPORTING im_make TYPE string.
CLASS-METHODS: get_count EXPORTING ex_count TYPE i.
PRIVATE SECTION.
DATA:
make TYPE string. ...
CLASS-DATA: n_o_vehicles TYPE i.
METHODS: init_make.
ENDCLASS.
SAP AG 2002

A UML class diagram shows firstly the class name and, underneath that, the class attributes and
methods.
The visibility of components in a class is shown in UML using the characters "+" and "-":
+ indicates public components
- indicates private components
Alternatively, public and private can be prefixed to the methods. The third option for providers of
modeling tools in UML is to introduce their own symbols for visibility.
Representation of visibility characteristics is optional and is normally only used for models that are close
to implementation.
Static components are marked with an underscore.
The method signature is represented as follows (optional):
The input and output parameters and the parameters to be changed are shown in brackets.
The return code is separated from the type name by a colon.

(C) SAP AG

BC401

7-18

Principles (2)

Classes,
Classes, attributes,
attributes, and
and methods
methods
Objects,
Objects, instances
instances of
of classes
classes
Accessing
Accessing attributes
attributes and
and methods
methods
The
The constructor
constructor
Additional
Additional principles
principles

SAP AG 2002

(C) SAP AG

BC401

7-19

Creating Objects

Rules:

Objects are created using the CREATE OBJECT


statement

Objects can only be created and addressed using


reference variables

lcl_vehicle
- make
- model
- ser_no
- n_o_vehicles
+ set_make
- init_make
+ get_count
...

CREATE OBJECT r_vehicle

(5) lcl_vehicle
Public

...
r_vehicle

set_make
get_count
...

Private
make
modell
ser_no
...

SAP AG 2002

A class contains the generic description of an object. It describes all the characteristics that are common
to all objects in that class. During the program runtime, the class is used to create specific objects
(instances). This process is called instantiation.
Example:
The specific object Car xy with Ser-No. 0815" is created through instantiation from the class
lcl_vehicle; it is created in the main memory at runtime.
The lcl_vehicle class itself does not exist as an independent runtime object in ABAP Objects.
Implementation:
Objects are instantiated using the statement: CREATE OBJECT.
During instantiation, the runtime environment dynamically requests main memory space and assigns it to
the object.

(C) SAP AG

BC401

7-20

Reference Variables

...
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
...
PRIVATE SECTION.
...
ENDCLASS.

What do these
reference variables
point to?

CLASS lcl_vehicle IMPLEMENTATION.


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

r_vehicle2

?
?

START-OF_SELECTION.

...
SAP AG 2002

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

(C) SAP AG

BC401

7-21

Creating Objects: Syntax

DATA: r_vehicle1 TYPE REF TO lcl_vehicle,


r_vehicle2 TYPE REF TO lcl_vehicle.
CREATE OBJECT r_vehicle1.
CREATE OBJECT r_vehicle2.
(3) lcl_vehicle
Public

Private

r_vehicle1

(4) lcl_vehicle

r_vehicle2

Public

Private

SAP AG 2002

The CREATE OBJECT statement creates an object in the main memory. The attribute values of this
object are either initial values or correspond to the VALUE entry.
Reference variables can also be assigned to each other.
For the above example this would mean that r_vehicle1 and r_vehicle2 point to the same object.

(C) SAP AG

BC401

7-22

Garbage Collector

DATA: r_vehicle1 TYPE REF TO lcl_vehicle,


r_vehicle2 TYPE REF TO lcl_vehicle.
CREATE OBJECT r_vehicle1.
CREATE OBJECT r_vehicle2.
(3) lcl_vehicle

r_vehicle2 = r_vehicle1

Public

Private

r_vehicle1

(4) lcl_vehicle

r_vehicle2

Public

Private

SAP AG 2002

As soon as no more references point to an object, the Garbage Collector removes it from the memory.
The Garbage Collector is a system routine that automatically deletes objects that can no longer be
addressed from the main memory and releases the memory space they occupied.

(C) SAP AG

BC401

7-23

Garbage Collector: Procedure

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

References of class or instance attributes to other objects are followed.


These objects are also marked.

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

(4) lcl_object

Deleted
(2) lcl_object

(5) lcl_object

SAP AG 2002

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

(C) SAP AG

BC401

7-24

If you want to keep several objects from the same class in your program, you can define an internal
table, which, for example, only consist of one column containing the object references for this class.
You can process the objects using a LOOP through the internal table.

(C) SAP AG

BC401

7-25

If a class defines object references to a second class as attributes (in the above example: References to
objects of the class lcl_wheel), only these object references will be stored in an object belonging to
that class.
The objects in the second class lcl_wheel have their own identity. They are encapsulated in the first
class lcl_vehicle and can only be addressed from this class using reference variables.

(C) SAP AG

BC401

7-26

Principles (3)

Classes,
Classes, attributes,
attributes, and
and methods
methods
Objects,
Objects, instances
instances of
of classes
classes
Accessing
Accessing attributes
attributes and
and methods
methods
The
The constructor
constructor
Additional
Additional principles
principles

SAP AG 2002

(C) SAP AG

BC401

7-27

Calling Methods

Client
(5) lcl_vehicle
Public

Private

motor_on

r_vehicle->motor_on( )

Method
Reference
Component selector

SAP AG 2002

Every object behaves in a certain way. This behavior is determined by its methods. There are three types
of method:
1. Methods that trigger the behavior and do not return values (see example)
2. Methods that return a value
3. Methods that return or change several values
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.
The example shows the new syntax for method calls, in which the CALL-METHOD prefix is omitted.

(C) SAP AG

BC401

7-28

Calling Instance Methods: Syntax


Instance methods: CALL METHOD <instance>-><instance_method>
EXPORTING <im_var> = <variable>
IMPORTING <ex_var> = <variable>
CHANGING <ch_var> = <variable>
RECEIVING <re_var> = <variable>
EXCEPTIONS <exception> = <nr>.
Shortened notation as of 4.6C:
(see online documentation)

<instance>-><instance_method>
( [additions] )

DATA: r_vehicle TYPE REF TO lcl_vehicle.


DATA: make_name TYPE STRING.
...

make_name = 'the make of the car'.


CALL METHOD r_vehicle->set_make EXPORTING im_make = make_name.
* other variant, since 6.1 available, see documentation!
r_vehicle->set_make( make_name )
* now getting something back from method...
r_vehicle->get_make( IMPORTING ex_make = make_name ).

SAP AG 2002

Instance methods are called using CALL METHOD <reference>-><instance_method>.


Since SAP R/3 Basis Release 6.10, the shortened form is also supported; CALL METHOD is omitted. For
further information, refer to the online documentation.
Special case: When calling an instance method from within another instance method, you can omit the
instance name. The method is automatically executed for the current object.
For the method call set_make, you can omit the EXPORTING addition in the brackets. In this case, it
is sufficient to set the actual parameter of the caller (in the example: make_name). However, if the
method has two or more parameters in its interface, all actual and formal parameters within the brackets
must have the EXPORTING addition.
In the case of methods that return parameters to the caller, the IMPORTING addition must always be
used and all actual and formal parameters must be listed.
In method calls, multiple parameters are separated by spaces.

(C) SAP AG

BC401

7-29

Calling Static Methods: Syntax

Static methods:

CALL METHOD <classname>=><class_method>


( [additions] )
<classname>=><class_method>
( [additions] )

DATA: r_vehicle TYPE REF TO lcl_vehicle.


DATA: make_name TYPE STRING,
count TYPE I.
...

* get_count has one interface-parameter re_count


CALL METHOD lcl_vehicle=>get_count( IMPORTING re_count = count ).
* other variant, since 6.1 available, see documentation
lcl_vehicle=>get_count( IMPORTING re_count = count ).

SAP AG 2002

Static methods (also referred to as class methods) are called using CALL METHOD
<classname>=><class_method>.
Static methods are addressed with their class name, since they do not need instances.
Note:
If you are calling a static method from within the class, you can omit the class name.

(C) SAP AG

BC401

7-30

Functional Methods

Example

a = b +

Functional method

When defining:
Only one RETURNING parameter
Only IMPORTING parameters and exceptions are possible

When calling:
a) RECEIVING parameters possible
b) Various forms of direct call possible:

MOVE, CASE, LOOP


Logical expressions (IF, ELSEIF, WHILE, CHECK, WAIT)
Arithmetic expressions and bit expressions (COMPUTE),
see example: a = b + c

SAP AG 2002

Methods that have a RETURNING parameter are described as functional methods. These methods cannot
have EXPORTING or CHANGING parameters, but has many (or as few) IMPORTING parameters and
exceptions as required.
Functional methods can be used directly in various expressions:
Logical expressions (IF, ELSEIF, WHILE, CHECK, WAIT)
The CASE statement (CASE, WHEN)
The LOOP statement
Arithmetic expressions (COMPUTE)
Bit expressions (COMPUTE)
The MOVE statement.

(C) SAP AG

BC401

7-31

Functional Methods: Example


CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS: get_average_fuel
IMPORTING im_distance
TYPE s_distance,
im_fuel
TYPE ty_fuel
RETURNING VALUE(re_fuel) TYPE ty_fuel,
ENDCLASS.

DATA: r_vehicle1 TYPE REF TO lcl_vehicle,


r_vehicle2 TYPE REF TO lcl_vehicle,
avg_fuel TYPE ty_fuel.
...

* example for short syntax in aritmet. operation


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

SAP AG 2002

Depending on the number of IMPORTING parameters, the syntax for functional methods is as follows
(same for static functional methods):
No IMPORTING parameters:
ref->func_method( )
Exactly 1 IMPORTING parameter: ref->func_method( p1 ) or
ref->func_method( im_1 = p1 )
Several IMPORTING parameters: ref->func_method( im_1 = p1 im_2 = p2 )
Example of detailed syntax for functional method call:
CALL METHOD r_vehicle->get_average_fuel
EXPORTING im_distance = 500
im_fuel
= 50
RECEIVING re_fuel
= avg_fuel.

Here, re_fuel is the formal parameter of the interface and avg_fuel is the actual parameter of the
calling program.

(C) SAP AG

BC401

7-32

External Access to Public Attributes

CLASS lcl_vehicle DEFINITION.


PUBLIC SECTION.
DATA: make TYPE string READ-ONLY.
CLASS-DATA: n_o_vehicles TYPE i READ-ONLY.

just a demo
just a demo

...

ENDCLASS.
...

(2) lcl_vehicle

DATA: r_vehicle TYPE REF TO lcl_vehicle.


DATA: make_name TYPE string,
count TYPE i.

make
...

START-OF-SELECTION.
*--------------------------------------* main program, think of a client !
CREATE OBJECT r_vehicle.
r_vehicle
make_name = r_vehicle->make.
count = lcl_vehicle=>n_o_vehicles.

only if public attr.


only if public attr.

SAP AG 2002

There are different ways of accessing public attributes from outside the class:
You access static attributes using <classname>=><class_attribute>
You access instance attributes using <instance>-><instance_attribute>
=> and -> are the component selectors

(C) SAP AG

BC401

7-33

Principles (4)

Classes,
Classes, attributes,
attributes, and
and methods
methods
Objects,
Objects, instances
instances of
of classes
classes
Accessing
Accessing attributes
attributes and
and methods
methods
The
The constructor
constructor
Additional
Additional principles
principles

SAP AG 2002

(C) SAP AG

BC401

7-34

Constructor

lcl_vehicle

Special method for creating


objects with defined initial state

Only has IMPORTING


parameters and EXCEPTIONS

Is executed only once per


instance

- make
- model
- n_o_vehicles
...
+ constructor
...

CREATE OBJECT

(3) lcl_vehicle
Public

Private

METHODS constructor IMPORTING <im_parameter>


EXCEPTIONS <exception>.

SAP AG 2002

The constructor is a special instance method in a class with the name constructor. The following
rules apply:
Each class can have one constructor.
The constructor is automatically called at runtime within the CREATE OBJECT statement.
If you need to implement the constructor, then you must define and implement it in the PUBLIC
SECTION.
When exceptions are raised in the constructor, instances are not created, so no main memory space is
occupied.

(C) SAP AG

BC401

7-35

Constructor: Example
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS constructor IMPORTING im_make
TYPE string
im_model TYPE string.
PRIVATE SECTION.
DATA: make TYPE string, weight TYPE p.
CLASS-DATA n_o_vehicles TYPE i.
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
METHOD constructor.
make = im_make.
model = im_model.
ADD 1 TO n_o_vehicles.
ENDMETHOD.
ENDCLASS.

Automatic constructor call

DATA r_vehicle TYPE REF TO lcl_vehicle.


...
CREATE OBJECT r_vehicle
EXPORTING im_make
= 'Ferrari'
im_model = 'F40'.

Call from the


main program

SAP AG 2002

You need to implement the constructor when, for example:


You need to allocate (external) resources
You need to initialize attributes that cannot be covered by the VALUE addition to the DATA
statement
You need to modify static attributes
You cannot normally call the constructor explicitly.

(C) SAP AG

BC401

7-36

Preview: Static Constructor

CLASS lcl_vehicle DEFINITION.


PUBLIC SECTION.
CLASS-METHODS: CLASS_CONSTRUCTOR.
PRIVATE SECTION.
CLASS-DATA: n_o_vehicles TYPE I.
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
METHOD CLASS_CONSTRUCTOR.
...
ENDMETHOD. ...
ENDCLASS.

Special static method

Automatically called before


the class is first accessed

Only executed once per


program

* Static Constructor is called before following statements:


* demo 1
CREATE OBJECT r_vehicle.
* demo 2
counter = lcl_vehicle=>n_o_vehicles. if attribute is public
* demo 3
lcl_vehicle=>get_count( importing re_count = counter ).
SAP AG 2002

The static constructor is a special static method in a class with the name class_constructor. It is
executed precisely once per program. The static constructor of a class <classname> is called
automatically when the class is first accessed, but before any of the following actions are executed:

Creating an instance in the class using CREATE OBJECT <obj>, where <obj> has the data type
REF TO <classname>
Addressing a static attribute using <classname>=><attribute>
Calling a static attribute using CALL METHOD <classname>=><classmethod>
Registering a static event handler method using SET HANDLER
<classname>=><handler_method> FOR <obj>
Registering an event handler method for a static event in class <classname>.
The static constructor cannot be called explicitly.

(C) SAP AG

BC401

7-37

Principles (5)

Classes,
Classes, attributes,
attributes, and
and methods
methods
Objects,
Objects, instances
instances of
of classes
classes
Accessing
Accessing attributes
attributes and
and methods
methods
The
The constructor
constructor
Additional
Additional principles
principles

SAP AG 2002

(C) SAP AG

BC401

7-38

Namespace Within a Class

lcl_vehicle

The same namespace for

Attributes

Methods

Events

Types

Constants

Public
components

Method
make

Private
components

Attribute
make

Method
implementation

ALIAS names

There is a local namespace within


methods

SAP AG 2002

Within a class, attribute names, method names, event names, constant names, type names and alias
names all share the same namespace.
There is a local namespace within methods. Definitions of local variables can cover components in one
class.

(C) SAP AG

BC401

7-39

The Reference Variable ME


CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS constructor
IMPORTING im_make TYPE string
im_modell TYPE string.
PRIVATE SECTION.
DATA make TYPE string. ...
ENDCLASS.
CLASS lcl_vehicle IMPLEMENTATION.
METHOD constructor. just a demo
DATA make TYPE string VALUE 'Benz'.
CONCATENATE im_make make INTO ME->make.
ENDMETHOD.

lcl_vehicle
Public
components

Private
components

Attribute
make

Method
implementation

ME->make

METHOD DUMMY.
* calling own methods from inside class
* call method display_attributes( )
* with the short syntax variant:
display_attributes( ).
ENDMETHOD.
ENDCLASS.
SAP AG 2002

You can address the object itself within instance methods using the implicitly available reference
variable me.
Description of example:
In the constructor, the instance attribute make is covered by the locally defined variable make. In order
to still be able to address the instance attribute, you need to use me.
The dummy method demonstrates how to call a class's own method. You can omit the prefix me->.
Other important use:
An object calls another object's method and passes its own address.

(C) SAP AG

BC401

7-40

Principles of Object-Oriented Programming: Unit


Summary

You are now able to:


Create classes
Create objects
Call methods
Explain how the garbage collector works

SAP AG 2002

(C) SAP AG

BC401

7-41

Exercises
Unit: Principles of Object-Oriented Programming
Topic:

Creating a Class

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


Create a local class

An airline needs to manage its airplanes.

Model solution: SAPBC401_AIRS_MAIN_A


SAPBC401_AIRS_A include program

1-1

Create the package ZBC401_## (where ##: is your group number) and save all the
repository objects you have created during the course in this package.

1-2

Create the main program ZBC401_##_MAIN_AIRPLANE and the include program


ZBC401_##_AIRPLANE the main program contains (##: group number).

1-3

Create the class lcl_airplane in the include program.


1-3-1 This class has two private instance attributes:
- name
- planetype.
The attribute for the airplane name should be of the type STRING. Define the
attribute for the plane type using the table field saplane-planetype.
1-3-2 The class has a private static attribute:
- n_o_airplanes.
This attribute should be type I.
1-3-3 The class has a public instance method set_attributes to set the private
instance attributes name and plane type. Enter two corresponding importing
parameters for the declaration of the method in the definition part. The
definition of these parameters should be analogous to the two attributes.

(C) SAP AG

BC401

7-42

Implement the method in the implementation part; set both attributes. Each time
the method is called, the static attribute n_o_airplanes should increase by one.
(This is actually not right but will be corrected later).
1-3-4 The class is to have another public instance method display_attributes to
display the instance attributes. Declare this method and, in the implementation
part, output the attributes using the WRITE statement (you can also display the
icon icon_ws_plane, in which case you must add TYPE-POOLS icon to
the program.
1-3-5 Declare and implement a public static method display_n_o_airplanes to
display the static attribute n_o_airplanes.
(In the remaining exercises in this course, you can always start with the program you
created in the previous exercise or copy the corresponding model solution and continue
working with this program.)

(C) SAP AG

BC401

7-43

Exercises
Unit: Principles of Object-Oriented
Programming
Topic:

Instantiating Objects

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


Instantiate objects

Model solution: SAPBC401_AIRS_MAIN_B


SAPBC401_AIRS_A include program

2-1 Create a reference to the class lcl_airplane.


2-2 Define an internal table for buffering objects of the class lcl_airplane. The type of the
internal table should therefore be REF TO lcl_airplane.
2-3 Create several objects of the class lcl_airplane and store them in the internal table.
2-4 Follow the program flow in the Debugger.

(In the remaining exercises in this course, you can always start with the program you
created in the previous exercise or copy the corresponding model solution and continue
working with this program.)

(C) SAP AG

BC401

7-44

Exercises
Unit: Principles of Object-Oriented
Programming
Topic:

Method Calls

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


Call instance methods and static methods

Model solution: SAPBC401_AIRS_MAIN_C


SAPBC401_AIRS_C include program

3-1 Call the static method display_n_o_airplanes (before instantiating an object in class
lcl_airplane).
3-2 Use the set_attributes method to set the attributes for all objects already created. Choose
an airplane name and airplane type and pass them as text literals. (For the plane type you
can use a type from the table SAPLANE, for example 747-400.)
3-3 Display the object attributes using the display_attributes method.
3-4 Call the static method display_n_o_airplanes a second time.
3-5 Add a functional static method get_n_o_airplanes to the class lcl_airplane. The method
must be public and have the re_count (type I) return parameter (no input parameters).
3-6 Test your functional method by calling it from the main program.

(C) SAP AG

BC401

7-45

Exercises
Unit: Principles of Object-Oriented
Programming
Topic:

Constructor

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


Create a constructor for a class
Create an object using the constructor
Model solution: SAPBC401_AIRS_MAIN_D
SAPBC401_AIRS_D include program

4-1 Create a constructor for the class lcl_airplane (in your include program
ZBC401_##_AIRPLANE) The simplest way of doing this is to copy the method
set_attributes, which you now no longer need.
4-1-1

The constructor must have two importing parameters that fill the instance
attributes name and planetype.

4-1-2

The static attribute n_o_airplanes should have an ascending sequence of one in


the constructor.

4-2 In the method set_attributes, comment out the line in which the static attribute
n_o_airplanes is increased by one (if you still want to use this method).
4-3 In the main program ZBC401_##_MAIN_AIRPLANE, extend the creation of the object
with the constructor interface.
Fill the constructors interface parameters with the same values you used when calling
the set_attributes method.
4-4 (Optional)
Comment out the method call set_attributes or delete the call.

(C) SAP AG

BC401

7-46

Exercises
Unit: Principles of Object-Oriented Programming
Topic: Calling a Private Method
At the conclusion of these exercises, you will be able to:
Call methods within a class

Model solution: SAPBC401_AIRS_MAIN_E


SAPBC401_AIRS_E include program

Create the private method get_technical_attributes for the class lcl_airplane (in your
include program ZBC401_##_AIRPLANE).
5-1 The airplane type is the import parameter. (Type saplane-planetype)
5-2 The export parameter is the weight WEIGHT and the tank capacity TANKCAP.
Refer to the types in the table SAPLANE.
5-3 The result, both export parameters are ascertained in a database access to the table
SAPLANE.
Therefore, both attributes are read, depending on the airplane type.
5-4 If the imported plane type does not exist in the table, set default values (weight
100000, tank capacity 10000).
5-5 Test your method get_technical_attributes:

(C) SAP AG

5-5-1

By calling it from the main program

5-5-2

By calling it within the display_attributes method

5-3-3

Which call was successful, and why?

BC401

7-47

Solutions
Unit: Principles of Object-Oriented
Programming
Topic:

Creating a Class

*&---------------------------------------------------------------------*
*& Report

SAPBC401_AIRS_MAIN_a

*&---------------------------------------------------------------------*
REPORT

sapbc401_airs_main_a.

TYPE-POOLS icon.
INCLUDE SAPBC401_airs_A.
*&-----------------------------------------------------------------*
*&

Include

SAPBC401_AIRS_A

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

CLASS lcl_airplane DEFINITION

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

TYPE string

im_planetype TYPE saplane-planetype,


display_attributes.
CLASS-METHODS: display_n_o_airplanes.
PRIVATE SECTION.
"---------------------------------DATA: name

TYPE string,

planetype TYPE saplane-planetype.


(C) SAP AG

BC401

7-48

CLASS-DATA: n_o_airplanes TYPE i.


ENDCLASS.
*------------------------------------------------------------------*
*

CLASS lcl_airplane IMPLEMENTATION

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

= im_name.

planetype

= im_planetype.

n_o_airplanes = n_o_airplanes + 1.
ENDMETHOD.
METHOD display_attributes.
WRITE: / icon_ws_plane as icon,
/ 'Name of airplane:'(001), AT pos_1 name,
/ 'Airplane type'(002), AT pos_1 planetype.
ENDMETHOD.
METHOD display_n_o_airplanes.
WRITE: /, / 'Total number of planes'(ca1),
AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
ENDMETHOD.
ENDCLASS.

(C) SAP AG

BC401

7-49

Solutions
Unit: Principles of Object-Oriented
Programming
Topic:

Instantiating Objects

*&---------------------------------------------------------------------*
*& Report

SAPBC401_AIRS_MAIN_b

*&---------------------------------------------------------------------*
*& create and insert planes into internal table

*&---------------------------------------------------------------------*
REPORT

sapbc401_airs_main_b.

TYPE-POOLS icon.
INCLUDE SAPBC401_airs_A.
DATA: r_plane TYPE REF TO lcl_airplane,
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION.
*##############################

CREATE OBJECT r_plane.


APPEND r_plane TO plane_list.
CREATE OBJECT r_plane.
APPEND r_plane TO plane_list.
CREATE OBJECT r_plane.
APPEND r_plane TO plane_list.

(C) SAP AG

BC401

7-50

Solutions
Unit: Principles of Object-Oriented
Programming
Topic:

Method Calls

*&---------------------------------------------------------------------*
*& Report

SAPBC401_AIRS_MAIN_C

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

call method set_Attributes to initialize objects

*&

and visualize content of objects via display_attributes

*&---------------------------------------------------------------------*
REPORT

sapbc401_airs_main_c.

TYPE-POOLS icon.
INCLUDE sapbc401_airs_c.
DATA: r_plane TYPE REF TO lcl_airplane,
plane_list TYPE TABLE OF REF TO lcl_airplane,
count type i.
START-OF-SELECTION.
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_plane.
APPEND r_plane TO plane_list.
r_plane->set_attributes( im_name = 'LH Berlin'
im_planetype = '747-400' ).
CREATE OBJECT r_plane.
APPEND r_plane TO plane_list.
r_plane->set_attributes( im_name = 'AA New York'
im_planetype = '737-100' ).

(C) SAP AG

BC401

7-51

LOOP AT plane_list INTO r_plane.


r_plane->display_attributes( ).
ENDLOOP.
lcl_airplane=>display_n_o_airplanes( ).
* calling the functional method get_n_o_airplanes
* long syntax for functional call:
* lcl_airplane=>get_n_o_airplanes( receiving re_count = count ).
* short syntax for functional call:
count = lcl_airplane=>get_n_o_airplanes( ).
write: / 'Number of airplanes : ', count.

(C) SAP AG

BC401

7-52

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

Include

SAPBC401_AIRS_C

*&

Develops functional static method get_n_o_airplanes

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

CLASS lcl_airplane DEFINITION

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

TYPE string

im_planetype TYPE saplane-planetype,


display_attributes.
CLASS-METHODS: display_n_o_airplanes,
get_n_o_airplanes returning VALUE(re_count) type I.
PRIVATE SECTION.
"---------------------------------DATA: name

TYPE string,

planetype TYPE saplane-planetype.


CLASS-DATA: n_o_airplanes TYPE i.
ENDCLASS.
*------------------------------------------------------------------*
*

CLASS lcl_airplane IMPLEMENTATION

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

= im_name.

planetype

= im_planetype.

(C) SAP AG

BC401

7-53

n_o_airplanes = n_o_airplanes + 1.
ENDMETHOD.
METHOD display_attributes.
WRITE: / icon_ws_plane as icon,
/ 'Name of airplane:'(001), AT pos_1 name,
/ 'Airplane type'(002), AT pos_1 planetype.
ENDMETHOD.
METHOD display_n_o_airplanes.
WRITE: /, / 'Total number of planes'(ca1),
AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
ENDMETHOD.
method get_n_o_airplanes.
re_count = n_o_airplanes.
endmethod.
ENDCLASS.

(C) SAP AG

BC401

7-54

Solutions
Unit: Principles of Object-Oriented
Programming
Topic:

Constructor

*&---------------------------------------------------------------------*
*& Report

SAPBC401_AIRS_MAIN_d

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

call constructor of class lcl_airplane

*&---------------------------------------------------------------------*
REPORT

sapbc401_airs_main_d.

TYPE-POOLS icon.
INCLUDE sapbc401_airs_d.
DATA: r_plane TYPE REF TO lcl_airplane,
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION.
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_plane exporting im_name = 'LH Berlin'
im_planetype = '747-400'.
APPEND r_plane TO plane_list.
CREATE OBJECT r_plane exporting im_name = 'AA New York'
im_planetype = '737-100'.
LOOP AT plane_list INTO r_plane.
r_plane->display_attributes( ).
ENDLOOP.
lcl_airplane=>display_n_o_airplanes( ).

(C) SAP AG

BC401

7-55

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

Include

SAPBC401_AIRS_d

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

CLASS lcl_airplane DEFINITION

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

TYPE string

im_planetype TYPE saplane-planetype,


display_attributes.
CLASS-METHODS: display_n_o_airplanes.
PRIVATE SECTION.
"---------------------------------DATA: name

TYPE string,

planetype TYPE saplane-planetype.


CLASS-DATA: n_o_airplanes TYPE i.
ENDCLASS.
*------------------------------------------------------------------*
*

CLASS lcl_airplane IMPLEMENTATION

*------------------------------------------------------------------*
CLASS lcl_airplane IMPLEMENTATION.
METHOD constructor.
name
= im_name.
planetype
= im_planetype.
n_o_airplanes = n_o_airplanes + 1.
ENDMETHOD.
METHOD display_attributes.
(C) SAP AG

BC401

7-56

WRITE: / icon_ws_plane as icon,


/ 'Name of airplane'(001), AT pos_1 name,
/ 'Airplane type: '(002), AT pos_1 planetype.
ENDMETHOD.
METHOD display_n_o_airplanes.
WRITE: /, / 'Number of airplanes: '(ca1),
AT pos_1 n_o_airplanes LEFT-JUSTIFIED, /.
ENDMETHOD.
ENDCLASS.

(C) SAP AG

BC401

7-57

Solutions
Unit: Principles of Object-Oriented
Programming
Topic:

Calling a Private Method

*&---------------------------------------------------------------------*
*& Report

SAPBC401_AIRS_MAIN_e

*&

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

inside display_attributes a private method is called to get

*&

further details on technical aspects of the planetype

*&---------------------------------------------------------------------*
REPORT

sapbc401_airs_main_e.

TYPE-POOLS icon.
INCLUDE sapbc401_airs_e.
DATA: r_plane TYPE REF TO lcl_airplane,
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION.
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_plane exporting im_name = 'LH Berlin'
im_planetype = '747-400'.
APPEND r_plane TO plane_list.
r_plane->display_attributes( ).
CREATE OBJECT r_plane exporting im_name = 'AA New York'
im_planetype = '727-200'.
r_plane->display_attributes( ).
lcl_airplane=>display_n_o_airplanes( ).

(C) SAP AG

BC401

7-58

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

Include

SAPBC401_AIRS_e

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

CLASS lcl_airplane DEFINITION

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

TYPE string

im_planetype TYPE saplane-planetype,


display_attributes.
CLASS-METHODS: display_n_o_airplanes.
PRIVATE SECTION.
"---------------------------------METHODS: get_technical_attributes
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.

(C) SAP AG

"lcl_airplane DEFINITION

BC401

7-59

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

CLASS lcl_airplane IMPLEMENTATION

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

= im_name.

planetype

= im_planetype.

n_o_airplanes = n_o_airplanes + 1.
ENDMETHOD.

"constructor

METHOD display_attributes.
data: weight type saplane-weight,
cap type saplane-tankcap.
WRITE: / icon_ws_plane AS ICON,
/ 'Name of airplane'(001), AT pos_1 name,
/ 'Airplane type: '(002), AT pos_1 planetype.
get_technical_attributes( exporting im_type = planetype
importing ex_weight = weight
ex_tankcap = cap ).
write: / 'wheight: '(003), weight,
'tankcap: '(004), 60 cap.
ENDMETHOD.

"display_attributes

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

"display_n_o_airplanes

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

"get_technical_attributes
BC401

7-60

ENDCLASS.

(C) SAP AG

"lcl_airplane IMPLEMENTATION

BC401

7-61

Inheritance

Contents:
Generalization / specialization of classes

SAP AG 2002

(C) SAP AG

BC401

8-1

Inheritance: Unit Objectives

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


Define an inheritance relationship between
classes
Redefine methods

SAP AG 2002

(C) SAP AG

BC401

8-2

Inheritance: Integration in Course Content

e
Inheritanc gramming

and
Data Types
ts in
Data Objec
Detail

Pro
Oriented
of ObjectPrinciples
n
ig
and Des
Analysis
amming
P
ted rogr
ect-Orien
bj
O
to
n
Introductio
al
Using Intern
Tables

rams
Calling Prog
Data
and Passing

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

8-3

Inheritance: UML Example


lcl_vehicle

"is a"
relationship

lcl_car

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

lcl_truck

lcl_bus

- car_type
- max_seats
- accelertion

- max_cargo
- n_o_tanks
- n_o_wheels

- max_passengers
- lavatory
- television

+...
+get_type

+...
+get_cargo

+...
+get_passengers

SAP AG 2002

Inheritance is a relationship, in which one class (the subclass) inherits all the main characteristics of
another class (the superclass). The subclass can also add new components (attributes, methods, and so
on) and replace inherited methods with its own implementations.
Inheritance is an implementation relationship that emphasizes similarities between classes. In the
example above, the similarities between the car, bus, and truck classes are extracted to the vehicle
superclass. This means that common components are only defined/implemented in the superclass and are
automatically present in the subclasses.
The inheritance relationship is often described as an "is a" relationship: A truck is a vehicle.

(C) SAP AG

BC401

8-4

lcl_super2

No
multiple inheritance

lcl_sub1

lcl_sub2

lcl_sub3

Specialization

lcl_super1

Generalization

Multiple Inheritance?

SAP AG 2002

Inheritance should be used to implement generalization and specialization relationships. A superclass is


a generalization of its subclasses. The subclass in turn is a specialization of its superclasses.
The situation in which a class, for example lcl_sub2, inherits from two classes (lcl_super1 and
lcl_super2) simultaneously, is known as multiple inheritance. However, this is not implemented in
ABAP Objects. ABAP Objects only has single inheritance.
You can, however, simulate multiple inheritance in ABAP Objects using interfaces (see the section on
interfaces).
Single inheritance does not mean that the inheritance tree only has one level. On the contrary, the direct
superclass of one class can in turn be the subclass of a further superclass. In other words: The inheritance
tree can have any number of levels, so that a class can inherit from several superclasses, as long as it
only has one direct superclass.
Inheritance is a "one-sided relationship": Subclasses know their direct superclasses, but (super)classes do
not know their subclasses.

(C) SAP AG

BC401

8-5

Relationships Between Superclasses and Subclasses

Common components only exist once in the


superclass

New components in the superclass are


automatically available in subclasses

Amount of new coding is reduced


("programming by difference")

lcl_super

Subclasses are extremely dependent on


superclasses

"White Box Reuse":


Subclass must possess detailed knowledge of
the implementation of the superclass

lcl_sub
New
components
Inherited
components

SAP AG 2002

If inheritance is used properly, it provides a significantly better structure, as common components only
need to be stored once centrally (in the superclass) and are then automatically available to subclasses.
Subclasses also benefit from modifications (however, they can also be invalidated as a result).
Inheritance provides very strong links between the superclass and the subclass. The subclass must
possess detailed knowledge of the implementation of the superclass, particularly for redefinition, but
also in order to use inherited components. Even if the superclass does not technically know its
subclasses, the subclass often makes additional requirements of the superclass, for example, because a
subclass needs certain protected components or because implementation details in the superclass need to
be changed in the subclass in order to redefine methods. The basic reason is that the developer of a
(super)class cannot normally predict all the requirements that subclasses will later need to make of the
superclass.

(C) SAP AG

BC401

8-6

Inheritance: Syntax

CLASS lcl_vehicle DEFINITION.


PUBLIC SECTION.
METHODS: estimate_fuel
IMPORTING im_distance
TYPE s_distance
RETURNING VALUE(re_fuel) TYPE ty_fuel.
PRIVATE SECTION.
DATA: make TYPE string,
...

ENDCLASS.
CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.
PUBLIC SECTION.
METHODS: get_cargo RETURNING VALUE(re_cargo) TYPE ty_cargo.
PRIVATE SECTION.
DATA: max_cargo TYPE ty_cargo.
ENDCLASS.
SAP AG 2002

Normally the only other entry required for subclasses is what has changed in relation to the direct
superclass. Only additions are permitted in ABAP Objects, that is, in a subclass you can "never take
something away from a superclass". All components from the superclass are automatically present in the
subclass.
The attributes of the superclass lcl_vehicle exist in the subclass lcl_truck; the method
estimate_fuel is also available in the subclass.
The subclass defines a method get_cargo. It is not visible in the superclass.

(C) SAP AG

BC401

8-7

Redefining Methods
CLASS lcl_vehicle DEFINITION.
PUBLIC SECTION.
METHODS estimate_fuel
IMPORTING im_distance
TYPE ty_distance
RETURNING VALUE(re_fuel) TYPE ty_fuel.
ENDCLASS.
CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.
PUBLIC SECTION.
METHODS estimate_fuel REDEFINITION.
...
ENDCLASS.
CLASS lcl_truck IMPLEMENTATION.
METHOD estimate_fuel.
...
super->estimate_fuel(...)
ENDMETHOD.
ENDCLASS.

Always points to the


superclass component

Cannot change
the interface

New
implementation of
method

SAP AG 2002

The REDEFINITION statement for the inherited method must be in the same SECTION as the
definition of the original method. (It can therefore not be in the PRIVATE SECTION, since a class's
private methods are not visible and therefore cannot be redefined in subclasses).
If you redefine a method, you do not need to enter its interface again in the subclass, but only the name
of the method. The reason for this is that ABAP Objects does not support overloading.
In the case of redefined methods, changing the interface (overloading) is not permitted; exception:
Overloading is possible with the constructor.
Within the redefined method, you can access components of the direct superclass using the SUPER
reference.
To implement a redefined method in a subclass, you often need to call the method of the same name in
the immediate superclass. In ABAP Objects you can call the method from the superclass using the
pseudo-reference super:
The pseudo-reference super can only be used in redefined methods.

(C) SAP AG

BC401

8-8

Inheritance and Redefining the Constructor

CLASS lcl_vehicle DEFINITION.


PUBLIC SECTION.
METHODS: constructor IMPORTING
im_make TYPE string.
ENDCLASS.

CLASS lcl_vehicle IMPLEMENTATION.


METHOD CONSTRUCTOR.
make = im_make.
ENDMETHOD.
ENDCLASS.

CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle.


PUBLIC SECTION.
METHODS: constructor IMPORTING im_make TYPE string
im_cargo TYPE ty_cargo.
PRIVATE SECTION.
DATA: max_cargo TYPE ty_cargo.
ENDCLASS.
Can change the
interface
CLASS lcl_truck IMPLEMENTATION.
METHOD constructor.
CALL METHOD super->constructor( im_make = im_make ).
max_cargo = im_cargo.
ENDMETHOD.
Call constructor of immediate
ENDCLASS.
superclass
SAP AG 2002

The constructor of the superclass must be called within the constructor of the subclass. The reason for
this is the special function of the constructor: To ensure that objects are initialized correctly. Only the
class itself, however, can initialize its own (private) components correctly; this task cannot be carried out
by the subclass. Therefore it is essential that all (instance) constructors are called in an inheritance
hierarchy (in the correct sequence).
For static constructors, unlike instance constructors, the static constructor in the superclass is called
automatically, that is the runtime system automatically ensures that the static constructors of all its
superclasses have already been executed before the static constructor in a particular class is executed.

(C) SAP AG

BC401

8-9

Rules for Calling the Constructor

lcl_1

DATA: r_2 TYPE REF TO lcl_2,


r_3 TYPE REF TO lcl_3.
CREATE OBJECT r_2 EXPORTING im_a1 = 100.

a1
constructor
(im_a1:i)

CREATE OBJECT r_3 EXPORTING im_a1 = 100


im_a2 = 1000.

Case 1:
Class of instance to be created has constructor
Fill its parameters
Case 2:
Class of instance to be created has no constructor
Search for the next superclass with a constructor
in the inheritance tree
Fill its parameters

lcl_2

lcl_3
a2
constructor
(im_a1, im_a2)

SAP AG 2002

The model described for instance constructors must also be taken into account for CREATE OBJECT.
There are two main methods of creating an instance of a class using CREATE OBJECT:
1. The class has a defined (and implemented) instance constructor
In this case, when you are using CREATE OBJECT, the parameters have to be filled according to the
constructor interface, that is, optional parameters may, and non-optional parameters must be filled
with actual parameters. If the constructor does not have any (formal) parameters, no parameters may
or can be filled.
2. The instance constructor for that class has not been defined
In this case, you must search the inheritance hierarchy for the next highest superclass in which the
instance constructor has been defined and implemented. Then, when you are using CREATE
OBJECT, the parameters of that class must be filled (similarly to the first method above).
If there is no superclass with a defined instance constructor, then no parameters may or can be filled.
If no instance constructor has been defined for a class, then a default constructor, which is implicitly
always present is used. This default constructor calls the constructor from the immediate superclass.

(C) SAP AG

BC401

8-10

Inheritance and Visibility


CLASS lcl_vehicle DEFINITION.

Public components

Visible to all

Direct access

...

PROTECTED SECTION.
DATA tank TYPE REF TO lcl_tank.

Protected components

PUBLIC SECTION.

PRIVATE SECTION.
DATA make TYPE string.

Only visible within the class


and its subclasses

ENDCLASS.

Private components

Only visible within the class

No access from outside the


class,
not even from the subclass

lcl_vehicle
- make
- modell
# tank
...
+constructor
+display_attributes
+get_count

+ public
# protected
- private

SAP AG 2002

Inheritance provides an extension of the visibility concept: There are protected components. The
visibility of these components lies between that of the public components (visible to all users, all
subclasses, and the class itself), and private (visible only to the class itself). Protected components are
visible to and can be used by all subclasses and the class itself.
Subclasses cannot access the private components (particularly attributes) of the superclass. Private
components are genuinely private. This is particularly important if a (super)class needs to make local
enhancements to handle errors: It can use private components to do this without knowing or invalidating
subclasses.
In ABAP Objects, you must keep to the section sequence PUBLIC, PROTECTED, PRIVATE.

(C) SAP AG

BC401

8-11

Visibility of Protected Components

Can be addressed
"from outside" for
all clients

(5) lcl_bus
Public

Private

Inherited
get_make
set_make
get_count
display_attributes
estimate_fuel

Protected

Inherited

tank
Can only be
addressed within
the class

SAP AG 2002

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

(C) SAP AG

BC401

8-12

Rules for Redefining Methods

Inherited methods can be redefined in subclasses

Redefined methods must be re-implemented in subclasses

The signature of redefined methods cannot be changed

Static methods cannot be redefined

In inheritance, static components are "shared":


A class shares its non-private static attributes with all its subclasses

lcl_vehicles
estimate_fuel

lcl_car

lcl_truck

estimate_fuel

estimate_fuel

lcl_bus
estimate_fuel

The method is implemented in different ways


SAP AG 2002

In ABAP Objects, you can not only add new components, but also provide inherited methods with new
implementations. This is known as redefinition. You can only redefine (public and protected) instance
methods, other components (static methods, attributes and so on) cannot be redefined. Changes to
method parameters (signature changes) are not possible.
In UML, the redefinition of a method is represented by listing the method again in the subclass. Methods
(and all other components) that are inherited but not redefined are not listed in the subclass, as their
existence there is clear from the specialization relationship.
You should not confuse redefinition with "overloading". The latter describes the ability of a class to have
methods with the same name but a different signature. This is not available in ABAP Objects.
There is only one static event per roll area. In this way, a class that defines a public or protected static
attribute shares this attribute with all its subclasses. The significant point here is that subclasses do not
each receive their own copy of the static attribute.

(C) SAP AG

BC401

8-13

Redefining Methods: Example

lcl_bus

lcl_truck

- max_passengers
...

- max_cargo
...

+ constructor
+ estimate_fuel

+ constructor
+ estimate_fuel

METHOD estimate_fuel.
DATA: total_weight ...
* just an example!
total_weight = max_passengers *
average_weight + weight.
re_fuel = total_weight *
im_distance * factor.
ENDMETHOD.

METHOD estimate_fuel.
DATA: total_weight ...
* just an example!
total_weight = max_cargo +
weight.
re_fuel = total_weight *
im_distance * factor.
ENDMETHOD.

SAP AG 2002

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

(C) SAP AG

BC401

8-14

Inheritance: Unit Summary

You are now able to:


Define an inheritance relationship between
classes
Redefine methods

SAP AG 2002

(C) SAP AG

BC401

8-15

Inheritance Exercises
Unit: Inheritance
Topic: Creating Class Hierarchies
At the conclusion of these exercises, you will be able to:
Define subclasses
Redefine superclass methods in subclasses
Model solution: SAPBC401_INHS_MAIN_A
SAPBC401_INHS_A include program
Your program: ZBC401_##_MAIN_AIRPLANE
ZBC401_##_AIRPLANE include program

1-1

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

Create the subclass lcl_passenger_plane for the class lcl_airplane. Also, create this
subclass in your include program.
1-2-1 The class is to have a private instance attribute max_seats with the same
type as table field sflight-seatsmax.
1-2-2 A public constructor is to be defined and implemented in the class. This
constructor provides all instance attributes in the class with values.
1-2-3 Redefine the method display_attributes of the class lcl_airplane, so that,
using the redefined method, the WRITE statement displays all instance
attributes.

1-3

Create the subclass lcl_cargo_plane for the class lcl_airplane. Also, create this
subclass in your include program.
1-3-1 The class is to have a private instance attribute max_cargo with the same
type as the table field scplane-cargomax.
1-3-2 A public constructor is to be defined and implemented in the class. This
constructor provides all instance attributes in the class with values.
1-3-3 Redefine the method display_attributes of the class lcl_airplane, so that,
using the redefined method, the WRITE statement displays all instance
attributes.

(C) SAP AG

BC401

8-16

1-4

Switch to your main program.


1-4-1 Use the DATA statement to create a reference for each subclass
(lcl_passenger_plane, lcl_cargo_plane).
1-4-2 Call the static method display_n_o_airplanes (before instantiating any
objects).
1-4-3 Use the two references to create one instance each of the subclasses
lcl_passenger_plane and lcl_cargo_plane. Decide for yourself how to fill
the attributes.
1-4-4 Call the display_attributes method for both instances.
1-4-5 Call the static method display_n_o_airplanes a second time.

1-5

Follow the program flow in the Debugger, paying special attention to the call of
display_attributes.

1-6

Can the method get_technical_attributes be called directly from the redefined


method display_atributes of the subclass?

1-7

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

(C) SAP AG

BC401

8-17

Inheritance Solutions
Unit: Inheritance
Topic:

Creating Class Hierarchies

*&---------------------------------------------------------------------*
*& Report

SAPBC401_INHS_MAIN_a

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

the classes lcl_passenger_plane and lcl_cargo_plane are

*&

instantiated. Inheritance is shown

*&---------------------------------------------------------------------*
REPORT

sapbc401_inhs_main_a.

INCLUDE <icon>.
INCLUDE sapbc401_inhs_a.
DATA: r_plane TYPE REF TO lcl_airplane,
r_cargo type ref to lcl_cargo_plane,
r_passenger type ref to lcl_passenger_plane,
plane_list TYPE TABLE OF REF TO lcl_airplane.
START-OF-SELECTION.
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_passenger EXPORTING
im_name = 'LH BERLIN'
im_planetype = '747-400'
im_seats = 345.
CREATE OBJECT r_cargo EXPORTING
im_name = 'US HErcules'
im_planetype = '747-500'
im_cargo = 533.

(C) SAP AG

BC401

8-18

r_cargo->display_attributes( ).
r_passenger->display_attributes( ).
lcl_airplane=>display_n_o_airplanes( ).

(C) SAP AG

BC401

8-19

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

Include

SAPBC401_INHS_a

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

CLASS lcl_airplane DEFINITION

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

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

CLASS lcl_cargo_plane DEFINITION

*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
"---------------------METHODS: constructor IMPORTING im_name TYPE string
im_planetype TYPE saplane-planetype
im_cargo TYPE scplane-cargomax.
METHODS: display_attributes REDEFINITION.
PRIVATE SECTION.
"---------------------DATA: max_cargo TYPE scplane-cargomax.
ENDCLASS.

"lcl_cargo_plane DEFINITION

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

CLASS lcl_cargo_plane IMPLEMENTATION

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

METHOD constructor.
CALL METHOD super->constructor( im_name
= im_name
im_planetype = im_planetype ).
(C) SAP AG

BC401

8-20

max_cargo = im_cargo.
ENDMETHOD.

"constructor

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

(C) SAP AG

"display_attributes
"lcl_cargo_plane IMPLEMENTATION

BC401

8-21

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

CLASS lcl_passenger_plane DEFINITION

*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..
PUBLIC SECTION.
METHODS: constructor IMPORTING im_name TYPE string
im_planetype TYPE saplane-planetype
im_seats TYPE sflight-seatsmax.
METHODS: display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: max_seats TYPE sflight-seatsmax.
ENDCLASS.

"lcl_passenger_plane DEFINITION

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

CLASS lcl_passenger_plane IMPLEMENTATION

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

METHOD constructor.
CALL METHOD super->constructor( im_name

= im_name

im_planetype = im_planetype ).
max_seats = im_seats.
ENDMETHOD.

"constructor

METHOD display_attributes.
super->display_attributes( ).
WRITE: / 'Max Seats = ', max_seats.
ULINE.
ENDMETHOD.
ENDCLASS.
(C) SAP AG

"display_attributes
"lcl_passenger_plane IMPLEMENTATION
BC401

8-22

(C) SAP AG

BC401

8-23

Casting

Contents:
Cast
Polymorphism

SAP AG 2002

(C) SAP AG

BC401

9-1

Casting: Unit Objectives

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


Use casts
Develop generic programs using polymorphism
with inheritance

SAP AG 2002

(C) SAP AG

BC401

9-2

Casting: Integration in Course Content

Casting

and
Data Types
ts in
Data Objec
Detail

e
Inheritanc
ming
ed Program
nt
Object-Orie
of
es
pl
ci
Prin
n
and Desig
Analysis
ing
Programm
d
te
en
Object-Ori
to
n
tio
Introduc
al
Using Intern
Tables

rams
Calling Prog
Data
and Passing

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

9-3

Casting (1)

Narrowing
Narrowing cast
cast
Widening
Widening cast
cast
Inheritance
Inheritance and
and polymorphism
polymorphism

SAP AG 2002

(C) SAP AG

BC401

9-4

Principle of Narrowing Cast

DATA: r_vehicle TYPE REF TO lcl_vehicle,


r_truck
TYPE REF TO lcl_truck.

CREATE OBJECT r_truck.

(5) lcl_truck
Public

Geerbt

r_truck

get_make
get_count

r_vehicle

Redefiniert

display_attributes
set_attributes
estimate_fuel

* Narrowing Cast
r_vehicle = r_truck

get_cargo
...

r_vehicle

SAP AG 2002

After the narrowing cast, you can use the r_vehicle reference to access the components of the
truck instance that were inherited from lcl_vehicle - obviously, in some cases with the
limitations entailed by their visibility. You can no longer access the truck-specific part of the instance
(get_cargo in the above example) using the r_vehicle reference.

(C) SAP AG

BC401

9-5

Compatibility and Narrowing Cast

Instances from subclasses can be used in any context, in which the


instances of the superclass appear

The components inherited from the superclass can be addressed

Generic access by the client is possible

DATA: r_vehicle
r_truck
level

TYPE REF TO lcl_vehicle,


TYPE REF TO lcl_truck,
TYPE
ty_level.

* generic access to subclass services


level = r_truck->estimate_fuel( 1000 ).
* Narrowing Cast
r_vehicle = r_truck.
* Use of the subclass instance in the superclass context
level = r_vehicle->estimate_fuel( 1000 ).

SAP AG 2002

One of the significant principles of inheritance is that an instance from a subclass can be used in any
context, in which an instance from the superclass appears. This is possible because the subclass has
inherited all components from the superclass and therefore has the same interface as the superclass. The
user can therefore address the subclass instance in the same way as the superclass instance.
Variables that point to a superclass instance can also refer to subclass instances at runtime.
The assignment of a subclass instance to a reference variable of the type "reference to superclass" is
described as a narrowing cast, because you are switching from a more detailed view to a one with less
detail.
The description "up-cast" is also used.
What is a narrowing cast used for? A user who is not interested in the finer points of cars, trucks, and
busses (but only, for example, in the fuel consumption and tank gauge) does not need to know about
them. This user only wants and needs to work with (references to) the lcl_vehicle class. However,
in order to allow the user to work with cars, busses, or trucks, you generally need a narrowing cast.

(C) SAP AG

BC401

9-6

A possible client (car rental company for example) wants to access the list of vehicles with identicallynamed services. The client wishes to, for example, calculate the required amount of fuel. The client is
not concerned with the details of how the car, bus, or truck do this.

(C) SAP AG

BC401

9-7

Objects from different classes (lcl_bus, lcl_truck, and lcl_car in the above example ) can be
stored in an internal table consisting of references to the superclass (lcl_vehicle in the above
example),and then processed in a uniform manner using the same access technique.
A client, the car rental company in this example, can then generically access the identically-named
service of the different classes. (This will be discussed in more detail.)

(C) SAP AG

BC401

9-8

When objects from different classes react differently to the same method call, this is known as
polymorphism. To do this, the classes implement the same method in different ways. This can be done
using inheritance, by redefining a method from the superclass in subclasses and implementing it
differently. (Interfaces will be discussed later; they too can enable polymorphic behavior.)
When an instance receives a message to execute a particular method, then that method is executed if it
has been implemented by the class the instance belongs to. If the class has not implemented that method,
but only inherited and not redefined it, then a search up through the inheritance hierarchy is carried out
until an implementation of that method is found.
The dynamic type, not the static type of the reference variable is used to search for the implementation
of a method (will be discussed later). r_vehicle->estimate_fuel above therefore uses the class
of the instance that r_vehicle actually refers to to search for the implementation of
estimate_fuel. The static type for r_vehicle, which is always REF TO lcl_vehicle is not
used.
Polymorphism is one of the main strengths of inheritance: The user can work in the same way with
different classes, regardless of their implementation. The search for the right implementation of a
method is carried out by the runtime system, not the user.

(C) SAP AG

BC401

9-9

Which coding is actually executed when estimate_fuel is called depends on the dynamic type of
the reference variable r_vehicle, that is it depends on which object from which (sub)class
r_vehicle refers to.
You can use polymorphism to write programs that are generic to a high degree and that do not even need
to be changed if use cases are added. In the simple example above, this means that, should a further
subclass be added, for example for motorbikes, the above coding would not need to be changed.
A redefined method will be created in the server class lcl_motorbike.

(C) SAP AG

BC401

9-10

Static and Dynamic Types of References

The static type of a reference variable


Is defined using TYPE REF TO

DATA: r_vehicle
TYPE REF TO lcl_vehicle.

Remains constant throughout the program flow


Defines which attributes and methods can be addressed

The dynamic type of a reference variable


Is defined by assignment
Can change during the program run

(5) lcl_truck

Defines which code is to be executed for


redefined methods

Inherited /
redefined
Estimate_
fuel
Estimate_fuel

(2) lcl_bus
Inherited /
redefined
r_vehicle

Estimate_
fuel
Estimate_fuel

SAP AG 2002

A reference variable always has two types, static and dynamic:


The static type of a reference variable is determined by variable definition using TYPE REF TO. It
cannot and does not change. It specifies which attributes and methods can be addressed
The dynamic type of a reference variable is the type of the instance currently being referred to, it is
therefore determined by assignment and can change during the program run. It defines what code is to
be executed for redefined methods.
In the example, the static type of the r_vehicle variable is always REF TO lcl_vehicle, but its
dynamic type after the cast is REF TO lcl_bus or REF TO lcl_truck.
In the Debugger, the reference me can be used to determine the dynamic type.

(C) SAP AG

BC401

9-11

Comparison to Procedural Programming

In object-oriented programming, you do not need to change the coding if


you add use cases

In a procedural program, you would have to adjust CASE constructions,


for example:

* Procedural realisation of the example without polymorphism


DATA: vehicle_list
TYPE TABLE OF vehicle_list_type,
vehicle
TYPE vehicle_list_type, ...
...
vehicle_list
LOOP AT vehicle_list INTO vehicle.
name category ...
CASE vehicle-category.
WHEN 'TRUCK'.
truck1
PERFORM estimate_fuel_truck USING ...
bus1
CHANGING fuel.
bus2
WHEN 'BUS'.
truck2
PERFORM estimate_fuel_bus USING ...
CHANGING fuel.
truck3
ENDCASE.
ADD fuel TO needed_fuel.
ENDLOOP.
SAP AG 2002

Using polymorphism makes generic programming easier. Instead of implementing a CASE or IF


statement, you can have one access or call, which improves readability and does not need to be changed
if you extend the program by adding further subclasses.

(C) SAP AG

BC401

9-12

Casting (2)

Narrowing
Narrowing cast
cast
Widening
Widening cast
cast
Inheritance
Inheritance and
and polymorphism
polymorphism

SAP AG 2002

(C) SAP AG

BC401

9-13

The client, the car rental company in the above example, wants to execute a function for specific
vehicles form the list (vehicle_list). For example, the client wants to ascertain the truck with the
largest cargo capacity.
However, not all vehicles are in the trucks list, it also includes references to cars and busses.

(C) SAP AG

BC401

9-14

The type of case described above is known as a widening cast (or "down cast") because it changes from
a less detailed view to one with more detail. The target reference (r_truck in the above example) must
correspond to the object reference (r_vehicle in the above example), that is the instance must have
the details implied by the reference.
The widening cast logically represents the opposite of the narrowing cast. The widening cast cannot be
checked statically, only at runtime. The Cast Operator ?= (or the equivalent MOVE ... ?TO )
must be used to make this visible.
With this kind of cast, a check is carried out at runtime to ensure that the current content of the source
variable corresponds to the type requirements of the target variables. In this example, it checks that the
dynamic type of the source reference r_vehicle is compatible with the static type of the target
reference r_truck. If it is, the assignment is carried out. Otherwise, an exception that can be handled is
raised, and the original value of the target variable remains the same. This exception of the error class
CX_SY_MOVE_CAST_ERROR can be caught using TRY-ENDTRY and the CATCH statement. (This
will be discussed in more detail later.)
Another way of preventing the runtime error would be to use RTTI (Runtime Type Identification). This
is a class library for ascertaining type attributes at runtime.

(C) SAP AG

BC401

9-15

Casting (3)

Narrowing
Narrowing cast
cast
Widening
Widening cast
cast
Inheritance
Inheritance and
and polymorphism
polymorphism

SAP AG 2002

(C) SAP AG

BC401

9-16

Semantics and Use with Inheritance

Rules:

Inherited components must behave in subclasses


exactly as they do in superclasses for all users

When you redefine a method its semantics must remain


the same; you cannot change the signature

Using inheritance:
Allows you to enhance classes using
generalization/specialization and hence achieve
better software structure
Provides possibility of polymorphic behavior,
"generic programming"; CASE constructions no
longer needed

Must not be used solely for "code inheritance"

SAP AG 2002

A subclass instance can be used in any context in which a superclass instance also appears. Moreover:
The user does not and is not intended to know whether they are dealing with a subclass or a superclass
instance. The user works only with references to the superclass and must rely on the inherited
components behaving in the subclass instances exactly as they do in the superclass instances, otherwise
the program will not work.
On the other hand, this ensures useful restrictions on the implementation of the subclasses: Inherited
components must keep their inherited semantics. You cannot use inherited attributes or events in any
way other than intended in the superclass, and you cannot change method semantics by redefinition.
You must avoid "code inheritance": It is not correct for one class to inherit from another simply because
part of the functionality required is already implemented there.

(C) SAP AG

BC401

9-17

Incorrect Use of Inheritance

Rules:

Inheritance is often used incorrectly:

To simply reuse code

Instead of additional attributes/aggregation/role


concepts
de

car

car_red

si

gn

car_blue

The use of inheritance does not always correspond


to expectations in the real world
de

change_width
Superclass
Rectangular

si

gn

Subclass
square
change_height

SAP AG 2002

Using inheritance instead of attributes, or a misunderstanding of inheritance as an is-one relationship


often leads to the following kind of design: the superclass car has the subclasses red car, green car, and
so on. These subclasses all have an identical structure and identical behavior.
Because an instance cannot change its class, in circumstances like the following, you should not use
inheritance directly, but use a so-called role design pattern instead:
The class employee has the subclasses full-time employee and part-time employee. What happens when a
part-time employee becomes a full-time employee? A new full-time employee object would have to be
instantiated and all the information copied from the part-time employee object. However, users who still
have a reference to the part-time employee instance would then be working with a part-time employee
object that logically does not exist anymore.
The use of inheritance does not always correspond to expectations in the real world: For example, if the
class square inherits from the class rectangle, the latter will have two separate methods for changing
length or width, although the sides of the square actually need to be changed by the same measurement.

(C) SAP AG

BC401

9-18

Casting: Unit Summary

You are now able to:


Use casts
Develop generic programs using polymorphism
with inheritance

SAP AG 2002

(C) SAP AG

BC401

9-19

Casting Exercises
Unit: Casting
Topic: Polymorphism
At the conclusion of these exercises, you will be able to:
Describe polymorphism and inheritance
Use generic programming for inheritance relationships and implement
polymorphic method calls
Model solution: SAPBC401_CASS_MAIN_A
SAPBC401_INHS_A include program

1-1

Extend your existing program ZBC401_##_MAIN_AIRPLANE or start with the


model solution from the last chapters exercises.

1-2

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

1-3

Try to insert the planes (passenger and cargo) into this internal table and execute the
display_attributes method for every plane in a LOOP.
Read the internal table in the LOOP using the auxiliary reference variable r_airplane
(type REF TO lcl_airplane).
1-3-1 Was this successful?
1-3-2 Check the internal table and the execution of the display_attributes method in
the Debugger
1-3-3 Which source code is executed when the display_attributes method is called,
the original method from the superclass or the relevant redefined methods from
the subclasses? What would happen if one of these methods had not been
redefined in the subclass?

(C) SAP AG

BC401

9-20

Model solution: SAPBC401_CASS_MAIN_B


SAPBC401_CASS_B include program
Template: SAPBC401_CAST_B

2-1

Copy the definition of the class lcl_carrier from the template SAPBC401_CAST_B to
your own include program ZBC401_##_AIRPLANE (hence adding this class to your
include program).

2-2

Add the following public instance methods to the class lcl_carrier:


2-2-1 The first method is add_airplane, which adds planes to the list of planes
airplane_list already defined in the class. The transfer parameter is a reference
to the class lcl_airplane.
Have a close look at the definition of the internal table airplane_list.
2-2-2 The second method is display_airplanes, which displays the planes from the list
airplane_list. The display_attributes method from class lcl_airplane should be
called at this point.
2-2-3 The third method is display_attributes, which displays the airline attributes.
This includes the airline name and the list of planes (you can use icon_flight as
an icon before the name).

2-3

Go back to your main program.


2-3-1 At the DATA statement, create a reference to the class lcl_carrier.
2-3-2 Comment out all statements affecting the internal table (or delete them).
2-3-3 Create an airline and fill the transfer parameters with data of your own choice.
2-3-4 Add the planes already created in the last exercise (passenger and cargo planes)
to the list of planes airplane_list. To do this, call the method add_airplane of
the class lcl_carrier.
Create more planes and add them to the airplane list.
2-3-5 Display the airline attributes by calling the display_attributes method of the
class lcl_carrier.
2-3-6 Question: Which code is executed when you execute display_attributes within
display_airplanes.

(C) SAP AG

BC401

9-21

Casting Solutions
Unit: Casting
Topic:

Polymorphism

*&---------------------------------------------------------------------*
*& Report

SAPBC401_CASS_MAIN_a

*&

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

show casting operations ...

*&---------------------------------------------------------------------*
REPORT

sapbc401_cass_main_a.

INCLUDE <icon>.
INCLUDE sapbc401_inhs_a.

DATA: r_plane TYPE REF TO lcl_airplane,


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

START-OF-SELECTION.
*##############################
lcl_airplane=>display_n_o_airplanes( ).
CREATE OBJECT r_passenger EXPORTING
im_name = 'LH BERLIN'
im_planetype = '747-400'
im_seats = 345.
APPEND r_passenger TO plane_list.
CREATE OBJECT r_cargo EXPORTING
(C) SAP AG

BC401

9-22

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

(C) SAP AG

BC401

9-23

*&---------------------------------------------------------------------*
*& Report

SAPBC401_CASS_MAIN_b

*&

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

carrier adds airplanes to its airplane_list --> polymorphism

*&---------------------------------------------------------------------*
REPORT

sapbc401_cass_main_b.

INCLUDE <icon>.
INCLUDE sapbc401_cass_b.

DATA: r_plane TYPE REF TO lcl_airplane,


r_cargo TYPE REF TO lcl_cargo_plane,
r_passenger TYPE REF TO lcl_passenger_plane,
r_carrier type ref to lcl_carrier.

START-OF-SELECTION.
*##############################
***** Create Carrier ********************************************
create object r_carrier exporting im_name = 'Smile&Fly-Travel'.
***** Passenger Plane ********************************************
CREATE OBJECT r_passenger EXPORTING
im_name = 'LH BERLIN'
im_planetype = '747-400'
im_seats = 345.
***** cargo Plane ************************************************
CREATE OBJECT r_cargo EXPORTING
im_name = 'US HErcules'
im_planetype = '747-500'
im_cargo = 533.
***** insert planes into itab if client ***************************
r_carrier->add_airplane( r_passenger ).

(C) SAP AG

BC401

9-24

r_carrier->add_airplane( r_cargo ).

***** show all airplanes inside carrier ***************************


r_carrier->display_attributes( ).

(C) SAP AG

BC401

9-25

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

CLASS lcl_airplane DEFINITION

*---------------------------------------------------------------------*
* Class definitions of ... lcl_airplane, cargo- and passenger_plane
* ...
* ...
*---------------------------------------------------------------------*
*

CLASS lcl_carrier DEFINITION

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

TYPE string,

airplane_list type TABLE OF REF TO lcl_airplane.


ENDCLASS.
*---------------------------------------------------------------------*
*

CLASS lcl_carrier IMPLEMENTATION

*---------------------------------------------------------------------*
CLASS lcl_carrier IMPLEMENTATION.
METHOD add_airplane.
APPEND im_plane TO airplane_list.
ENDMETHOD.
METHOD display_attributes.
WRITE: icon_flight AS ICON, name . uline. uline.
display_airplanes( ).
ENDMETHOD.
(C) SAP AG

BC401

9-26

METHOD display_airplanes.
data: r_plane type ref to lcl_airplane.
loop at airplane_list into r_plane.
r_plane->display_attributes( ).
endloop.
ENDMETHOD.
METHOD constructor.
name = im_name.
ENDMETHOD.
METHOD get_name.
ex_name = name.
ENDMETHOD.
ENDCLASS.

(C) SAP AG

BC401

9-27

Interfaces

Contents:
Interfaces
Compound interfaces
Polymorphism

SAP AG 2002

(C) SAP AG

BC401

10-1

Interfaces: Unit Objectives

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


Define and implement interfaces
Develop generic programs using polymorphism
with interfaces

SAP AG 2002

(C) SAP AG

BC401

10-2

Interfaces: Integration in Course Content

Interfaces
Casting

and
Data Types
ts in
Data Objec
Detail

e
Inheritanc
ing
Programm
nt
Orie ed
of Objectes
pl
ci
rin
P
n
and Desig
Analysis
ing
Programm
d
te
Orien
to Objectn
tio
uc
Introd
al
Using Intern
Tables

rams
Calling Prog
Data
and Passing

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

10-3

Interfaces (1)

Interfaces:
Interfaces: Principles
Principles
Working
Working with
with interfaces
interfaces
Preview:
Preview: Compound
Compound interfaces
interfaces

SAP AG 2002

(C) SAP AG

BC401

10-4

Interfaces: Use

Interfaces

Service 1
Service 2
Service 3
...

Shared services
lcl_carrier

lcl_rental

lcl_hotel

lcl_vehicles

lcl_airplane

...

...

...

...

SAP AG 2002

In ABAP Objects, interfaces are implemented in addition to and independently of classes. Interfaces
only describe the external point of contact of a class (protocols), they do not contain any implementation.
Interfaces are usually defined by a user. The user describes in the interface which services (technical and
semantic) it needs in order to carry out a task. The user never actually knows the providers of these
services, but communicates with them through the interface. In this way the user is protected from actual
implementations and can work in the same way with different classes/objects, as long as they provide the
services required. This is known as polymorphism with interfaces.

(C) SAP AG

BC401

10-5

Interfaces: Services

display_partner
check_availability
...

Client uses

Interface

Shared services
lcl_carrier

lcl_rental

lcl_hotel

lcl_vehicles

lcl_airplane

...

...

...

...

SAP AG 2002

In the above example, a client wants to use the same services of different server classes
(lcl_carrier, lcl_hotel, and lcl_rental) in the same way. There are different
implementations of the services in the server classes (polymorphism).
The following are examples of shared services of the server classes in the above case:
display_partner, check_availability, booking, or cancel_booking.

(C) SAP AG

BC401

10-6

Interface: UML Example

lcl_travel_agency
uses

Client

It is possible to
Implementation
implement
several
mehrerer
Interfaces
interfaces
mglich
!

<<Interface>>

<<Interface>>

lif_partners

lif_license

implements

lcl_carrier

...

lcl_rental

lcl_hotel

lcl_vehicles

lcl_airplane

...

...

...

...

SAP AG 2002

In UML, interfaces can represented in the same way as classes. However, they always have the
stereotype interface above their name and can therefore be distinguished from classes.
The use of an interface is represented by a dotted line with a two-sided arrow from the user to the
interface, the stereotype uses is optional. The fact that a class implements an interface is represented
by a dotted line with a three-sided arrow from the class to the interface. The similarity to the
representation of inheritance is intentional, because the interface can be seen as a generalization of the
class implemented or the class can be seen as a specialization of the interface.
In ABAP Objects, the same components can be defined in interfaces and in classes. This allows you to
shift part of the public point of contact of a class into an interface, even though the class is already in
use; users will not notice the difference as long as you use alias names (see appendix) for the
components that are now in the interface.
A class can implement any number of interfaces and an interface can be implemented by any number of
classes. By implementing several interfaces, a class can simulate multiple inheritance. In the example,
lcl_rental implements the interfaces lif_partners and lif_license.

(C) SAP AG

BC401

10-7

Defining and Implementing an Interface

Declaring the
interface

The server classes


"make the interface
public"

Interfaces are
implemented in classes

Interfaces do not have


visibility sections

INTERFACE lif_partners.
METHODS: display_partner.
ENDINTERFACE.

CLASS lcl_rental DEFINITION.


PUBLIC SECTION.
INTERFACES lif_partners.
ENDCLASS.

CLASS lcl_rental IMPLEMENTATION.


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

ENDMETHOD.
ENDCLASS.

Interface
resolution
operator

SAP AG 2002

In ABAP Objects, the same components (attributes, methods, constants, types, alias names) can be
defined in an interface in largely the same way as in classes. However, interfaces do not have component
visibility levels.
Interfaces are implemented in classes.
The interface name is listed in the definition part of the class. Interfaces can only be implemented
publicly and are therefore always in the PUBLIC SECTION. If you do not do this, you risk
multiple implementations if a superclass and a subclass both implement the same interface
privately.
The operations defined in the interface are implemented as methods of a class. A check is carried
out to ensure that all the methods defined in the interfaces are actually present in the
implementation part of the class (for global interfaces, a missing or superfluous implementation of
an interface method results in a warning).
The attributes, events, constants, and types defined in the interface are automatically available to
the class carrying out the implementation.

Interface components are addressed in the class carrying out the implementation by prefixing
the interface name, followed by a tilde (the Interface Resolution Operator):
<interfacename>~<componentname>.

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

(C) SAP AG

BC401

10-8

Interfaces: Features

Separation of external point of contact


(interface) and implementation (class)

The client defines the protocol, the server implements it

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


the implementation

Looser linkage between client and server

Polymorphism

Code 2
Code 1

Generic handling of objects of different classes

Code 4

Abstraction

Interface as a generalization of
the implementing class
super1

display_partner
Code 3

Interf.

Simulation of multiple inheritance


sub1

sub2

SAP AG 2002

Interfaces are the means of choice for describing external points of contact or protocols, without linking
them to a type of implementation. An extra layer is introduced between the client and the server to
protect the client explicitly from the server, thereby making the client independent.
Interfaces enable you to work uniformly with different classes (providers/servers). In particular, they
always ensure polymorphic behavior as they do not have their own implementation, but instead allow the
providers to carry it out.
The definition of an interface is always an abstraction: The user wants to handle various providers in the
same way and must therefore abstract concrete implementations to a description of the services required
to fulfill the task.
You can also use interfaces to achieve multiple inheritance by defining the functionality to be inherited
by a second class as an interface that the inheriting class then has to implement.

(C) SAP AG

BC401

10-9

Interfaces (2)

Interfaces:
Interfaces: Principles
Principles
Working
Working with
with interfaces
interfaces
Preview:
Preview: Compound
Compound interfaces
interfaces

SAP AG 2002

(C) SAP AG

BC401

10-10

Working with Interface Components

CLASS lcl_rental IMPLEMENTATION.


...
METHOD lif_partners~display_partner.
* special coding to display partners or
* just calling existing method that fits
display_attributes( ).
ENDMETHOD.
ENDCLASS.

lif_partners
display_partner
check_availability
...

implements

DATA: r_vehicle TYPE REF TO lcl_vehicle.


...

CREATE OBJECT r_vehicle.


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

lcl_rental
- name
- vehicle_list
+ add_vehicle
+ display_attributes
...

Interface resolution operator


SAP AG 2002

You can access interface components using an object reference, whose class implements the interface.
Syntactically this is done with the interface resolution operator, just as with the method definitions in the
implementation part of the class.
This allows you to differentiate between components defined in the interface and components of the
same name that are defined in the class itself. The reason for this is the shared namespace.
To simplify accessing interface methods you can work with alias names.
Alias names can only appear in the in the declaration part of a class or in the interface definition.
Example for an alias in the interface: ALIASES a1 FOR lif_interface~method1
An alias defined in this way can be directly addressed using r_ref->a1.

(C) SAP AG

BC401

10-11

Interface References: Narrowing Cast

DATA: r_rental TYPE REF TO lcl_rental,


r_lif
TYPE REF TO lif_partners.

CREATE OBJECT r_rental.

(1) lcl_rental
Public

Private

r_rental
r_lif

Interface
components
* Narrowing Cast
r_lif = r_rental

display_partner
check_availability
...

r_lif

SAP AG 2002

Interfaces are addressed using interface references. Interface references always refer to instances in the
classes carrying out the implementation. Interface references always have both static and dynamic types.
The assignment of an object reference to an interface reference is known as a narrowing cast since, as
with inheritance, only a part of the object interface is visible once you have assigned the reference.
With an interface reference, you can no longer address all components in the class carrying out the
implementation, but only the components defined in the interface. These components are now addressed
using the interface reference exclusively with their own short name.
When an object reference is assigned to an interface reference, you must be able to convert the dynamic
type of the interface reference to the static type of the object reference - that is, the class that was used to
define the object reference must have implemented the interface of the interface-reference.

(C) SAP AG

BC401

10-12

The travel agent is a user (client) of the created interface. The travel agency keeps references to its
business partners in an internal table. Th type of this internal table is REF TO lif_partners, that is
the reference to the interface lif_partners.
When it is called, the client's public method add_partner is transferred the business partner
references. In the method, the references are inserted into the table partner_list. Therefore, the
interface parameter of the add_partner method has the type REF TO lif_partners.
The aim here is polymorphism: It needs to be possible to generically access the services of the interface
later.

(C) SAP AG

BC401

10-13

Polymorphism can also be used for interfaces: you can use interface references to call methods that can
have a different implementation depending on the object behind the reference.
The dynamic type, not the static type of the reference variable is used to search for the implementation
of a method. In the above example, r_partner->display_partner( ) therefore uses the class
of the instance that r_partner actually refers to to search for the implementation of display. The
static type for r_partner, which is always REF TO lif_partners, is not used.

(C) SAP AG

BC401

10-14

The widening cast is, as with inheritance, the opposite of the narrowing cast: Here it is used to retrieve a
class reference from an interface reference. Obviously it cannot be statically checked, since an interface
can be implemented by more than one class.
An object reference cannot be assigned to an interface reference if it has itself not implemented the
corresponding interface. It cannot be assigned even if a subclass has implemented the interface and the
interface reference points to an object in this class.
Assignments between interface references whose interfaces are not related to each other cannot be
checked statically and must therefore be formulated using the cast operator ?=.
For this type of assignment, a check must be carried out at runtime to see whether the class of the
instance that the source reference points to also supports the interface that the target reference refers to.
If this is the case, the cast is carried out, otherwise the exception that can be handled of the class
CX_SY_MOVE_CAST_ERROR is raised.

(C) SAP AG

BC401

10-15

Interfaces (3)

Interfaces:
Interfaces: Principles
Principles
Working
Working with
with interfaces
interfaces
Preview:
Preview: Compound
Compound interfaces
interfaces

SAP AG 2002

(C) SAP AG

BC401

10-16

Compound Interfaces
Interface

lcl_hotel

lif_partners

lcl_rental

lcl_carrier

Solution:
Compound
interfaces

Interface

lif_room_booking

book_room

Problem:
Extending
interfaces

lif_partners

Interface

lcl_hotel

lcl_carrier

lcl_rental

SAP AG 2002

ABAP Objects contains a composition model for interfaces. A compound interface contains other
interfaces as components (component interfaces) and summarizes the extension of these component
interfaces. An elementary interface does not itself contain other interfaces.
One interface can be used as a component interface in several compound interfaces.
UML only deals with the specialization and generalization of interfaces. This relationship is represented
by a dotted line with a three-sided arrow from the specialized to the generalized interface.
Compound interfaces in ABAP Objects can always be seen as specializations of their component
interfaces and represented as such in UML.

(C) SAP AG

BC401

10-17

Compound Interfaces: Example


INTERFACE lif_partners.
METHODS display_partner.
ENDINTERFACE.
INTERFACE lif_room_booking.
INTERFACES lif_partners.
METHODS book_room.
ENDINTERFACE.

DATA: i_partner
i_room_book

CLASS lcl_hotel DEFINITION.


PUBLIC SECTION.
INTERFACES lif_room_booking.
ENDCLASS.
CLASS lcl_hotel IMPLEMENTATION.
METHOD lif_partners~display_partner.
ENDMETHOD.
METHOD lif_room_booking~book_room.
ENDMETHOD.
ENDCLASS.

TYPE REF TO lif_partners,


TYPE REF TO lif_room_booking,

...

i_partner = i_room_book.

Narrowing Cast

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

Widening Cast

SAP AG 2002

In a compound interface, the components of the component interface keep their original names, that is
<component-interfacename>~<componentname>; no more prefixes are added. In other
words, all components in a compound interface are on the same level, and components inherited from
component interfaces are marked with the usual interface prefix.
This equality principle for compound interfaces also affects how they are implemented. The procedure is
as follows: First, implement the elementary interfaces, then the additional methods from the compound
interfaces. For multiple compound interfaces, the process is simply repeated. In the class carrying out the
implementation, all components of all interfaces implemented are again on the same level.
This means that interface components only ever exist once and are known by their original names
<interfacename>~<componentname>. This is true both for compound interfaces and for the
classes that implement them.

(C) SAP AG

BC401

10-18

Interfaces: Unit Summary

You are now able to:


Define and implement interfaces
Develop generic programs using polymorphism
with interfaces

SAP AG 2002

(C) SAP AG

BC401

10-19

Interfaces Exercises
Unit: Interfaces
Topic: Defining Interfaces
At the conclusion of these exercises, you will be able to:
Define and implement interfaces

Model solution: SAPBC401_INTS_MAIN_A


SAPBC401_VEHD_F include program
SAPBC401_INTS_A include program

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

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

1-2

Copy the include program SAPBC401_VEHD_F to your own include program


ZBC401_##_VEHICLE. As well as the classes lcl_rental, lcl_vehicle, lcl_truck,
lcl_bus, the program also contains the interface lif_partners.

1-3

Incorporate this include program into your main program.


Add the types ty_fuel and ty_cargo (both TYPE P DECIMALS 2) to the main program.
Pay attention to the position of the interface definition; you may have to change the
order of the include programs or move the interface into the other include program.
Familiarize yourself with the interface definition.

(C) SAP AG

BC401

10-20

1-4

Now implement the interface of your class lcl_carrier.

1-5

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

UML-Template for Exercise 1-1

(C) SAP AG

BC401

10-21

(C) SAP AG

BC401

10-22

Exercises
Unit: Interfaces
Topic: Using Interfaces
At the conclusion of these exercises, you will be able to:
Define and implement interfaces
Use polymorphism with interfaces
Model solution: SAPBC401_INTS_MAIN_B
SAPBC401_VEHD_G include program
SAPBC401_INTS_A include program

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

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

2-2

Copy the definition of the class lcl_travel_agency from the template


SAPBC401_VEHT_B to your own include program. Then complete this new class.
2-2-1 The travel agency uses the public method add_partner to add business partners
(that is car rental companies and airlines) to the internal table partner_list.
2-2-2 What are the types of the internal table and the interface parameter of
add_partner?
2-2-3 The travel agency will use the method display_agency_partners to display the
data of its business partners.

(C) SAP AG

BC401

10-23

2-3

Go back to your main program.

2-4

Create an instance of the class lcl_travel_agency.


2-4-1 Use the add_partner method to add the travel agencys business partners to the
internal table.
2-4-2 Use the display_agency_partners method to display the travel agencys
business partners.
2-4-3 At which point does polymorphism take place?
Follow this in the Debugger.

UML-Template for Exercise 2-1

(C) SAP AG

BC401

10-24

Interfaces Solutions
Unit: Interfaces
Topic:

Defining Interfaces

*&---------------------------------------------------------------------*
*& Report

SAPBC401_INTS_MAIN_A

*&

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

include interface lif_partners and include file with lcl_vehicle.. *

*&---------------------------------------------------------------------*
REPORT

sapbc401_ints_main_a.

types ty_fuel type p decimals 2.


types ty_cargo type p decimals 2.
INCLUDE <icon>.
INCLUDE sapbc401_vehd_f.
include sapbc401_ints_a.
DATA: r_plane TYPE REF TO lcl_airplane,
r_cargo TYPE REF TO lcl_cargo_plane,
r_passenger TYPE REF TO lcl_passenger_plane,
r_carrier type ref to lcl_carrier,
r_agency type ref to lcl_travel_agency,
r_rental type ref to lcl_rental,
r_truck type ref to lcl_truck,
r_bus type ref to lcl_bus.

START-OF-SELECTION.
*##############################
***** Create Carrier ********************************************
create object r_carrier exporting im_name = 'Smile&Fly-Travel'.

(C) SAP AG

BC401

10-25

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

(C) SAP AG

BC401

10-26

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

Include

SAPBC401_INTS_a

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

CLASS lcl_airplane DEFINITION

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

CLASS lcl_carrier DEFINITION

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

TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane.


ENDCLASS.

"lcl_carrier DEFINITION

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

CLASS lcl_carrier IMPLEMENTATION

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

"lif_partners~display_partner

METHOD add_airplane.
APPEND im_plane TO airplane_list.
ENDMETHOD.
(C) SAP AG

"add_airplane
BC401

10-27

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

"display_attributes

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

"display_airplanes

METHOD constructor.
name = im_name.
ENDMETHOD.

"constructor

METHOD get_name.
ex_name = name.
ENDMETHOD.
ENDCLASS.

(C) SAP AG

"get_name
"lcl_carrier IMPLEMENTATION

BC401

10-28

Solutions
Unit: Interfaces
Topic:

Using Interfaces

*&---------------------------------------------------------------------*
*& Report

SAPBC401_INTS_MAIN_B

*&

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

include interface lif_partners and include file with lcl_vehicle.. *

*&

the client (travel_agency) uses the interface...

*&---------------------------------------------------------------------*
REPORT

sapbc401_ints_main_b.

types ty_fuel type p decimals 2.


types ty_cargo type p decimals 2.
INCLUDE <icon>.
INCLUDE sapbc401_vehd_g.
include sapbc401_ints_a.
DATA: r_plane TYPE REF TO lcl_airplane,
r_cargo TYPE REF TO lcl_cargo_plane,
r_passenger TYPE REF TO lcl_passenger_plane,
r_carrier type ref to lcl_carrier,
r_agency type ref to lcl_travel_agency,
r_rental type ref to lcl_rental,
r_truck type ref to lcl_truck,
r_bus type ref to lcl_bus.
START-OF-SELECTION.
*##############################
***** Create TRAVEL_AGENCY **************************************
CREATE OBJECT r_agency EXPORTING im_name = 'Fly&Smile Travel'.

(C) SAP AG

BC401

10-29

***** 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 ).
***** insert business-parnter of agency into partner_list***********
r_agency->add_partner( r_carrier ).
******* create RENTAL *****************************************
CREATE OBJECT r_rental EXPORTING im_name = 'HAPPY CAR RENTAL'.
******* create truck *****************************************
CREATE OBJECT r_truck EXPORTING im_make = 'MAN'
im_cargo = 45.
r_rental->add_vehicle( r_truck ).
******* create truck *****************************************
CREATE OBJECT r_bus EXPORTING im_make = 'Mercedes'
im_passengers = 80.
r_rental->add_vehicle( r_bus ).
******* create truck *****************************************
CREATE OBJECT r_truck EXPORTING im_make = 'VOLVO'
im_cargo = 48.
r_rental->add_vehicle( r_truck ).
***** insert business-partner of agency into partner_list***********
r_agency->add_partner( r_rental ).
(C) SAP AG

BC401

10-30

******* show attributes of all partners of travel_agency ******


r_agency->display_agency_partners( ).

(C) SAP AG

BC401

10-31

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

Include

SAPBC401_VEHD_g

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

"lif_partners

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

CLASS lcl_vehicle DEFINITION

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

constructor IMPORTING im_make TYPE string.

METHODS

display_attributes.

METHODS

set_make IMPORTING im_make TYPE string.

METHODS

get_make EXPORTING ex_make TYPE string.

CLASS-METHODS get_count EXPORTING re_count TYPE i.


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

TYPE string.

METHODS

init_make.

CLASS-DATA:

n_o_vehicles TYPE i.

ENDCLASS.

"lcl_vehicle DEFINITION

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

CLASS lcl_vehicle IMPLEMENTATION

(C) SAP AG

BC401

10-32

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

"get_average_fuel

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

"constructor

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

" me->init_make( ). also possible

ELSE.
make = im_make.
ENDIF.
ENDMETHOD.

"set_make

METHOD init_make.
make = 'default make'.
ENDMETHOD.

"init_make

METHOD get_make.
ex_make = make.
ENDMETHOD.

"get_make

METHOD display_attributes.
WRITE: make.
ENDMETHOD.

"display_attributes

METHOD get_count.
re_count = n_o_vehicles.
ENDMETHOD.
ENDCLASS.

"get_count
"lcl_vehicle IMPLEMENTATION

*---------------------------------------------------------------------*
(C) SAP AG

BC401

10-33

CLASS lcl_truck DEFINITION

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

constructor IMPORTING im_make TYPE string


im_cargo TYPE ty_cargo.

METHODS

display_attributes REDEFINITION.

METHODS

get_cargo RETURNING value(re_cargo) TYPE ty_cargo.

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

"lcl_vehicle DEFINITION

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

CLASS lcl_truck IMPLEMENTATION

*---------------------------------------------------------------------*
CLASS lcl_truck IMPLEMENTATION.
METHOD constructor.
super->constructor( im_make ).
max_cargo = im_cargo.
ENDMETHOD.

"constructor

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

"display_attributes

METHOD get_cargo.
re_cargo = max_cargo.
ENDMETHOD.

(C) SAP AG

"get_cargo

BC401

10-34

ENDCLASS.

"lcl_vehicle DEFINITION

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

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.

"lcl_vehicle DEFINITION

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

CLASS lcl_bus IMPLEMENTATION

*---------------------------------------------------------------------*
CLASS lcl_bus IMPLEMENTATION.
METHOD constructor.
super->constructor( im_make ).
max_passengers = im_passengers.
ENDMETHOD.

"constructor

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

20 ' Passengers = ', max_passengers.

ULINE.
ENDMETHOD.
(C) SAP AG

"display_attributes
BC401

10-35

ENDCLASS.

"lcl_vehicle DEFINITION

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

CLASS lcl_rental DEFINITION

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

constructor IMPORTING im_name TYPE string.

METHODS

add_vehicle IMPORTING im_vehicle


TYPE REF TO lcl_vehicle.

METHODS

display_attributes.

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

"lcl_rental DEFINITION

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

CLASS lcl_rental IMPLEMENTATION

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

"lif_partners~display_partner

constructor.

name = im_name.
ENDMETHOD.
METHOD

"constructor

add_vehicle.

APPEND im_vehicle TO vehicle_list.


ENDMETHOD.
METHOD

"add_vehicle

display_attributes.

DATA: r_vehicle TYPE REF TO lcl_vehicle.


WRITE: /
(C) SAP AG

icon_transport_proposal AS ICON, name.


BC401

10-36

WRITE:

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

LOOP AT vehicle_list INTO r_vehicle.


r_vehicle->display_attributes( ).
ENDLOOP.
ENDMETHOD.

"display_attributes

ENDCLASS.

"lcl_rental IMPLEMENTATION

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

CLASS lcl_travel_agency DEFINITION

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

constructor IMPORTING im_name TYPE string.

METHODS

add_partner IMPORTING im_partner


TYPE REF TO lif_partners.

METHODS

display_agency_partners.

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

"lcl_travel_agency DEFINITION

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

CLASS lcl_travel_agency IMPLEMENTATION

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

' Here are the partners of the travel agency: '.ULINE.ULINE.

LOOP AT partner_list INTO r_partner.


r_partner->display_partner( ).
ENDLOOP.
ENDMETHOD.
METHOD

"display_agency_partners

constructor.

name = im_name.
(C) SAP AG

BC401

10-37

ENDMETHOD.
METHOD

"constructor

add_partner.

APPEND im_partner TO partner_list.


ENDMETHOD.
ENDCLASS.

(C) SAP AG

"add_partner
"lcl_travel_agency IMPLEMENTATION

BC401

10-38

Events

Contents:

Defining and triggering events


Registering and handling events

SAP AG 2002

(C) SAP AG

BC401

11-1

Events: Unit Objectives

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


Define and trigger events
Handle events
Register and deregister events
Receive a reference from the sender
Explain the conceptual differences between
methods and events

SAP AG 2002

(C) SAP AG

BC401

11-2

Events: Integration in Course Content

Events
Interfaces

and
Data Types
ts in
Data Objec
Detail

Casting
e
Inheritanc
ing
Programm
nt
Orie ed
of Objectes
pl
ci
rin
P
n
and Desig
Analysis
ing
rogramm
P
d
te
en
Object-Ori
to
n
tio
Introduc
al
Using Intern
Tables

rams
Calling Prog
Data
and Passing

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

11-3

By triggering an event, an object or class announces a change of state, or that a certain state has been
achieved.
In the example, the class car triggers the event created. Other classes subscribe to this event (triggered
when a car is instantiated) and process it. The car rental company wants to be informed of completion;
the car is registered at the vehicle registration office.
Note:
The events discussed here are not the events of the ABAP runtime system (such as INITIALIZATION,
START-OF-SELECTION, and so on) and not the events of background processing or workflow.

(C) SAP AG

BC401

11-4

Features

Looser linkage than for a method call

Triggering object makes status change known

Handler objects can show interest and react

Different communication model

The trigger does not know the user;


user's reaction is of no interest to trigger

Areas of use

GUI implementations

Conformity with other object models: COM, ActiveX controls, OpenDoc

SAP AG 2002

Events link objects or classes more loosely than direct method calls do. Method calls establish precisely
when and in which statement sequence the method is called. However, with events, the reaction of the
object to the event is triggered by the event itself.
Events are most often used in GUI implementations.
Other external object models, such as COM, ActiveX controls, and so on, also provide events.

(C) SAP AG

BC401

11-5

Triggering and Handling Events: Overview

Rules:

Triggering events
1

Class defines event


(EVENTS, CLASS-EVENTS)

Object or class triggers event


(RAISE EVENT)

Handling events
3

Event handler class defines and implements event


handler method
([CLASS-]METHODS... FOR EVENT ... OF ...)

Event handler object or handler class registers itself to


specific events at runtime
(SET HANDLER)

SAP AG 2002

At the moment of implementation, a class defines its:


Instance events (using the EVENTS statement)
Static events (using the CLASS-EVENTS statement)
Classes or their instances that receive a message when an event is triggered at runtime and want to react
to this event define event handler methods.
Statement:
[CLASS-]METHODS <handler_method> FOR EVENT <event> OF <classname>.
These classes or their instances are registered to one or more events at runtime.
Statement:
SET HANDLER <handler_method> FOR <reference>. (for instance events)
SET HANDLER <handler_method>. (for static events)
A class or instance can trigger an event at runtime using the RAISE EVENT statement.

(C) SAP AG

BC401

11-6

Both instance and static events can be triggered in instance methods.


Only static events can be triggered in static methods.
Events can only have EXPORTING parameters which must be passed by value.
Triggering an event using the statement RAISE EVENT has the following effect:
The program flow is interrupted at that point
The event handler methods registered to this event are called and processed
Once all event handler methods have been executed, the program flow continues
If an event handler method in turn triggers an event, then the program flow is again interrupted and all
event handler methods are executed (nesting).

(C) SAP AG

BC401

11-7

Events are registered using the SET HANDLER statement. Registration is only active at program
runtime. Events cannot be persistent.
You want to register an object to an event belonging to another object. The SET HANDLER statement
enters the registration in that object's list. All handlers for one event are entered in this list.
When the event is triggered, the list shows which event handler methods need to be called.

(C) SAP AG

BC401

11-8

Event handler methods are triggered by events (RAISE EVENT), although they can also be called like
normal methods (CALL METHOD).
The interface of the event handler method consists solely of IMPORTING parameters. You can only use
parameters from the definition of the corresponding events (event interface). An event interface, which
only has EXPORTING parameters, is defined using the EVENTS statement in the declaration of the
event. The parameters are typed in the event definition and the typing is passed to the event handler
method, that is, the interface parameters of the event handler method cannot be typed in the definition of
the event handler method.
In addition to the explicitly defined event interface parameters, the implicit parameter sender can also
be listed as an IMPORTING parameter for instance events. This passes on a reference to the object that
triggered the event.

(C) SAP AG

BC401

11-9

When an event is triggered, only those event handler methods are executed that have, by this point,
registered themselves using SET HANDLER.
You can register an event using ACTIVATION 'X', and deregister it using ACTIVATION space. If
you do not specify ACTIVATION, then the event registers (default behavior).
You can register several methods in one SET HANDLER statement:
SET HANDLER <ref_handle1>-><handler_method1>
...
<ref_handleN>-><handler_methodN>
FOR <ref_sender> | FOR ALL INSTANCES.

(C) SAP AG

BC401

11-10

Every object that has defined events has an internal table, the handler table. All objects that have
registered for events are entered in this table together with their event handler methods.
Objects that have registered themselves for an event that is still "active" also remain "active". The
methods of these objects are called when the event is triggered, even if they can no longer be reached
using main memory references.

(C) SAP AG

BC401

11-11

Event Handling: Features

Event handling is sequential

Sequence in which event handler methods are called is not defined

With regard to the Garbage Collector, registration has the same effect
as a reference to the registered object

Registered objects are never deleted

The visibility of an event defines authorization for event handling

The visibility in an event handler method defines authorization for


using SET HANDLER statements

Event handler methods, however, can only have the same visibility or more
restricted visibility than the events they refer to

SAP AG 2002

If several objects have registered for an event, then the sequence in which the event handler methods are
called is not defined, that is, there is no guaranteed sequence in which the event handler methods are
called.
If a new event handler is registered in an event handler method for an event that has just been triggered,
then this event handler is added to the end of the sequence and is then also executed when its turn comes.
If an existing event handler is deregistered in an event handler method, then this handler is deleted from
the event handler method sequence.
Events are also subject to the visibility concept and can therefore be either public, protected, or private.
Visibility specifies who can handle an event:
PUBLIC: All users
PROTECTED: Only users within that class or its subclasses
PRIVATE: Only users within that class
Event handler methods also have visibility attributes. Event handler methods, however, can only have
the same visibility or more restricted visibility than the events they refer to. The visibility of event
handler methods establishes authorization for SET HANDLER statements; SET HANDLER statements
can be used: Everywhere, in the class and its subclasses, or only within the class.

(C) SAP AG

BC401

11-12

Events: Unit Summary

You are now able to:


Define and trigger events
Handle events
Register and deregister events
Explain the conceptual differences between
methods and events

SAP AG 2002

(C) SAP AG

BC401

11-13

Events Exercises
Unit: Events
Topic: Triggering and Handling Events
At the conclusion of these exercises, you will be able to:
Define and trigger events
Handle events
Register event handler methods
As soon as a new airplane is created, this event must be made known to
the airline. .

Model solution: SAPBC401_EVES_MAIN_A


SAPBC401_VEHD_H include program
SAPBC401_EVES_A include program
1 The add_airplane method of the class lcl_carrier will no longer be explicitly called in the
main program, but be triggered automatically from the class lcl_airplane.
Triggering an event when a plane is created (CREATE OBJECT) will result in the
automatic execution of the airline method add_airplane.
1-1

In the UML diagram decide what steps are needed where for the triggering and
handling of the event airplane_created.
See next page for UML diagram.

1-2

Trigger the event airplane_created in a suitable method within the class


lcl_airplane.

1-3

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

1-4

In the main program, comment out the calls


r_carrier->add_airplane.

1-5

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

(C) SAP AG

BC401

11-14

1-6 Optional:
Implement the event vehicle_created for the car rental company and its corresponding
vehicles.
2 Optional (advanced):
In the UML, there is the possibility of using events when creating the business partners of
the travel agency.
If airlines, car rental companies, or hotels are created, these business partners should
automatically be made known to the travel agency.
2-1

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

2-2

Implement your solution for lcl_carrier and lcl_rental.

(C) SAP AG

BC401

11-15

Solutions
Unit:

Events

Topic:

Triggering and Handling Events

*&---------------------------------------------------------------------*
*& Report

SAPBC401_EVES_MAIN_A

*&

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

Implement Events in lcl_vehicle and lcl_airplane

*&---------------------------------------------------------------------*
REPORT

sapbc401_eves_main_a.

TYPES: ty_fuel TYPE p DECIMALS 2,


ty_cargo TYPE p DECIMALS 2.
INCLUDE <icon>.
include sapbc401_vehd_h.
INCLUDE sapbc401_eves_a.

DATA: r_vehicle TYPE REF TO lcl_vehicle,


r_truck TYPE REF TO lcl_truck,
r_bus

TYPE REF TO lcl_bus,

r_passenger type ref to lcl_passenger_plane,


r_cargo type ref to lcl_cargo_plane,
r_carrier type ref to lcl_carrier,
r_rental type ref to lcl_rental,
r_agency type ref to lcl_travel_agency.
START-OF-SELECTION.
*########################
***** Create TRAVEL_AGENCY **************************************
CREATE OBJECT r_agency EXPORTING im_name = 'Fly&Smile Travel'.

(C) SAP AG

BC401

11-16

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

***** insert business-parnter of agency into partner_list***********


r_agency->add_partner( r_carrier ).
******* create RENTAL *****************************************
CREATE OBJECT r_rental EXPORTING im_name = 'HAPPY CAR RENTAL'.
******* create truck *****************************************
CREATE OBJECT r_truck EXPORTING im_make = 'MAN'
im_cargo = 45.
*

r_rental->add_vehicle( r_truck ).

******* create truck *****************************************


CREATE OBJECT r_bus EXPORTING im_make = 'Mercedes'
im_passengers = 80.
*

r_rental->add_vehicle( r_bus ).

******* create truck *****************************************


CREATE OBJECT r_truck EXPORTING im_make = 'VOLVO'
im_cargo = 48.
*

r_rental->add_vehicle( r_truck ).

***** insert business-parnter of agency into partner_list***********


(C) SAP AG

BC401

11-17

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

(C) SAP AG

BC401

11-18

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

Include

SAPBC401_EVES_A

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

CLASS lcl_airplane DEFINITION

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

TYPE string

im_planetype TYPE saplane-planetype,


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

TYPE saplane-planetype

EXPORTING ex_weight

TYPE s_plan_wei

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

(C) SAP AG

BC401

11-19

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

(C) SAP AG

"get_technical_attributes
"lcl_airplane IMPLEMENTATION

BC401

11-20

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

CLASS lcl_cargo_plane DEFINITION

*---------------------------------------------------------------------*
CLASS lcl_cargo_plane DEFINITION INHERITING FROM lcl_airplane.
PUBLIC SECTION.
"---------------------METHODS: constructor IMPORTING im_name TYPE string
im_planetype TYPE saplane-planetype
im_cargo TYPE scplane-cargomax.
METHODS: display_attributes REDEFINITION.
PRIVATE SECTION.
"---------------------DATA: max_cargo TYPE scplane-cargomax.
ENDCLASS.

"lcl_cargo_plane DEFINITION

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

CLASS lcl_cargo_plane IMPLEMENTATION

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

METHOD constructor.
CALL METHOD super->constructor
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.

(C) SAP AG

"display_attributes

BC401

11-21

ENDCLASS.

"lcl_cargo_plane IMPLEMENTATION

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

CLASS lcl_passenger_plane DEFINITION

*---------------------------------------------------------------------*
CLASS lcl_passenger_plane DEFINITION INHERITING FROM lcl_airplane..
PUBLIC SECTION.
METHODS: constructor IMPORTING im_name TYPE string
im_planetype TYPE saplane-planetype
im_seats TYPE sflight-seatsmax.
METHODS: display_attributes REDEFINITION.
PRIVATE SECTION.
DATA: max_seats TYPE sflight-seatsmax.
ENDCLASS.

"lcl_passenger_plane DEFINITION

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

CLASS lcl_passenger_plane IMPLEMENTATION

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

METHOD constructor.
CALL METHOD super->constructor
EXPORTING
im_name

= im_name

im_planetype = im_planetype.
max_seats = im_seats.
ENDMETHOD.

"constructor

METHOD display_attributes.
super->display_attributes( ).
WRITE: / 'Max Seats = ', max_seats.
ULINE.
ENDMETHOD.
(C) SAP AG

"display_attributes
BC401

11-22

ENDCLASS.

"lcl_passenger_plane IMPLEMENTATION

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

CLASS lcl_carrier DEFINITION

*---------------------------------------------------------------------*
CLASS lcl_carrier DEFINITION.
PUBLIC SECTION.
"---------------------------------------INTERFACES lif_partners.
METHODS: constructor IMPORTING im_name TYPE string,
get_name RETURNING value(ex_name) TYPE string,
add_airplane for event airplane_created of lcl_airplane
IMPORTING sender,
display_airplanes,
display_attributes.
PRIVATE SECTION.
"----------------------------------DATA: name

TYPE string,

airplane_list TYPE TABLE OF REF TO lcl_airplane.


ENDCLASS.

"lcl_carrier DEFINITION

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

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.
(C) SAP AG

"display_attributes
BC401

11-23

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

"display_airplanes

METHOD constructor.
name = im_name.
set handler add_airplane for all instances.
ENDMETHOD.

"constructor

METHOD get_name.
ex_name = name.
ENDMETHOD.
ENDCLASS.

(C) SAP AG

"get_name
"lcl_carrier IMPLEMENTATION

BC401

11-24

Solutions (optional)
Unit:

Events

Topic:

Triggering and Handling Events

*&---------------------------------------------------------------------*
*& Report

SAPBC401_EVES_MAIN_B

*&

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

Implement Events in LCL_vehicle and lcl_airplane

*&

Implement Events in LCL_carrier and lcl_rental

*&---------------------------------------------------------------------*
REPORT

sapbc401_eves_main_b.

TYPES: ty_fuel TYPE p DECIMALS 2,


ty_cargo TYPE p DECIMALS 2.
INCLUDE <icon>.
include sapbc401_vehd_i.
INCLUDE sapbc401_eves_b.
DATA: r_vehicle TYPE REF TO lcl_vehicle,
r_truck TYPE REF TO lcl_truck,
r_bus

TYPE REF TO lcl_bus,

r_passenger type ref to lcl_passenger_plane,


r_cargo type ref to lcl_cargo_plane,
r_carrier type ref to lcl_carrier,
r_rental type ref to lcl_rental,
r_agency type ref to lcl_travel_agency.
START-OF-SELECTION.
*########################
******* create travel_agency *****************************************
CREATE OBJECT r_agency EXPORTING im_name = 'Fly&Smile Travel'.

(C) SAP AG

BC401

11-25

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

(C) SAP AG

BC401

11-26

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

Include

SAPBC401_EVES_B

*&---------------------------------------------------------------------*
*------------------------------------------------------------------*
* events in: lcl_airplane and lcl_carrier !
*
*------------------------------------------------------------------*
*

CLASS lcl_airplane DEFINITION

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

TYPE string

im_planetype TYPE saplane-planetype,


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

TYPE saplane-planetype

EXPORTING ex_weight

TYPE s_plan_wei

ex_tankcap
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

*------------------------------------------------------------------*
(C) SAP AG

BC401

11-27

CLASS lcl_airplane IMPLEMENTATION.


METHOD constructor.
name

= im_name.

planetype

= im_planetype.

n_o_airplanes = n_o_airplanes + 1.
RAISE EVENT airplane_created.
ENDMETHOD.

"constructor

METHOD display_attributes.
DATA: weight TYPE saplane-weight,
cap TYPE saplane-tankcap.
WRITE: / icon_ws_plane AS ICON,
/ 'Name of airplane'(001), AT pos_1 name,
/ 'Type of airplane: '(002), AT pos_1 planetype.
get_technical_attributes( EXPORTING im_type = planetype
IMPORTING ex_weight = weight
ex_tankcap = cap ).
WRITE: / 'Weight:'(003), weight,
'Tankkap:'(004), cap.
ENDMETHOD.

"display_attributes

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

"display_n_o_airplanes

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

ex_weight = 100000. ex_tankcap = 10000. ENDIF.

ENDMETHOD.
ENDCLASS.

"get_technical_attributes
"lcl_airplane IMPLEMENTATION

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

CLASS lcl_carrier DEFINITION

*---------------------------------------------------------------------*
CLASS lcl_carrier DEFINITION.
PUBLIC SECTION.
(C) SAP AG

BC401

11-28

"---------------------------------------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,
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.
(C) SAP AG

BC401

11-29

SET HANDLER add_airplane FOR ALL INSTANCES.


RAISE EVENT lif_partners~partner_created.
ENDMETHOD.
ENDCLASS.

(C) SAP AG

"constructor
"lcl_carrier IMPLEMENTATION

BC401

11-30

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

Include

SAPBC401_VEHD_i

*&---------------------------------------------------------------------*
*---------------------------------------------------------------------*
* define client lcl_travel_agency
* it will use the interface lif_partners
*
* implement EVENT in LCL_VEHICLE and LCL_RENTAL
*---------------------------------------------------------------------*
INTERFACE lif_partners.
METHODS display_partner.
*** event defined inside the interface !! ****
EVENTS: partner_created.
ENDINTERFACE.

"lif_partners

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

CLASS lcl_vehicle DEFINITION

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

constructor IMPORTING im_make TYPE string.

METHODS

display_attributes.

METHODS

set_make IMPORTING im_make TYPE string.

METHODS

get_make EXPORTING ex_make TYPE string.

CLASS-METHODS get_count EXPORTING re_count TYPE i.


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

TYPE string.

METHODS

init_make.

CLASS-DATA:

n_o_vehicles TYPE i.

(C) SAP AG

BC401

11-31

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.
re_count = n_o_vehicles.
ENDMETHOD.
(C) SAP AG

"get_count
BC401

11-32

ENDCLASS.

"lcl_vehicle IMPLEMENTATION

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

CLASS lcl_rental DEFINITION

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

constructor IMPORTING im_name TYPE string.

METHODS

add_vehicle for event vehicle_created of lcl_vehicle


importing sender.

METHODS

display_attributes.

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

"lcl_rental DEFINITION

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

CLASS lcl_rental IMPLEMENTATION

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

"lif_partners~display_partner

constructor.

name = im_name.
set handler add_vehicle for all instances.
raise event lif_partners~partner_created.
ENDMETHOD.
METHOD

"constructor

add_vehicle.

APPEND sender TO vehicle_list.


ENDMETHOD.

(C) SAP AG

"add_vehicle

BC401

11-33

METHOD

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

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

BC401

11-34

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

(C) SAP AG

"add_partner
"lcl_travel_agency IMPLEMENTATION

BC401

11-35

Global Classes and Interfaces

Contents:
Local versus global classes and interfaces
Class Builder

SAP AG 2002

(C) SAP AG

BC401

12-1

Global Classes and Interfaces: Unit Objectives

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


Describe the difference between local and global
classes and interfaces
Create global classes and interfaces using the
Class Builder

SAP AG 2002

(C) SAP AG

BC401

12-2

Global Classes and Interfaces: Integration in


Course Content

terfaces
sses and In
la
C
l
a
b
Glo
Events

Interfaces
Casting

and
Data Types
ts in
Data Objec
Detail

e
Inheritanc
ming
ed Program
nt
rie
O
of ObjectPrinciples
n
and Desig
Analysis
ing
Programm
d
te
en
Ori
to Objectn
tio
uc
Introd
al
Using Intern
Tables

rams
Calling Prog
Data
and Passing

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

12-3

Global Classes and Interfaces (1)

Class
Class Builder
Builder
Working
Working with
with global
global classes
classes and
and interfaces
interfaces
Applied
Applied example
example

SAP AG 2002

(C) SAP AG

BC401

12-4

Review: Local Classes and Interfaces

Programm-1

Programm-2

REPORT prog1.
REPORT prog2.
CLASS lcl_airplane DEFINITION.
ENDCLASS.

DATA: r_airplane
TYPE REF TO lcl_airplane.

...

...

...

Local program classes

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

No global access possible

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

SAP AG 2002

Local classes and interfaces are only known within the program in which they are defined and
implemented.
Local classes and interfaces are not stored in the Repository (no TADIR entry). There is no "global"
access to these classes or interfaces (for example, from other programs).

(C) SAP AG

BC401

12-5

Global Classes and Interfaces

ABAP Workbench development tool: Class Builder

Tool for creating, testing, and managing global classes and


interfaces

Stored in Repository

Generates the framework coding,


for example CLASS <name> DEFINITION

Manages the include programs in which the coding is stored

Access from all programs using TYPE REF TO

Customer namespace for global classes and interfaces: Y* or


Z*

Where-used list available

SAP AG 2002

Unlike local program classes and interfaces, global classes and interfaces can be created and
implemented using the ABAP Workbench tool Class Builder. These classes and interfaces are then
available active throughout the whole system.
Global class and interface names share the same namespace.
Individual methods of global classes and interfaces can be transported separately.

(C) SAP AG

BC401

12-6

Creating Global Classes in the Object Navigator

Workbench

Edit

Goto

Utilities

Environment

MIME Repository
Diese Knpre hier
Repository Browser
Repository Information
Systemich auch
brauche
Tag Library
Transport Organizer

System

Help

Create Report
a class in the Object
Navigator

Package

Instance creation

ZBC401_00

Object Name
ZBC401_00
Class Library
Classes

Description

private
protected
public
abstract

Normal ABAP class


Exception class
Persistent class
Final class
Only modeled

SAP AG 2002

You can also display the Class Builder's global classes in the Object Navigator.
Being able to view classes through the navigation window on the left is especially useful when
developing code.
Here, you can also create a new class. Proceed as you would when creating a program: Use the context
menu for a package node or directly for a class node within a package.
Alternatively, you can also create a new class by entering a class name and then choosing Display. In
this case, you must specify a package.
I dialog box asks you to make further specifications for the new class:
Instance creation: Where are instances of this new class to be created?
For example, if you specify private the class could only be instantiated within the class itself.
The default setting is public.
Exception class (this will be discussed in more detail later, in the context of exception handling)
Persistent class (this will be discussed in more detail later, in the context of special techniques)
Final class (represents the end of an inheritance tree)
Only modeled (class definition only for modeling)

(C) SAP AG

BC401

12-7

Class Builder: Attributes


Class

Edit

Goto

Utilities

Environment

System

Help

Define class
attributes

Class Builder: Change Class ZCL_AIRPLANE_00


Class Constructor
Class Interface
Properties

ZCL_AIRPLANE_00
Interfaces

Friends

Implemented/Active
Attributes Methods

Events

Internal Types

Aliases

Filter
Attribute

Level

Name

Instan

PLANE _TYPE

Instan

N_O_AIRPLANES

Static

Visib. Mod. Re. Typing

Assoc. Type

Description

Priv

Type

STRING

Name of airplane

Priv

Type

SAPLANE

Airplane type

Priv

Type

Number of airplanes

SAP AG 2002

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

(C) SAP AG

BC401

12-8

Class Builder: Methods


Class

Edit

Goto

Utilities

Environment

System

Help

Define class
methods

Class Builder: Change Class ZCL_ AIRPLANE_00


Constructor
ZCL_AIRPLANE_00

Class Interface
Properties

Interfaces

Parameters

Friends

Implemented/Active

Attribute Methods

Events

Internal Types Aliases

Exceptions

Methods

Level

CONSTRUCTOR

Instance Method Public

CONSTRUCTOR

DISPLAY ATTRIBUTES

Instance Method Public

Airplane attributes

DISPLAY_N_O_AIRPLANES

Static Method

Number of planes

Visibility

Mod. Met.

Public

Description

Define signature of selected


method,
here: CONSTRUCTOR

SAP AG 2002

Under the Methods tab, you can create methods.


This task is simplified by the Constructor function, choosing which automatically creates the constructor
method. You still have to specify the interface and the source code for the method.
Choose Parameter to define the signature for the method the cursor is currently on.

(C) SAP AG

BC401

12-9

Class Builder: Interface Methods


Class

Edit

Goto

Utilities

Environment

System

Help

Class Builder: Change Class ZCL_ AIRPLANE_00

ZCL_AIRPLANE_00

Class Interface
Properties

Implemented/Active

Interfaces Friends Attribute Methods

Parameters

Events

Internal Types Aliases

Exceptions
Visibility

Methods

Level

CONSTRUCTOR

Instance Method Public

CONSTRUCTOR

DISPLAY ATTRIBUTES

Instance Method Public

Airplane attributes

DISPLAY_N_O_AIRPLANES

Static Method

Number of planes

ZIF_FLY~START

Interface Method Public

Public

2) Method implementation of
a global interface

Mod. Met.

Description

Preparations for start

1) Announce a global
interface in a global class

SAP AG 2002

A global interface that was created in the Class Builder can be announced in a server class by choosing
the Interfaces tab.
All interface methods are then automatically listed under the Methods tab.
All interface methods must then be implemented in this server class. In the example, the interface
zif_fly consists of a single method start.

(C) SAP AG

BC401

12-10

Class Builder: Method Interface

Class

Edit

Goto

Utilities

Environment

System

Help

Class Builder: Change Class ZCL_AIRPLANE_00


Constructor
Class Interface
Properties

Method Parameters
Methods
Parameter

ZCL_AIRPLANE_00
Interfaces

Friends

Implemented/Active
Attributes

Methods

Events

Internal Types

Aliases

CONSTRUCTOR
Exceptions
P

Typing

Assoc. Type

IM_ NAME

Type

STRING

IM_PLANETYPE

Type

SAPLANE-...

Type

Type

Default Value Description


Plane type

Signature parameters of
method,
here: CONSTRUCTOR

SAP AG 2002

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

(C) SAP AG

BC401

12-11

Class Builder: Method Implementation

Method

Edit

Goto

Utilities

Environment

System

Help

Class Builder: Change Class ZCL_ AIRPLANE_00


Signature
Type Parameters

Type spec.

Description

IM_NAME

TYPE STRING

IM_PLANETYPE

TYPE SAPLANE-PLANETYPE Plane type

Method

CONSTRUCTOR

active

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

Display the interface to


help
implementing
Display
thewith
interface
to help
the method the method
with implementing

SAP AG 2002

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

(C) SAP AG

BC401

12-12

Class Builder: Inheritance


Class

Edit

Goto

Utilities

Environment

System

Help

Class Builder: Change Class


CL_VEHICLE
Announce
superclass
Class Constructor
Class Interface
Properties

ZCL_CARGO_PLANE_00
Interfaces

Friends

Implemented/Active

Attributes Methods

Events

Internal Types

Aliases

Superclass
Superclass

Superclass

ZCL_AIRPLANE_00

Description

...

Instantiation

...

Final
...
SAP AG 2002

In the Class Builder, inheritance relationships are defined by choosing the Properties tab.
Here, for example, is the Superclass function, which you can use to specify the superclass for the current
class.
In this example, the superclass ZCL_AIRPLANE_00 is specified for the subclass
ZCL_CARGO_PLANE_00.

(C) SAP AG

BC401

12-13

Class Builder: Test Environment

Class

Edit

Goto

Utilities

Test Class ZCL_AIRPLANE_00


Instance

Handler

Test Class ZCL_AIRPLANE_00

Upper/Lower Case Active

ZCL_AIRPLANE_00
Attributes
Methods

Handler
TestObject->
Upper/Lower Case Active

DISPLAY_N_O_AIRPLANES
ZCL_AIRPLANE_00

45<CL_AIRPLANE_00

Interfaces
Attributes
Methods
DISPLAY_ATTRIBUTES
DISPLAY_N_O_AIRPLANES

Create an instance with


the test environment
SAP AG 2002

If the class is completed and activated, you can use the test tool to create an instance of the class and test
method calls of the class.

(C) SAP AG

BC401

12-14

Global Classes and Interfaces (2)

Class
Class Builder
Builder
Working
Working with
with global
global classes
classes and
and interfaces
interfaces
Applied
Applied example
example

SAP AG 2002

(C) SAP AG

BC401

12-15

Global Classes in the Object Navigator

Workbench

Edit

Goto

Utilities

Environment

System

Help

ABAP Editor: Report zdemo


Pattern

MIME Repository
Diese Knpre hier
Repository Browser
Repository Information
Systemich auch
brauche
Tag Library
Transport Organizer
Class/Interface

Report

zdemo

Active

Left: Displaying a class in the


navigation window allows you
to access the class components

ZCL_AIRPLANE_00

Object Name
ZCL_AIRPLANE_00

Description
Class Airplane

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

Attributes
NAME
N_O_AIRPLANES
PLANE _TYPE
Methods

Name of airplane
Number of planes
Airplane type

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

Right: Edit an ABAP program


in the Editor

SAP AG 2002

You can also display the Class Builder's global classes in the Object Navigator.
Being able to view classes through the navigation window on the left is especially useful when editing
source code. You can drag & drop specific components into the right Editor window and automatically
create and insert source code (as a template).

(C) SAP AG

BC401

12-16

Class Builder: CREATE OBJECT


Workbench

Edit

Goto

Utilities

Environment

System

Help

ABAP Editor: Report zdemo


Pattern

Report

MIME Repository

Knpre
Repository Browser Diese
Selecting
andhier
dragging

CREATE OBJECT

Class/Interface
ZCL_AIRPLANE_00

Object Name
ZCL_AIRPLANE_00

*********************************************************************
* XY_00_airplane
*********************************************************************
* XY_00_airplane
CLASS lcl_airplane DEFINITION.
START-OF-SELECTION.
####################

Description
Class Airplane

Attributes
NAME
N_O_AIRPLANES
PLANE _TYPE
Methods

Active

into

Repository Information
System
brauche
ichcreates
auch
the
Editor
Tag Library
Transport Organizer

zdemo

CREATE OBJECT r_airplane


EXPORING ...
IMPORTING ...

Name of airplane
Number of planes
Airplane type

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

SAP AG 2002

Drag & drop the class name: Instantiates an object.


Selecting and dragging a class name to the right automatically creates a CREATE OBJECT statement
with the whole interface of the constructor. You still have to add the call's actual parameters.

(C) SAP AG

BC401

12-17

Class Builder: CALL METHOD

Workbench

Edit

Goto

Utilities

Environment

System

Help

ABAP Editor: Report zdemo


Pattern

MIME Repository

Report

Knpre hier
Repository Information
System ich auch
brauche
Tag Library
Selecting and dragging into
Transport Organizer
the Editor creates CALL

zdemo

Active

Repository Browser Diese

Class/Interface

METHOD

ZCL_AIRPLANE_00

Object Name
ZCL_AIRPLANE_00
Attributes
NAME
N_O_AIRPLANES
PLANE _TYPE

*********************************************
* XY_00_airplane
*********************************************
* XY_00_airplane
class lcl airplane definition
START-OF-SELECTION.
#################################

Description
Class Airplane

Name of airplane
Number of planes
Airplane type

CALL METHOD
xxx->display_attributes

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

SAP AG 2002

Drag & drop the method name: Calls a method


Selecting and dragging a method to the right automatically creates a CALL METHOD statement with the
whole interface of the method. In this case you must also add the call's actual parameters and set the
call's reference variable.

(C) SAP AG

BC401

12-18

Global Classes and Interfaces (3)

Class
Class Builder
Builder
Working
Working with
with global
global classes
classes and
and interfaces
interfaces
Applied
Applied example
example

SAP AG 2002

(C) SAP AG

BC401

12-19

An applied example for the use of ABAP Objects is the standard output tool SAP Grid Control. It is
implemented in ABAP Objects and provides the user with a wide range of functions (for example sorting
data, reorganizing/hiding columns, totalling).
Principle of SAP Control Framework:
To use such a control the developer no longer has to re-implement functions in the control, but simply
specify the instances of the classes that contain these functions.
The exact procedure for using the SAP Grid Control will be discussed in the following.

(C) SAP AG

BC401

12-20

Including a Grid Control Instance in a Dialog Program

You require two classes for


using a SAP Grid Control

Screen
Area
1 CL_GUI_CUSTOM_CONTAINER
Public

Private

Custom
Container
Control
3 CL_GUI_ALV_GRID
Public

Private

ALV
Grid
Control

SAP AG 2002

To implement a SAP Grid Control, you must implement:


An instance of the container control
An instance of the displaying SAP Grid Control
The data retrieval
The display of data using a method call

An SAP container is capable of housing other controls (such as the SAP Grid Control, tree control,
picture control, splitter control, and so on). It manages these controls in a logical collection and provides
a physical area for visualization. Each control "lives" in a container. Because containers are themselves
controls, containers can be nested within one another. The container becomes the parent of its control.

Global classes are available for accessing the custom control and the SAP Grid Control. At runtime, an
object each of the class CL_GUI_CUSTOM_CONTAINER and the class CL_GUI_ALV_GRID is
created. These objects contain all necessary information for accessing the controls. For information on
the object types (classes) and the corresponding methods, refer to the online documentation.

(C) SAP AG

BC401

12-21

The control is displayed on a screen, the call of which is not shown in this example.
To create the object that communicates with the container control, it is sufficient to include the name of
the container area 'CONTAINER_1' on the screen, on which the container area is defined.
To create the object that communicates with the SAP Grid Control, you must include the reference
variable that refers to the object for the custom container. This is because the object for the SAP Grid
Control contains a reference variable that points to the container object as a private attribute. This
relationship tells the object, which container it should be included in.
To display data in a SAP Grid Control, it must be provided in an internal table. Then a method is called
that receives the content of the internal table and its structure. The name of this method id
set_table_for_first_display. If, while the program runs, only the content of the internal
table to be displayed changes, it is sufficient to call the method refresh_table_display with the
container area before the the screen is re-sent.

(C) SAP AG

BC401

12-22

Global Classes and Interfaces: Unit Summary

You are now able to:


Describe the difference between local and global
classes and interfaces
Create global classes and interfaces using the
Class Builder

SAP AG 2002

(C) SAP AG

BC401

12-23

Exercises
Unit: Global Classes and Interfaces
Topic: Creating Global Classes
At the conclusion of these exercises, you will be able to:
Use the Class Builder to process global classes and interfaces

A travel agency communicates with its business partners. Various hotels


are now also to be business partners.

Model solution: CL_HOTEL


CL_HOUSE
IF_PARTNERS

1-1

Create the global class ZCL_##_HOTEL in the Class Builder.

1-2

The class is to have the following attributes:


name
type STRING, private instance attribute
max_beds
type I, private instance attribute
n_o_hotel
type I, private static attribute

1-3

The class is to have the following methods:


constructor
with import parameters im_name and im_beds
display_attributes
for displaying the instance attributes of the class
display_n_o_hotels static method for displaying instances created

1-4

Implement these methods.

1-5

Activate and test your class using the Class Builder test tool.

(C) SAP AG

BC401

12-24

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

Optional:
Include the new class in the program with the airlines and car rental companies. Adjust the
sections that refer to the local interface lif_partners to suit the new global interface.

lcl_travel_agency
uses

zif_partners
implements

lcl_carrier

lcl_hotel

lcl_vehicles

lcl_airplane

...
4

lcl_car_rental

...

...

...

(optional)
Define an inheritance relationship in the Class Builder. Your hotel is to inherit from the
superclass ZCL_##_HOUSE. Tip: Construct the class ZCL_##_HOUSE copying the class
ZCL_##_HOTEL to ZCL_##_HOUSE and then making changes to this copy. The house
should only have an attribute name (protected) and the method display_attributes; delete all
superfluous components.
Finally, define the inheritance relationship between the house and the hotel.

(C) SAP AG

BC401

12-25

Solutions
Unit:

Global Classes and Interfaces

Topic:

Creating Global Classes

*&---------------------------------------------------------------------*
*& Report

SAPBC401_CLSS_MAIN_A

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

Global Class lcl_hotel is also a business partner of the

*&

travel agency

*&---------------------------------------------------------------------*
REPORT

sapbc401_clss_main_a.

TYPES: ty_fuel TYPE p DECIMALS 2,


ty_cargo TYPE p DECIMALS 2.
INCLUDE <icon>.
include sapbc401_vehd_j.
INCLUDE sapbc401_clss_a.
DATA: r_vehicle TYPE REF TO lcl_vehicle,
r_truck TYPE REF TO lcl_truck,
r_bus

TYPE REF TO lcl_bus,

r_passenger type ref to lcl_passenger_plane,


r_cargo type ref to lcl_cargo_plane,
r_carrier type ref to lcl_carrier,
r_rental type ref to lcl_rental,
r_agency type ref to lcl_travel_agency,
r_hotel type ref to cl_hotel.
START-OF-SELECTION.
*########################
******* create travel_agency *****************************************
CREATE OBJECT r_agency EXPORTING im_name = 'Fly&Smile Travel'.

(C) SAP AG

BC401

12-26

******* 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 CARRIER ********************************************
create object r_carrier exporting im_name = 'Smile&Fly-Travel'.
***** Passenger Plane ********************************************
CREATE OBJECT r_passenger EXPORTING
im_name = 'LH BERLIN'
im_planetype = '747-400'
im_seats = 345.
***** cargo Plane ************************************************
CREATE OBJECT r_cargo EXPORTING
im_name = 'US HErcules'
im_planetype = '747-500'
im_cargo = 533.
******* create hotel *****************************************
create object r_hotel exporting im_name = 'HOLIDAY INN'
im_beds = 345.
******* show attributes of all partners of travel_agency ******
r_agency->display_agency_partners( ).

(C) SAP AG

BC401

12-27

Special Techniques

Contents:
Abstract and final classes
Visibility of constructors
Friends
Object Services

SAP AG 2002

(C) SAP AG

BC401

13-1

Special Techniques: Unit Objectives

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


Create and describe abstract and final classes
Explain the visibility criteria of constructors
Describe the friend concept
Describe the persistence service of Object
Services

SAP AG 2002

(C) SAP AG

BC401

13-2

Special Techniques: Integration in Course Content

chniques
Special Te d Interfaces
an
sses
Global Cla
Events

Interfaces
Casting

and
Data Types
ts in
Data Objec
Detail

e
Inheritanc
ing
Programm
nt
Orie ed
of Objectes
pl
ci
rin
P
n
and Desig
Analysis
ing
Programm
d
te
Orien
to Objectn
tio
uc
Introd
al
Using Intern
Tables

rams
Calling Prog
Data
and Passing

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

13-3

Special Techniques (1)

Abstract
Abstract and
and final
final classes
classes
Visibility
Visibility of
of constructors
constructors
The
The friend
friend concept
concept
Persistent
Persistent objects
objects

SAP AG 2002

(C) SAP AG

BC401

13-4

Abstract Classes

Abstract classes themselves cannot be instantiated (although


their subclasses can)

References to abstract classes can refer to instances of subclasses

Abstract (instance) methods are defined in the class, but not


implemented

They must be redefined in subclasses

CLASS lcl_vehicle DEFINITION ABSTRACT.


PUBLIC SECTION.
METHODS estimate_fuel_consumption ABSTRACT
IMPORTING ...
ENDCLASS.

Class cannot
be instantiated

Method not
implemented in this
class
SAP AG 2002

It is not possible to instantiate objects of an abstract class However, this does not mean that references to
such a class are not useful. On the contrary, they are very useful, since they can (and must) refer to
instances in subclasses of the abstract class at runtime. The CREATE OBJECT statement is extended in
this context. You can specify the class of the instance to be created explicitly:
CREATE OBJECT <RefToAbstractClass> TYPE <NonAbstractSubclassName>.
Abstract classes are normally used as an incomplete blueprint for concrete (that is, non-abstract)
subclasses, for example to define a uniform interface.
Abstract instance methods are used to specify particular interfaces for subclasses, without having to
immediately provide implementation for them. Abstract methods need to be redefined and thereby
implemented in the subclass (here you also need to include the corresponding redefinition statement in
the DEFINITION part of the subclass).
Classes with at least one abstract method are themselves abstract.
Static methods and constructors cannot be abstract (they cannot be redefined).

(C) SAP AG

BC401

13-5

Final Classes

Final classes cannot have subclasses

CLASS lcl_truck DEFINITION FINAL


INHERITING FROM lcl_vehicle.
...
ENDCLASS.

vehicle

truck

...

bus

...

...

Final methods cannot be redefined in subclasses

CLASS lcl_bus DEFINITION INHERITING FROM lcl_vehicle.


PUBLIC SECTION.
METHODS estimate_number_of_free_seats FINAL.
ENDCLASS.

SAP AG 2002

A final class cannot have subclasses, and can protect itself in this way against (uncontrolled)
specialization.
A final method in a class cannot be redefined in a subclass, and can protect itself in this way against
(uncontrolled) redefinition.
Some features:
A final class implicitly only contains final methods. In this case, you cannot enter FINAL explicitly
for these methods.
Methods cannot be both final and abstract.
Classes, on the other hand, that are both abstract and final can be useful: Only static components
can be used.

(C) SAP AG

BC401

13-6

Special Techniques (2)

Abstract
Abstract and
and final
final classes
classes
Visibility
Visibility of
of constructors
constructors
The
The friend
friend concept
concept
Persistent
Persistent objects
objects

SAP AG 2002

(C) SAP AG

BC401

13-7

Who Can Instantiate Classes?

The usability of classes can be restricted:


CLASS cl_class DEFINITION ...

CREATE PUBLIC
Every user (client) can create instances of a class
(default setting)

CREATE PROTECTED
Only the class itself and all its subclasses can create instances of this
class

CREATE PRIVATE
Only the class can create instances of itself

This implicitly controls the visibility of the


class
Possible use:
Singleton concept

(1) lcl_singleton
Public

Private
r_singl

Client

get_
singleton

SAP AG 2002

If you want to ensure that not every user (client) can instantiate a class, you can use the following
additions to restrict the visibility area of the constructor and hence limit the use of the class. (The
following additions must be preceded by CLASS ... DEFINITION.)
The CREATE PUBLIC addition is implicitly available for every class definition, provided neither
of the other two CREATE additions is used. It defines the default that every user can create
instances of a known class.
The optional additions CREATE PROTECTED and CREATE PRIVATE, on the other hand, have
the effect that not every user can create instances of a class. In the case of CREATE PROTECTED,
only subclasses of the class or the class itself and, in the case of CREATE PRIVATE, only the class
itself can create instances of the class.
Therefore, the additions CREATE PROTECTED and CREATE PRIVATE allow you to control
instance creation and, for example, are a prerequisite for the instance management of persistent
objects, for which the uniqueness of objects must be ensured. (Persistent objects will be discussed
in more detail later.)

If it is to be impossible to instantiate a class more than once (for example, because it serves as a data
administrator or data container), you can use the singleton concept. The class is defined with the addition
CREATE PRIVATE and FINAL and instantiated using its static constructor.
A public static component could then make the reference to the class available to an external user.

(C) SAP AG

BC401

13-8

Special Techniques (3)

Abstract
Abstract and
and final
final classes
classes
Visibility
Visibility of
of constructors
constructors
The
The friend
friend concept
concept
Persistent
Persistent objects
objects

SAP AG 2002

(C) SAP AG

BC401

13-9

In rare cases, classes have to work together so closely that they need access to their protected and private
components. To avoid making these components available to all users, there is the concept of friendship
between classes.

A class can provide friendship to other classes and interfaces (and hence all classes that implement the
interface). To do this you use the FRIENDS additions to the CLASS statement, in which all classes and
interfaces that are to be provided friendship are listed. Friends are allowed to access the protected and
private components of the class providing the friendship and can always create instances of this class,
regardless of the CREATE addition to the CLASS statement.

In principle, providing friendship is one-sided: A class providing friendship is not automatically a friend
of its friends. If a class providing friendship wants to access the non-public components of a friend, this
friend has to explicitly provide friendship to it.

Classes that inherit from friends and interfaces that contain a friend as a component interface also
become friends. Therefore, extreme caution is advised when providing friendship. The higher up a friend
is in the inheritance tree, the more subclasses can access all components of a class providing friendship.
However, providing friendship, unlike the attribute of being a friend, is not inherited. A friend of a
superclass is therefore not automatically a friend of its subclasses.

(C) SAP AG

BC401

13-10

Special Techniques (4)

Abstract
Abstract and
and final
final classes
classes
Visibility
Visibility of
of constructors
constructors
The
The friend
friend concept
concept
Persistent
Persistent objects
objects

SAP AG 2002

(C) SAP AG

BC401

13-11

The persistence service helps the programmer to work object-oriented with data in relational databases.

In principle, ABAP programs work with data and objects that exist(s) in the internal session at runtime.
They are transient when the program is stopped. If this data is to be stored program-independently, that
is persistently, it must be stored in the database. (You could also use files on operating system level.)

In ABAP Objects, this is done using the OPEN SQL interface.


To be able to work with ABAP Objects persistently, the persistence service was introduced with SAP
R/3 Basis Release 6.10. Objects and their attributes can be written to the database and re-imported.

(C) SAP AG

BC401

13-12

Features of the Persistence Service

Objects of a running ABAP program are transient

The persistence service allows you to work with persistent objects

Persistent classes are created


in the Class Builder

Create Class CL_PERSISTENT_CLASS


Class Type
Normal ABAP Class
Exception Class
Persistent Class

...

Persistence service tasks

Loading the objects from the database

Managing changes to the objects

Storing the objects in the database

SAP AG 2002

To use the persistence service for objects, their classes must be created as so-called persistent classes in
the Class Builder.

The term persistent class indicates that the objects of the class and their state are managed by the
persistence service. In ABAP programs, objects of these classes are, for example, not created using the
normal statement CREATE OBJECT, but instead using a method of the persistence service that ensures
the correct initialization.

When creating a persistent class, the Class Builder automatically creates a corresponding class, the so
called class actor or agent, the methods of which are used to manage the objects of the persistent class.

As well as their unique identity, persistent classes can also contain so-called key attributes, which the
persistence service uses to ensure the uniqueness of the persistent objects' contents.

(C) SAP AG

BC401

13-13

Class Agent

Within the persistence service, the class actor or class agent manages
the persistent objects

The agent provides a range of services (methods), which are used to


manage the objects and the encapsulated data

Technically, the agent is a singleton, which is addressed using the public


static attribute AGENT

...

DATA: r_carrier TYPE REF TO cl_carrier,


r_agent
TYPE REF TO ca_carrier,
carrname TYPE
s_carrname.
r_agent = ca_carrier=>agent.

The agent,
a singleton of the class
CA_CARRIER and
friend of the persistent
class CL_CARRIER

TRY.
r_carrier = r_agent->get_persistent( i_carrid = 'LH' ).
carrname
= r_carrier->get_carrname( ).
WRITE: 'LH: ', carrname.
CATCH cx_os_object_not_found.
ENDTRY.
SAP AG 2002

For every persistent class cl_persistent, the Class Builder generates two further classes
ca_persistent and cb_persistent. These classes make up the class-specific part of the
persistence service.

ca_persistent is the so-called class actor (or agent), which is used to manage the managed object
of the class cl_persistent, and in which all actual database accesses take place. The class actor
inherits the relevant methods from the abstract superclass cb_persistent. The programmer can
extend the class actor and redefine the methods (especially the database accesses). The superclass
cb_persistent cannot be changed. The class actor is a friend of the managed class. It has the
attribute CREATE PRIVATE and exactly one instance of the class actor is created when it is first
accessed.

The static attribute AGENT is a reference variable with the type of the class ca_persistent. When
the attribute is first accessed in an ABAP program, the static constructor of the class ca_persistent
creates exactly one instance of this class, which points to the attribute AGENT. This object is part of the
persistence service and its methods are used to manage the object of the persistent class. For each
program there is only one object of the class ca_persistent, because you cannot create objects from
outside using CREATE OBJECT.

The class actor manages one or more objects of the relevant persistent class. These objects must have
different keys.

(C) SAP AG

BC401

13-14

Special Techniques: Unit Summary

You are now able to:


Create and describe abstract and final classes
Explain the visibility criteria of constructors
Describe the friend concept
Describe the persistence service of Object
Services

SAP AG 2002

(C) SAP AG

BC401

13-15

Exercises - optional
Unit: Special Techniques
Topic: Singleton Classes
At the conclusion of these exercises, you will be able to:
Create a singleton; requirement for next exercise

Model solution: CL_SINGLETON


SAPBC401_SPCS_MAIN_A

(Advanced)
Create the global class ZCL_##_SINGLETON in the Class Builder.
The following must be specified for the class:
1-1

You must be able to be instantiate the class only once. (Tip: Instantiation should take
place automatically when the class is first accessed.)

1-2

Instantiation only takes place within the class.

1-3

The class has a static reference variable r_singleton that refers to the instantiated
object.

1-4

The class has a static reference variable r_singleton that refers to the instantiated
object.

In the main program ZBC401_##_MAIN_SPECIAL, instantiate the singleton class


ZCL_##_SINGLETON by calling the get_singleton method.
2-1

Why must the get_singleton method in this example be static?

2-2

Verify your blueprint by calling get_singleton several times. (Debug.) When does
instantiation take place and how often?

(C) SAP AG

BC401

13-16

Exercises - optional
Unit: Special Techniques
Topic: Concluding Project Exercise
At the conclusion of these exercises, you will be able to:
Create a friends relationship and access the data of a class providing
the friendship (a singleton) from the befriended class
(Note that the friends concept is mainly used in bigger projects with
more complex classes)
Model solution: CL_AGENCY
SAPBC401_SPCS_MAIN_B

(Advanced)
Use your singleton and the main program from the last exercise.
3-1

Add a static attribute connection_list (with type TY_CONNECTIONS, that is an itab)


to the singleton class.

3-2

When instantiating the singleton, this internal table is to be automatically filled with
the flight connections from the table SPFLI.

Create a global class ZCL_##_AGENCY, which is to be provided friendship by the singleton.


4-1

Define and implement a constructor for ZCL_##_AGENCY.


In the constructor, the private attribute of the class name is to be initialized.

4-2

This class is to have a public method get connection.


4-2-1 Import parameter:
im_carrid and im_connid (types: S_CARR_ID and S_CONN:ID)
4-2-2 Export parameter:
A structure with line type SPFLI
Name the export parameter ex_connection.

(C) SAP AG

BC401

13-17

4-2-3 In the method, the internal table of the class providing the friendship is to be
accessed in a single record access. (READ TABLE...)
If the requested record does not exist, it is sufficient in this example to display
an appropriate message using the WRITE statement.
5

Go back to the singleton class.


Here, provide friendship to the class ZCL_##_AGENCY.

In your main program, instantiate the class ZCL_##_AGENCY.


The singleton should have been instantiated in the last exercise.
There, the internal table with the flight connections is already filled.
6-1-1 Execute the get_connection method of ZCL_##_AGENCY requesting a flight
connection that exists in the SPFLI table.
(for example LH / 0400)

friend
(3) lcl_agency
(1) cl_singleton
get_
connection

connection_
list

(C) SAP AG

BC401

13-18

Solutions - optional
Unit:

Special Techniques

Topic:

Singleton Classes

*&---------------------------------------------------------------------*
*& Report

SAPBC401_spcS_MAIN_A

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

Work with singleton:

*&

The singleton class consists of a static pointer r_singleton

*&

pointing to the class itself; the class is final and has

*&

the attribute create private.

*&

in the class-constructor the class is instantiated via

*&

this reference. The static method get_singleton passes the

*&

reference to the outside world so that the singleton can be used!

*&---------------------------------------------------------------------*
REPORT

sapbc401_spcs_main_a.

DATA: r_single type ref to cl_singleton.


START-OF-SELECTION.
*########################
r_single = cl_singleton=>get_singleton( ).

(C) SAP AG

BC401

13-19

Solutions - optional
Unit:

Special Techniques

Topic:

Concluding Project Exercise

*&---------------------------------------------------------------------*
*& Report

SAPBC401_spcS_MAIN_B

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

Practice with singleton & friends

(show package concept )

*&
*&

The class cl_agency is a friend of the singleton;

*&

cl_agency works directly with the private data of the singleton

*&

the method get_connection reads single records out of an

*&

internal table of the singleton; so the singleton acts as a kind

*&

of data-container. cl_agency uses this data in the singleton

*&

directly. (performance aspects, package-concept...)

*&---------------------------------------------------------------------*
REPORT

sapbc401_spcs_main_b.

DATA: r_single type ref to cl_singleton,


r_agency type ref to cl_agency,
rec type spfli.

START-OF-SELECTION.
*########################
r_single = cl_singleton=>get_singleton( ).
create object r_agency exporting im_name = 'Agency'.
r_agency->get_connection( exporting im_carrid = 'LH'
im_connid = '0400'
importing ex_connection = rec ).
write: / rec-carrid, rec-connid.
(C) SAP AG

BC401

13-20

(C) SAP AG

BC401

13-21

Exception Handling

Contents:
Predefined exceptions and exceptions you define
yourself
Raising, handling, and passing along exceptions

SAP AG 2002

(C) SAP AG

BC401

14-1

Exception Handling: Unit Objectives

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


Create your own exception classes
Raise exceptions in a program
Handle exceptions
Pass exceptions along

SAP AG 2002

(C) SAP AG

BC401

14-2

Exception Handling: Integration in Course Content

Handling
Exception
chniques
Special Te
aces
and Interf
es
ss
Global Cla
Events
Interfaces
Casting

and
Data Types
ts in
Data Objec
Detail

e
Inheritanc
ming
ed Program
nt
Object-Orie
of
es
pl
ci
Prin
n
and Desig
Analysis
ing
rogramm
P
d
te
en
Object-Ori
to
n
tio
Introduc
al
Using Intern
Tables

rams
Calling Prog
Data
and Passing

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

14-3

We use the term exception to refer to a situation that arises while an ABAP program is being executed,
where there is no point in continuing to run the program in the normal way. Since SAP R/3 Basis
Release 6.10, exceptions and exception handling is based on the exception classes concept. This concept
includes the functions of the concepts that preceded it but also enhances (and thus replaces) them.
Class-based exceptions are raised either using the ABAP statement RAISE EXCEPTION or by the
ABAP runtime environment. For example, if the program tries to divide by zero the runtime
environment raises the exception. You can, however, ascertain that this situation has arisen using a query
in the ABAP program. From there, you can then raise an exception yourself.
You can define exception classes yourself, but there is already a range of predefined exception classes in
the system. In an exception situation, an exception is represented by an exception object - that is, an
instance of an exception class. The attributes of each exception object can contain information about the
error situation.
The use of class-based exceptions is not limited to object-oriented contexts. Class-based exceptions can
be raised and handled in all ABAP processing blocks. In particular, the catchable runtime errors used
until now can be handled as class-based exceptions.
If a class-based exception occurs, the system interrupts the normal program flow and tries to navigate to
a suitable handler. If it cannot find a handler, a runtime error occurs.

(C) SAP AG

BC401

14-4

Exception Classes: The Inheritance Hierarchy


cx_root
textid
kernel_errid
...
get_text
get_source_position

cx_no_check

cx_dynamic_check

cx_sy_arithmetic_error

cx_static_check

cx_sy_move_cast_error

cx_sy_arithmetic_overflow
SAP AG 2002

All exception classes are derived from the one of the classes CX_NO_CHECK,
CX_DYNAMIC_CHECK, or CX_STATIC_CHECK, themselves derived from the common superclass
CX_ROOT. The way in which exception classes are assigned to one of these three paths in the hierarchy
defines how the associated exceptions are passed along. (This will be discussed in more detail later in
this unit.)
All exception classes begin with the prefix CX_. In general, they are defined globally in the ABAP
Workbench Class Builder. However you can also define local exception classes.
The root class CX_ROOT contains two predefined methods that are inherited by the other classes. The
GET_SOURCE_POSITION method returns the program name, include name (if relevant), and line
number in the source code where the exception occurred. The GET_TEXT method returns an exception
text of a class in the form of a string. You can assign several texts to each class. You can then specify
which text is to used when an exception is raised by passing an identifier to the IMPORTING parameter
TEXTID of the instance constructor.
All exception classes inherit the KERNEL_ERRID attribute from CX_ROOT. This attribute contains the
name of the appropriate runtime error if the exception was raised by the runtime environment - such as
COMPUTE_INT_ZERODIVIDE if the program tries to divide by zero. If the exception is not listed, a
runtime error occurs.

(C) SAP AG

BC401

14-5

Handling Exceptions

TRY.
...
CATCH cx_...

cx_...

...

[INTO r_exc1].

Code whose
exceptions (if
any) are to be
handled

...
CATCH cx_...

... [INTO r_exc2].

...
CLEANUP.

Handlers
Handlers for
for the
the
specified
specified exception
exception
classes
classes and
their
and
their
subclasses
subclasses

...
ENDTRY.

Block for "tidying up"


if there is no handler
available in the TRYENDTRY structure

SAP AG 2002

Like all ABAP control structures, TRY-ENDTRY structures can be nested. Thus the TRY block, CATCHblocks, and the CLEANUP block in particular can contain complete TRY-ENDTRY structures
themselves.
The TRY block contains the application code that is to handle the exceptions. If an exception occurs in
the TRY block the system searches first for a CATCH statement (which will handle the exception) in the
same TRY-ENDTRY structure and then step by step outwards in all the enclosing TRY-ENDTRY
structures. If it finds one, it navigates to this handler. If it cannot find a handler but the TRY-ENDTRY
structure is in a procedure, it then tries to pass the exception along to the calling program. (This will be
discussed in more detail later.)
A CATCH block contains the exception handler that is executed if a specified exception has occurred in
the TRY block in the same TRY-ENDTRY structure. After the CATCH statement, you can specify as
many exception classes as you wish. In this way, you define an exception handler for all these
exception classes and their subclasses. After an exception occurs, the system searches through the listed
exception handlers in the order specified. It then executes the first exception handler whose CATCH
statement contains the relevant exception class or one of its superclasses.
In some cases, the system cannot find a handler for an exception within a specific TRY-ENDTRY
structure but the exception is handled in a surrounding TRY-ENDTRY structure or passed along to a
calling program. If this occurs, a CLEANUP block is executed before leaving the TRY-ENDTRY
structure.

(C) SAP AG

BC401

14-6

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 object reference to the exception object is stored in the reference variable r_exc. Using r_exc
and the functional method get_text, the handler accesses the exception text for this exception object
and stores in the string variable text.
To display exception texts as messages, the MESSAGE statement has been extended so that you can use
any string:
MESSAGE <string> TYPE <type>.
As well as the message <string> that will be displayed, you must display the message type <type>,
either as a literal or in a field.
If the value range for data type i is not exceeded, no exception is raised and the TRY block is processed
completely. The program then continues executing after the keyword ENDTRY.
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.
The keyword documentation for each keyword lists the exception classes whose exceptions may occur
when the appropriate ABAP statement is executed.

(C) SAP AG

BC401

14-7

Example: Using Your Own Exceptions


CLASS lcl_airplane DEFINITION.
...
METHODS get_technical_attributes
IMPORTING im_type
TYPE saplane-planetype
EXPORTING ex_weight TYPE s_plan_wei
ex_tankcap TYPE s_capacity.
...
ENDCLASS.
CLASS lcl_airplane IMPLEMENTATION.
...
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.

Adapting the program:


If there is no table entry available,
raise and handle an exception you
have written

SAP AG 2002

The above program source code shows the method get_technical_attributes of the class
lcl_airplane, which was implemented in an earlier exercise in this training course. It receives an
airplane type as an import parameter and returns its weight and tank capacity as export parameters.
The relevant information is read from the database table saplane. If the airplane type passed is not
available in this table (that is, if sy-subrc <> 0), the values 100.000 and 10.000 respectively are
assigned to the export parameters ex_weight and ex_tankcap. We will now change this behavior:
If an airplane type is not entered in the table, an exception that we have defined should be raised and
handled appropriately.

(C) SAP AG

BC401

14-8

Creating Your Own Exception Classes

Workbench

Edit

Goto

Utilities

Environment

System

Pattern

privat
ZCX_WRONG_PLANETYPE
protected
CX_STATICS_CHECK
Inherits From
public
abstract
Class Type:
Usual ABAP Class
Exception Class
Persistent Class
Class

Package
ZBC401_00

ZBC401_00
Class Library
Classes

Pretty Printer
Report

MIME Repository
Object Navigator Diese Knpre hier
Repository Infosystem
brauche ich auch
Tag Library
Transport Organizer

Object Name

Help

Description

Final Class
Only modeled

SAP AG 2002

Exceptions are represented by objects that are instances of exception classes. Defining an exception is
thus synonymous with creating an exception class.
Exception classes are generally defined globally. For special exceptions that will only occur within a
single ABAP program however, you can also define local exception classes.
Global exception classes are defined and managed in the Class Builder. When you create a new class, if
you use the correct naming convention (prefix ZCX_) and choose the class type Exception Class, the
system automatically displays the Exception Builder instead of the Class Builder.
The Exception Builder offers all the functions you need to create exception classes and generates
specified components that cannot be changed. When you create an exception class, you must also
specify which category of exception it will be - that is, whether it is derived from
CX_STATIC_CHECK, CX_DYNAMIC_CHECK or CX_NO_CHECK.

(C) SAP AG

BC401

14-9

Maintaining Your Own Attributes and Exception


Texts
Class

Edit

Goto

Utilities

Environment

System

Help

Class Builder: Change Class ZCX_WRONG_PLANETYPE


Class Documentation
ZCX_WRONG_PLANETYPE

Class Interface

Implemented/Active

Attributes Texts

Your own attributes


provide the user with
Attributeadditional
Type
information
CX_ROOT

Const..

TEXTID

Instan..

Filter
Nu

Re

Typing

Pub..

Type

SOTR_CONC

Pub..

Type

SOTR_CONC

Type Re

CX_ROOT

Type

S380ERRID

Type

SAPLANE-PLANETYPE

PREVIOUS

Instan..

Pub..

KERNEL_ERRID

Instan..

Pub..

PL_TYPE

Instan..

Pub..

Associated Type

Exception text
used to describe
exception situation
in more detail

Exception ID

Text

CX_ROOT

An exception occurred

ZCX_WRONG_PLANETYPE This airplane type is unknown


SAP AG 2002

The methods are all inherited from CX_ROOT. You can also add your own methods. The instance
constructor is generated automatically.
You can also define your own attributes, whose contents specify the exception in more detail. The
Exception Builder ensures that the instance constructor has identically-named IMPORTING parameters
for these attributes.
The exception texts of global classes are defined on the Texts tab of the Exception Builder. They can
contain parameters. To do this, use the elementary attributes of the exception class by enclosing their
name in ampersands ('&') in the exception text.
The exception texts of global exception classes are stored in their different translations in the Open Text
Repository (OTR). Note that several texts can be assigned to a single class. You assign a text to an
exception using the TEXTID attribute, which contains the globally unique ID of the text object within an
exception object at runtime. The method GET_TEXT then exports this text, replaces any text parameters
with the contents of the relevant attributes as necessary, and returns the text as a character string.
For each global class, the Exception Builder generates a default text whose name matches the class
name. (The name of this default text cannot be changed.) You need to create names for other texts. For
each text, the Exception Builder generates a static constant that contains the associated ID in the OTR.
You can then specify which text is to used when an exception is raised by passing an identifier to the
IMPORTING parameter TEXTID of the instance constructor. If you do not specify a text, the default
text is used.

(C) SAP AG

BC401

14-10

If the airplane type passed to the method has not been stored in the table saplane, the exception we
defined previously, zcx_wrong_planetype, is raised. In addition, a TRY-ENTRY control structure is
implemented that is only processed if sy-subrc <> 0.
The TRY block contains the application code that is to handle the exceptions. When the exception is
raised, the IMPORTING parameter pl_type of the instance constructor is filled. (This parameter is
automatically generated by the Exception Builder.) Using this parameter, the program then assigns the
value of the airplane type to the identically-named attribute.
The exception that has been raised is handled in the CATCH block. The reference to the exception object
is stored in the reference variable r_exc, which was created as a local data object in the method (TYPE
REF TO cx_root).
Since the IMPORTING parameter TEXTID of the instance constructor was not filled when the
exception was raised, the default text generated when the exception class was created is addressed using
the functional method get_text. The method GET_TEXT then exports this text, replaces the text
parameter with the contents of the attribute pl_type, and returns the text as a character string.
The returned text is stored in the local data object text, which has the type string. The text is then
displayed as an information (type I) message.

(C) SAP AG

BC401

14-11

Passing Exceptions Along


CLASS class DEFINITION.
...
METHODS meth IMPORTING <im_parameter>
EXPORTING <ex_parameter>
RAISING
cx_exception.
...
ENDCLASS.

REPORT propagate_exceptions.
...
DATA r_obj TYPE REF TO class.
...

CLASS class IMPLEMENTATION.


...
METHOD meth.
...
RAISE EXCEPTION TYPE cx_exception.
ENDMETHOD.
ENDCLASS.

TRY.
r_obj->meth( EXPORTING ...
IMPORTING ... ).
CATCH cx_exception.
...

Exceptions that occur in


procedures do not necessarily
need to be handled there; they
can be passed along to the
calling program.

ENDTRY.

SAP AG 2002

Exceptions that occur in procedures (methods, function modules, or subroutines) do not necessarily need
to be handled there; they can be passed along to the calling program. The calling program can then
handle the exception itself or also pass it along to its own caller, and so on.
The highest levels to which an exception can be passed are processing blocks without local data areas that is, event blocks or dialog modules. The exceptions passed along by the called procedures must be
dealt with there, as must any exceptions raised within this processing block itself. Otherwise a runtime
error occurs.
To pass along an exception from a procedure, you generally use the RAISING addition when defining
the procedure interface.
In methods of local classes and subroutines, specify the RAISING addition directly when defining the
procedure (METHODS meth ... RAISING cx_... cx_..., FORM form ... RAISING cx_... cx_...). After
RAISING, list the exception classes whose objects are to passed along.
In methods of global classes, the exception classes whose objects are to be propagated are entered in the
exception table of the method in the Class Builder. Check the Exception Class field in this exception
table. Similarly, exceptions raised by function modules are passed along by being entered in the
Function Builder.

(C) SAP AG

BC401

14-12

Example: Passing Exceptions Along


CLASS lcl_airplane DEFINITION.
METHODS display_attributes.
METHODS get_technical_attributes
IMPORTING im_type
TYPE saplane-planetype
EXPORTING ex_weight
TYPE s_plan_wei
ex_tankcap
TYPE s_capacity
RAISING
zcx_wrong_planetype.
ENDCLASS.
METHOD display_attributes.
DATA: r_exc TYPE REF TO cx_root,
text TYPE string.
...
TRY.
get_technical_attributes(
EXPORTING im_type = planetype
IMPORTING ex_weight = weight
ex_tankcap = cap ).
WRITE: /'Gewicht:'(003), weight,
'Tankkapazitt:'(004), cap.
CATCH zcx_wrong_planetype INTO r_exc.
text = r_exc->get_text( ).
MESSAGE text TYPE 'I'.
ENDTRY.
ENDMETHOD.

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 zcx_wrong_planetype
EXPORTING pl_type = im_type.
ENDIF.
ENDMETHOD.

SAP AG 2002

As in the previous example, the exception we have defined (zcx_wrong_planetype) is raised if the
airplane type passed to the method get_technical_attributes is not stored in the table saplane. Here,
however, the exception is only raised in the method get_technical_attributes, not handled there.
To pass the exception along to the caller of the method, we enter it after the RAISING keyword.
Now, the caller - that is, the method display_attributes - handles the exception. For this purpose, we
have implemented a TRY-ENDTRY control structure in this method. The method
get_technical_attributes is now called in the TRY block of this control structure.
If the exception is raised in the method get_technical_attributes, the program continues by handling this
exception. That is, the method get_technical_attributes is terminated and the appropriate CATCH block
is processed within the caller. Note in particular that the program no longer executes the WRITE
statements entered in the TRY block after get_technical_attributes is called.

(C) SAP AG

BC401

14-13

Exceptions That Must Be Declared


cx_root

cx_no_check

You can handle these


exceptions. If you do not,
they are passed along
automatically. You cannot
pass them explicitly using
the RAISING addition

cx_dynamic_check

You must handle these


exceptions or pass them
along explicitly using the
RAISING addition

Not part of syntax check

cx_static_check

You must handle


these exceptions or
pass them along
explicitly using the
RAISING addition

Part of syntax check

Not part of syntax check

SAP AG 2002

Subclasses of CX_STATIC_CHECK: The relevant exception must either be handled, or passed along
explicitly using the RAISING addition. The syntax check ensures that this is the case. At present, only
exceptions you define yourself for error situations in the application code are subclasses of
CX_STATIC_CHECK.
Subclasses of CX_DYNAMIC_CHECK: The relevant exception does not have to be declared. If such an
exception occurs at runtime, just as with subclasses of CX_STATIC_CHECK, it must either be handled
or passed along explicitly using a RAISING addition. However, this is not checked in the syntax check.
If such an exception occurs at runtime and is not either handled or passed along, a runtime error occurs.
Most predefined exceptions with the prefix CX_SY_... for error situations in the runtime environment
are subclasses of CX_DYNAMIC_CHECK.
Subclasses of CX_NO_CHECK: These exceptions cannot be declared. These exceptions can be handled.
Otherwise they are automatically passed along. The syntax check never finds an error here. All
exceptions of the category CX_NO_CHECK that are not handled in the call hierarchy are automatically
passed to the top level, If they are not caught there, they cause a runtime error. Some predefined
exceptions with the prefix CX_SY_... for error situations in the runtime environment are subclasses of
CX_NO_CHECK.

(C) SAP AG

BC401

14-14

Exception Handling: Unit Summary

You are now able to:


Create your own exception classes
Raise exceptions in a program
Handle exceptions
Pass exceptions along

SAP AG 2002

(C) SAP AG

BC401

14-15

Exception Handling Exercise 1


Unit: Exception Handling
Topic: Defining, raising, propagating, and catching
class-based exceptions
At the conclusion of these exercises, you will be able to:
Define exception classes
Raise class-based exceptions
Pass exceptions along
Catch class-based exceptions
Improve your program so that, when the airplane attributes are
displayed, an error text is displayed instead of the default values
if the airplane type is invalid.
Implement this using the class-based exceptions concept.
Program: ZBC401_##_RAISE_TRY
Template: SAPBC401_EVES_MAIN_8B
Model solution: SAPBC401_EXCS_RAISE_TRY
## is your two-digit group number
1-1

Copy your solution to the last exercise from the unit Events, or the corresponding
model solution SAPBC401_EVES_MAIN_B, with all their includes. Give them the
new names ZBC401_##_RAISE_TRY, ZBC401_##_RAISE_TRY_CL1, and
ZBC401_##_RAISE_TRY_CL2.

1-2

Define a global exception class. (We suggest the name


ZCX_##_INVALID_PLANETYPE.)
Choose the appropriate superclass so that the system performs a syntax check to ensure
that, after the relevant exception is raised, it is either handled or passed explicitly along
using a RAISING addition.
Add an attribute for the airplane type (suggested name: PLANETYPE) and assign the
type S_PLANETYPE to it.
Create a default error message that can be enhanced dynamically to include the airplane type.

1-3

(C) SAP AG

Raise the exception in the get_technical_attributes method of your local


class lcl_airplane.
Add a RAISING addition to the definition part of the method, so that the exception can
be passed along.
BC401

14-16

1-4

(C) SAP AG

Catch the exception in the display_attributes method of your local class


lcl_airplane.
To do this, you will need a local reference to the exception instance (suggested name:
r_exception). Assign a type to this reference using the superclass CX_ROOT.
Read the error text from the exception instance using the get_text method. To do
this you will need an auxiliary variable of the type string (suggested name
exc_text).

BC401

14-17

Exception Handling Solution 1


Unit: Exception Handling
Topic: Defining, propagating, and raising events

Model solution: Include BC401_EXCS_RAISE_TRY_CL2.


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

Include

BC401_EXCS_RAISE_TRY_CL2

*&---------------------------------------------------------------------*
...
*------------------------------------------------------------------*
*

CLASS lcl_airplane DEFINITION

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

TYPE string

im_planetype TYPE saplane-planetype,


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

TYPE saplane-planetype

EXPORTING ex_weight

TYPE s_plan_wei

ex_tankcap
RAISING
DATA: name
(C) SAP AG

TYPE s_capacity

cx_bc401_invalid_planetype.

TYPE string,
BC401

14-18

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 des Flugzeugs'(001), AT pos_1 name,
/ 'Type of airplane: '(002), AT pos_1 planetype.
* handle exception in case of invalid planetype:
TRY.
get_technical_attributes( EXPORTING im_type = planetype
IMPORTING ex_weight = weight
ex_tankcap = cap ).
WRITE: / 'Gewicht:'(003), weight,
'Tankkap:'(004), cap.
CATCH cx_bc401_invalid_planetype INTO r_exception.
exc_text = r_exception->get_text( ).
WRITE: / exc_text COLOR COL_NEGATIVE.
ENDTRY.
ENDMETHOD.

"display_attributes

METHOD display_n_o_airplanes.
...
(C) SAP AG

BC401

14-19

ENDMETHOD.

"display_n_o_airplanes

METHOD get_technical_attributes.
SELECT SINGLE weight tankcap FROM saplane
INTO (ex_weight, ex_tankcap)
WHERE planetype = im_type.
IF sy-subrc <> 0.
RAISE EXCEPTION TYPE cx_bc401_invalid_planetype
EXPORTING planetype = im_type.
ENDIF.
ENDMETHOD.
ENDCLASS.

(C) SAP AG

"get_technical_attributes
"lcl_airplane IMPLEMENTATION

BC401

14-20

Dynamic Programming

Contents:
Dynamic attributes
Data reference variables
Field symbols
Runtime Type Identification (RTTI)

SAP AG 2002

(C) SAP AG

BC401

15-1

Dynamic Programming: Unit Objectives

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


Use dynamic attributes in suitable ABAP
statements
Use data objects generated at runtime
Ascertain the attributes of data objects at runtime

SAP AG 2002

(C) SAP AG

BC401

15-2

Dynamic Programming:
Integration in Course Content

Dynamic
ing
Programm

Exception

handling

chniques
Special Te
Interfaces
sses and
Global Cla
Events
Interfaces
Casting

and
Data Types
ts in
Data Objec
Detail

e
Inheritanc
ing
Programm
nt
Orie ed
of Objectes
pl
ci
rin
P
n
and Desig
Analysis
ing
Programm
d
te
Orien
to Objectn
tio
uc
Introd
al
Using Intern
Tables

rams
Calling Prog
Data
and Passing

rview
Course Ove

SAP AG 2002

(C) SAP AG

BC401

15-3

Dynamic Programming (1)

Field
Field Symbols
Symbols in
in Detail
Detail
Dynamic
Dynamic Calls
Calls
Data
Data References
References
Ascertaining
Ascertaining Data
Data Attributes
Attributes Dynamically
Dynamically

SAP AG 2002

(C) SAP AG

BC401

15-4

Field Symbols
FIELD-SYMBOLS <fs> TYPE|LIKE ... |TYPE ANY}.
ASSIGN ... dataobject TO <fs>.
UNASSIGN <fs>.
... <fs> IS ASSIGNED ...

Generic or
complete type
specification

DATA int TYPE i VALUE 15.


FIELD-SYMBOLS <fs_int> TYPE i.

fs_int

15

int

ASSIGN int TO <fs_int>.


WRITE: / int, <fs_int>.

fs_int

15

int

<fs_int> = 17.
WRITE: / int, <fs_int>.

fs_int

17

int

fs_int

17

int

UNASSIGN <fs_int>.
IF <fs_int> IS ASSIGNED.
WRITE: / int, <fs_int>.
ELSE.
WRITE: / 'fieldsymbol not assigned'(fna).
ENDIF.

SAP AG 2002

You declare field symbols using the FIELD-SYMBOLS <fs> statement. Note that the parentheses
(<>) are part of the syntax.
Field symbols allow you to access an assigned data object - that is, all the accesses that you make to the
field symbol are made to the data object assigned to it. Field symbols are similar to dereferenced
pointers. Thus, you can only access the content of the data object to which the field symbol points. (That
is, field symbols use value semantics).
You use the ASSIGN statement to assign a data object to the field symbol <fs>. If the field symbol is
generically typed (TYPE ANY), it adopts the type of the data object.
By specifying a type for the field symbol, you can ensure that only compatible objects are assigned to it.
Example:
DATA: date TYPE d VALUE '19991231', time TYPE t.
FIELD-SYMBOLS: <fs_date> TYPE d, <fs_time> TYPE t.
ASSIGN: date TO <fs_date>, time TO <fs_time>.
<fs_time> = <fs_date>. returns a syntax error.
Conversely, using the following construction would deliver a runtime error:FIELD-SYMBOLS:
<fs_date> TYPE ANY, <fs_time> TYPE ANY.
Use the expression <fs> IS ASSIGNED to find out whether the field symbol <fs> is assigned to a
field.
The statement UNASSIGN <fs>. sets the field symbol <fs> so that it points to nothing. The logical
expression <fs> IS ASSIGNED is then false.

(C) SAP AG

BC401

15-5

The CASTING Addition


ASSIGN ... dataobject TO <fs> CASTING [TYPE type|...] .

Inhalt des zugewiesenen


The content of the assigned
Datenobjekts wird so
data object is interpreted as
interpretiert, als ob er den
if it had the implicit or
implizit bzw. explizit
explicit type specified
angegeben Typ htte

TYPES: BEGIN OF st_date,


year(4) TYPE n,
month(2) TYPE n,
day(2)
TYPE n,
END OF st_date.
* option 1: implicit
FIELD-SYMBOLS <fs> TYPE st_date.
ASSIGN sy-datum TO <fs> CASTING.

sy
...

* access after casting:


WRITE: / <fs>-year, <fs>-month, <fs>-day.
* option 2: explicit
FIELD-SYMBOLS <fs> TYPE ANY.
ASSIGN sy-datum TO <fs> CASTING TYPE st_date.
...

...

date
20011221

...
...

fs

SAP AG 2002

If you use the CASTING addition when you assign a data object to a field symbol that has a different
type, you can remove the restrictions of having to use the data object's original type. The access is then
interpreted as though the data object had the data type of the field symbol.
If you use the CASTING TYPE <type> addition when you assign a data object to a field symbol that
has a different type, you can access the data object using the field symbol as if the object had the type
<type>.
In the above example, note that the system field sy-datum is an elementary character-type component
of length 8.
You can also use type casting dynamically when you assign a data object to a field symbol.
For example:
PARAMETERS tabname TYPE dd02l-tabname.
DATA:
dummy TYPE i,
line(65535) TYPE c.
FIELD-SYMBOLS <fs_wa> TYPE ANY.

ASSIGN line TO <fs_wa> CASTING TYPE (tabname).


You can now access line through <fs_wa> as if this elementary data object had the same type as the
line type of the transparent table passed using tabname. (You define the dummy data object only to
ensure that line has the correct alignment).
(C) SAP AG

BC401

15-6

Dynamic Programming (2)

Field
Field Symbols
Symbols in
in Detail
Detail
Dynamic
Dynamic Calls
Calls
Data
Data References
References
Ascertaining
Ascertaining Data
Data Attributes
Attributes Dynamically
Dynamically

SAP AG 2002

(C) SAP AG

BC401

15-7

Using Dynamic Attributes in Statements

Replacing a literal with a variable:

CALL TRANSACTION 'T_CODE'.


* dynamic:
data_object = 'T_CODE'.
CALL TRANSACTION data_object.

Replacing an identifier with a variable in parentheses (without spaces):

SUBMIT report_name.
* dynamic:
data_object = 'REPORT_NAME'.
SUBMIT (data_object).

Replacing a list with an internal table:

SET PF-STATUS 'STATUS_NAME' EXCLUDING 'FC1' 'FC2' ... .


* dynamic:
* ... fill internal_table with function codes ...
SET PF-STATUS 'STATUS_NAME' EXCLUDING internal_table .

SAP AG 2002

In many ABAP statements, you can pass attributes dynamically. The syntax for doing this differs,
depending on the statement you use:
If you pass the attribute as a literal in the static form of the statement, you can replace the literal with a
variable. If you pass the attribute as an identifier in the static form of the statement, you can replace the
identifier with a variable in parentheses. Make sure there are no spaces between either parenthesis and
the variable. If the attribute is a list, you can replace it with an internal table.
Note: you must use upper case when filling data objects with literals.
For more information on which of these three options you can use with a specific ABAP statement - if
any - refer to the ABAP documentation for that statement.
In Open SQL statements, you can also specify the logical conditions of the WHERE clause dynamically at
runtime, by entering the ABAP source code in a variable. In the FROM clause of the SELECT statement,
you can specify either individual table names or a dynamic JOIN expression using a variable. Similarly,
you can program the GROUP-BY and HAVING clauses in SELECT statements. For more information,
refer to the keyword documentation.

(C) SAP AG

BC401

15-8

Calling Methods Dynamically


Internal
table types

TYPE-POOL abap.
TYPES abap_parmbind_tab ...
TYPES abap_excpbind_tab ...

Name of formal
parameter

...

Reference to the
actual parameter

How variable
is passed
(optional)

TYPE-POOLS abap.
DATA: ptab TYPE abap_parmbind_tab,
etab TYPE abap_excpbind_tab.
...
data_object = 'METHOD_NAME'.
* Fill ptab and etab
...
CALL METHOD ref->(data_object)
PARAMETER-TABLE ptab
EXCEPTION-TABLE etab.

ptab

name kind

Name of
exception
etab

value

Value for
sy-subrc
name

value

SAP AG 2002

You can call instance and static methods dynamically using parentheses in the syntax, as is normal in
ABAP. Use the PARAMETER-TABLE and EXCEPTION-TABLE additions of the CALL METHOD
statement to pass the actual parameters dynamically.
The parameter table must have the attributes of the ABAP_PARMBIND_TAB table type. The table has
three columns: NAME (for the name of the formal parameter); KIND for the way the parameter is
passed (exporting, importing, changing, or receiving); VALUE with the type REF TO data (for the
value of the actual parameter).
The way the parameter is passed is specified for each formal parameter in the declaration of the called
method. Thus, the content of the KIND column can be initial.
For the value of the actual parameter, the VALUE reference of the line in the table must point to the data
object containing that value. You can use the GET REFERENCE statement to achieve this.
The exception table must have the attributes of the ABAP_EXCPBIND_TAB table type. This table has
two columns: NAME for the name of the exception; VALUE for the value to be assigned to sy-subrc.
VALUE must be of type i.

(C) SAP AG

BC401

15-9

Dynamic Programming (3)

Field
Field Symbols
Symbols in
in Detail
Detail
Dynamic
Dynamic Calls
Calls
Data
Data References
References
Ascertaining
Ascertaining Data
Data Attributes
Attributes Dynamically
Dynamically

SAP AG 2002

(C) SAP AG

BC401

15-10

Data Reference Variables


TYPES reftype

DATA

ref

TYPE REF TO type_name |


LIKE REF TO do_name
|
TYPE REF TO data }.

Any completely
specified type

TYPE REF TO type_name |


LIKE REF TO do_name
|
TYPE REF TO data }.

Generic type
assignment

GET REFERENCE OF dataobject INTO ref.

DATA:

ref

ref TYPE REF TO i,


do TYPE i VALUE 15.

do

GET REFERENCE OF do INTO ref.

15

ref
do

15

Get a reference to a data


object
SAP AG 2002

Data reference variables contain data references - that is, pointers to data objects. You use the TYPES
reftype TYPE REF TO type_name statement to define a reference type to a data object, where
type_name is any completely specified type. You can also use the generic variant TYPE REF TO
data here. You define the data reference variable itself using the DATA statement. This reference
variable is a data object that can contain any data object (TYPE REF TO data) or a data object of the
specified type.
You work with data references using references. That is, when you access a data reference variable the
data reference itself is accessed, so that changes are made to the addresses.
Data references are handled in ABAP like any data object with an elementary data type. This means that
a reference variable can be defined not only as a single field, but also as the smallest indivisible unit in a
complex data object, such as a structure or an internal table.
After it has been defined, the data reference variable is initial - that is, it contains an empty pointer. For a
data reference variable to contain a reference that points to a data object, you must use this variable to
get a reference to a data object that has already been declared (GET REFERENCE OF dataobject
INTO ref). You can also assign an existing data reference from another data reference variable or
generate a data object dynamically using it. (This will be discussed in more detail later.)

(C) SAP AG

BC401

15-11

Example: Using Data Reference Variables in


Dynamic Method Calls
CLASS lcl_vehicle DEFINITION.
...
METHODS get_make
EXPORTING ex_make TYPE string.
...
ENDCLASS.
TYPE-POOLS abap.
DATA: ptab
TYPE
wa_ptab LIKE
meth
TYPE
ref
TYPE
gd_make TYPE
...

abap_parmbind_tab,
LINE OF ptab,
string,
REF TO data,
string.

CLASS lcl_vehicle IMPLEMENTATION.


...
METHOD get_make.
ex_make = make.
ENDMETHOD.
...
ENDCLASS.

After the dynamic method call:


name

GET REFERENCE OF gd_make INTO ref.


wa_ptab-value = ref.
wa_ptab-name = 'EX_MAKE'.
INSERT wa_ptab INTO TABLE ptab.

ptab

meth = 'GET_MAKE'.
CALL METHOD r_truck->(meth)
PARAMETER-TABLE ptab.

kind

value

EX_MAKE

gd_make

VOLVO

WRITE gd_make.
SAP AG 2002

In this example, the get_make method of the lcl_vehicle class is called dynamically. It has only
one export parameter and no exceptions.
First we define a parameter table ptab with the global table type abap_parmbind_tab from the
type group abap. The associated work area is called wa_ptab.
We fill the work area wa_ptab with the associated values. We assign the name of the export parameter
EX_MAKE to the component name. The component value contains the reference to the corresponding
actual parameter gd_make. We also define the data reference variable ref (TYPE REF TO data)
and fill the corresponding reference using GET REFERENCE. The kind component of the work area
need not be filled.
We then insert this work area in the parameter table ptab using the INSERT statement. Finally we
assign the name of the calling method to the data object meth. We then call the method using the syntax
already shown.
After the method call, the actual parameter gd_make contains the passed value.

(C) SAP AG

BC401

15-12

Generating Data Objects at Runtime

DATA

ref
{ TYPE REF TO type_name | LIKE REF TO do_name }.
CREATE DATA ref.
You can also
assign a type
dynamically
DATA ref
TYPE REF TO data.
CREATE DATA ref

TYPE { type_name | itab_type_def }.

PARAMETERS pa_tab
TYPE dd021-tabname.
DATA
ref_itab TYPE REF TO data.

ref_itab

CREATE DATA ref_itab TYPE STANDARD TABLE


OF (pa_tab)
WITH DEFAULT KEY.
Standard table with standard key
and line type appropriate for the
content of the data object pa_tab
SAP AG 2002

All data objects declared in the declaration part of a program using the appropriate statement (such as
DATA) are generated statically and can be addressed from when the first event block is executed.
However, you can also use data reference variables to generate any data object you want dynamically
while the program is executing. You can use either of the above variants to do this.
Both of these variants generate a data object in the internal session of the current ABAP program. The
data reference in the data reference variable ref points to this object after the statement has been
executed. This dynamically generated data object does not have its own name; it can only be addressed
using the data reference variable. If you want to access the content of the data object, you need to
dereference the data reference first.
In the second variant, you specify the data type of the data object you want to generate after the TYPE
addition of the CREATE-DATA statement. In this case, you can specify the data type dynamically:
CREATE DATA ref TYPE (dataobject). You cannot do this in other ABAP statements.
dataobject is the name of a field containing the name of the relevant data type.
When you generate internal tables using the second variant, you must specify the table kind statically.
You can, however, specify the line type either statically or dynamically. You can also specify the key
components either statically or dynamically (as the contents of a table containing the component names).
You can also specify the initial number of table lines statically or dynamically (as the contents of a
variable).

(C) SAP AG

BC401

15-13

Dereferencing Data References

ASSIGN ref->* TO <fs> [CASTING ... ].

PARAMETERS pa_tab
DATA
ref_itab

TYPE dd021-tabname.
TYPE REF TO data.

You can then address


the contents of the
internal table using the
field symbol

fs_itab

ref_itab

FIELD-SYMBOLS <fs_itab> TYPE ANY TABLE.

CREATE DATA ref_itab TYPE STANDARD TABLE


OF (pa_tab)
WITH DEFAULT KEY.
ASSIGN ref_itab->* TO <fs_itab>.
SELECT * FROM (pa_tab) INTO TABLE <fs_itab>.

SAP AG 2002

To access the contents of the data object, you need to dereference the data reference first. To access data
objects generated with data reference variables with generic types (TYPE REF TO data), you can use
field symbols: ASSIGN ref->* TO <fs>. This statement assigns the relevant data object (the one
to which the data reference in the reference variable ref points) to the field symbol <fs>. If the data
object i s assigned successfully, sy-subrc is set to 0. If the field symbol is fully generically typed, it
adopts the type of the data object. If the field symbol is partially or completely typed, the system checks
the compatibility of the data types. You can also cast to the assigned data object.
If the data reference in ref is initial or invalid, it cannot be dereferenced. In that case the field symbol
remains unchanged and sy-subrc is set to 4.
If the data reference variable ref is completely typed (that is, not generically), you can use the prefix
ref-> to access the contents of the data object to which ref is pointing. You can write this expression
in any operand position. If the data reference is typed, you can also address the components of the
referenced data object directly and use them in any operand position.
DATA ref TYPE REF TO sflight.
CREATE DATA ref.
ref->fldate = ref->fldate + 5.
WRITE: / ref->seatsmax.

(C) SAP AG

BC401

15-14

Example: Generating Data Objects at Runtime


PARAMETERS pa_dbtab TYPE dd02l-tabname DEFAULT 'SFLIGHT'.
DATA d_ref TYPE REF TO data.
FIELD-SYMBOLS: <fs_wa> TYPE ANY, <fs_comp> TYPE ANY.
START-OF-SELECTION.
CREATE DATA d_ref TYPE (pa_dbtab).
ASSIGN d_ref->* TO <fs_wa>.
SELECT * FROM (pa_dbtab) INTO <fs_wa>.
DO.
ASSIGN COMPONENT sy-index OF STRUCTURE <fs_wa> TO <fs_comp>.
IF sy-subrc NE 0.
SKIP.
EXIT.
ENDIF.
WRITE <fs_comp>.
ENDDO.
ENDSELECT.
SAP AG 2002

This example displays the content of a transparent table. You can make the FROM clause of the SELECT
statement dynamic. For the INTO clause, you will need a data object that has a line type compatible with
that of the table being displayed. Since the name - and thus the line type of the table is not known until
runtime, you should not create the data object until then.
Unlike conventional data objects, you can specify the type of a data object created at runtime
dynamically. The TYPE addition of the CREATE DATA statement contains the name of the table, so that
the system creates the appropriate structure.
The statement ASSIGN d_ref->* TO <fs_wa> assigns the data object to the field symbol. The
data type of the table is inherited by the field symbol, so type casting is no longer necessary.
You can now write each data record from the SELECT statement into the compatibly-typed data object
using the field symbol <fs_wa>.
If you knew the component names, you could display the fields directly using WRITE <fs_wa>-... .
However, you will not normally know the names of the components, nor how many of them there are.
For this reason, you must display the components using the ASSIGN-COMPONENT variant: The
components of the structure <fs_wa are assigned one-by-one to the field symbol <fs_comp> and then
displayed. When the loop runs out of components, the program reads the next data record.

(C) SAP AG

BC401

15-15

Dynamic Programming (4)

Field
Field Symbols
Symbols in
in Detail
Detail
Dynamic
Dynamic Calls
Calls
Data
Data References
References
Ascertaining
Ascertaining Data
Data Attributes
Attributes Dynamically
Dynamically

SAP AG 2002

(C) SAP AG

BC401

15-16

Ascertaining Internal Table Attributes


DATA: no_of_lines
TYPE i,
initial_lines TYPE i,
table_kind
TYPE c.

Number of lines in
the internal table

Number of lines
reserved when table
was first created

DESCRIBE TABLE itab


LINES no_of_lines
OCCURS initial_lines
KIND
table_kind.

Table kind

* other variant:
no_of_lines = lines( itab ).
table_kind
Constants used
to evaluate the
return value

TYPE-POOL: sydes.
sydes_kind-undefined
sydes_kind-standard
sydes_kind-sorted
sydes_kind-hashed

SAP AG 2002

The DESCRIBE TABLE statement allows you to obtain the following information about an internal
table:
The number of lines:
After LINES, you must enter a type i variable (here no_of_lines)
The number of table lines initially reserved:After OCCURS, you must enter a type i variable (here:
initial_lines)
The table kind:
After KIND, you must enter a type c variable. The runtime system fills the variable with a constant
defined in the type group SYDES - SYDES_KIND-UNDEFINED, SYDES_KIND-STANDARD,
SYDES_KIND-SORTED, or SYDES_KIND-HASHED.
Since SAP R/3 Basis Release 6.10, there is also a built-in function, lines.
Note:
You can use the information about the number of lines in an internal table to query at runtime whether
an internal table has any entries in it at all. Alternatively, use the IS INITIAL query. The genericallytyped interface parameters of subroutines, function modules, and methods can use the information on the
table kind.

(C) SAP AG

BC401

15-17

Dynamic Type Descriptions for RTTI Classes


Hierarchy of description classes:

Rules:

CL_ABAP_TYPEDESCR
CL_ABAP_TYPEDESCR
CL_ABAP_DATADESCR
CL_ABAP_DATADESCR
CL_ABAP_ELEMDESCR
CL_ABAP_ELEMDESCR

Ascertaining the type attributes of a


data object at runtime:

CL_ABAP_REFDESCR
CL_ABAP_REFDESCR

Pass the data object to the


static method
DESCRIBE_BY_DATA of the
class CL_ABAP_TYPEDESCR

Get the reference to the


appropriate description object

Evaluate the public attributes


of this object

CL_ABAP_COMPLEXDESCR
CL_ABAP_COMPLEXDESCR
CL_ABAP_STRUCTDESCR
CL_ABAP_STRUCTDESCR
CL_ABAP_TABLEDESCR
CL_ABAP_TABLEDESCR
CL_ABAP_OBJECTDESCR
CL_ABAP_OBJECTDESCR
CL_ABAP_CLASSDESCR
CL_ABAP_CLASSDESCR
CL_ABAP_INTFDESCR
CL_ABAP_INTFDESCR

SAP AG 2002

Since the introduction of ABAP Objects, there is now a system called the RTTI concept (Run Time Type
Information) that you can use to find out type attributes at runtime. It is based on system classes. The
concept includes all ABAP types, and so covers all of the functions of the statements DESCRIBE
FIELD and DESCRIBE TABLE.
There is a description class for each type with special attributes for special type attributes. The class
hierarchy of the description classes corresponds to the hierarchy of the types in the ABAP type system.
In addition, the description classes for complex types, references, classes, and interfaces have special
methods used to specify references to sub-types. Using these methods, you can navigate through a
compound type to all its sub-types.
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.

(C) SAP AG

BC401

15-18

Declaring Types Dynamically: Example


...
DATA:
descr_ref TYPE REF TO cl_abap_structdescr,
wa_comp
TYPE abap_compdescr.
...

START-OF-SELECTION.
...
* get reference to type descripion object by widening cast:
descr_ref ?= cl_abap_typedescr=>describe_by_data( <fs_wa> ).
...

TOP-OF-PAGE.
LOOP AT descr_ref->components INTO wa_comp.
WRITE wa_comp-name.
ENDLOOP.

SAP AG 2002

We can now enhance the example of dynamic type declarations so that the system also displays the
column names of the transparent table in the list.
Since we need the attributes of a structure, we first define a reference to the appropriate description
class. Instances of this class possess a COMPONENTS attribute, which you use to describe the individual
components of the relevant structure. This attribute is an internal table. Therefore you also need to define
a work area with a compatible line type.
The (functional) method call returns the reference to the description instance of the structure. (The
system creates the structure dynamically, which is why it is accessed through a field symbol).
Only the abstract class CL_ABAP_TYPEDESCR contains the method DESCRIBE_BY_DATA. Its
RETURNING parameter is typed as a reference to this superclass. However, since the actual parameter
descr_ref has the type of the subclass CL_ABAP_STRUCTDESCR, we need to assign the object
using a (widening) cast.
You can then access the attributes of the description instance in any form. In this example, the
component names are displayed as the column headers. (We have omitted the formatting options for the
sake of clarity.)
For more information and syntax examples, refer to the online documentation, either under the keyword
RTTI or the class CL_ABAP_TYPEDESCR.

(C) SAP AG

BC401

15-19

Dynamic Programming: Unit Summary

You are now able to:


Use dynamic attributes in suitable ABAP
statements
Use data objects generated at runtime
Ascertain the attributes of data objects at runtime

SAP AG 2002

(C) SAP AG

BC401

15-20

Exercise 1 Optional
Unit: Dynamic Programming
Topic: Casting Types
At the conclusion of these exercises, you will be able to:
Use field symbols to cast types
Perform calculations on dates
Change your program so that the default value for the key date is
calculated differently. It should be the first day of the following month.

Program:

ZBC401_##_CASTING

Template: SAPBC401_TABS_PROCESS_DATA
Model solution: SAPBC401_DYNS_CASTING

1-1

Copy your solution to the last exercise from the unit Using Internal Tables
ZBC401_##_PROCESS_DATA or the corresponding model solution
SAPBC401_TABS_PROCESS_DATA and give it the new name
ZBC401_##_CASTING.

1-2

Define a structure type (we suggest the name: st_date) with three components:
Year, month, and day. Assign an appropriate type to each component.
Define a field symbol based on this type (suggested name: <fs_date>).

1-3

In the LOAD-OF-PROGRAM event block:


Copy todays date to the input parameter pa_date.
Assign the input parameter to the field symbol.
Now fill the input parameter with the first day of the next month by accessing the
pseudo-components for the year, month, and day, using the field symbol.

(C) SAP AG

BC401

15-21

Screen Exercise 2
Unit: Dynamic Programming
Topic: Dynamic Open SQL Statements and Generating
Data Objects at Runtime
At the conclusion of these exercises, you will be able to:
Generate data objects dynamically
Program dynamic SQL statements
Develop an ABAP program that can be used as an ad hoc data browser.
You should be able to access only the table name on the selection screen.
Delegate filtering by field content and similar functions to an SAP Grid
Control instance, which you should also use to display the data.
The purpose of this program is to make you more familiar with dynamic
programming techniques. (There is already a Data Browser, installed as a
standard tool in the ABAP Workbench.)
Program:

ZBC401_##_CREATE_DATA_SQL

Template: SAPBC401_DYNT_CREATE_DATA_SQL
Model solution: SAPBC401_DYNS_CREATE_DATA_SQL

2-1

Copy your program, SAPBC401_DYNT_CREATE_DATA_SQL, giving it the name


ZBC401_##_CREATE_DATA_SQL.

2-2

Get to know the source code and runtime behavior of this program.
Then implement the following concept: At runtime, the program should generate an
internal table whose line type is compatible with the selected transparent table. The
former should then be filled with the complete contents of the latter using a dynamic
SQL statement. The internal table filled in this way should then be passed to a SAP
Grid Control instance.

2-3

Define a reference for the internal table that will be generated (we suggest the name
ref_itab).

(C) SAP AG

BC401

15-22

2-4

At program runtime, generate the internal table. At this time, it is known which line
type must be used.
The table must be a standard table with a non-unique standard key.

2-5

Assign a generically-typed field symbol to the generated internal table (suggested


name: <fs_itab>), so that its contents can be accessed.

2-6

Before calling the screen, insert an Open SQL statement that copies the complete
contents of the selected transparent table into the internal table using an array fetch.
If an error occurs, make sure the program terminates.

2-7

Generate a SAP Grid Control instance within the PBO module that you have created,
INIT_CONTROLS_0100. Again, if an error occurs, make sure the program
terminates.
The relevant class is called CL_GUI_ALV_GRID.

2-8

Pass the internal table filled in this way to this SAP Grid Control instance.
If an error occurs, make sure the program terminates.
The relevant method is called
SET_TABLE_FOR_FIRST_DISPLAY.
You need only pass values to two parameters: The line type to
I_STRUCTURE_NAME and the name of the internal table to
IT_OUTTAB.

(C) SAP AG

BC401

15-23

Solution 1 - Optional
Unit: Dynamic Programming
Topic:

Casting Types

REPORT sapbc401_dyns_casting.
TYPE-POOLS col.
TYPES:
BEGIN OF st_flight_c,
...
END OF st_flight_c,
BEGIN OF st_flight,
...
END OF st_flight,
BEGIN OF st_date,
year(4)

TYPE n,

month(2) TYPE n,
day(2)

TYPE n,

END OF st_date.

CONSTANTS c_number TYPE i VALUE 30.


DATA:
datastring

TYPE string,

set_string

TYPE string,

wa_flight_c TYPE st_flight_c,


wa_flight

TYPE st_flight.

DATA:
(C) SAP AG

BC401

15-24

it_sets TYPE STANDARD TABLE OF string


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

it_col_flights TYPE bc401_t_flights_color,


it_col_doubles LIKE it_col_flights,
wa_col_flight LIKE LINE OF it_col_flights.

FIELD-SYMBOLS <fs_date> TYPE st_date.

PARAMETERS:
pa_date LIKE sy-datum,
pa_alv

AS CHECKBOX DEFAULT 'X'.

LOAD-OF-PROGRAM.
pa_date = sy-datum.
ASSIGN pa_date TO <fs_date> CASTING.
<fs_date>-day = '01'.
IF <fs_date>-month < 12.
<fs_date>-month = <fs_date>-month + 1.
ELSE.
<fs_date>-month = '01'.
<fs_date>-year = <fs_date>-year + 1.
ENDIF.
(C) SAP AG

BC401

15-25

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

" date in the past

ENDIF.
START-OF-SELECTION.
...

(C) SAP AG

BC401

15-26

Solution 2
Unit:

Dynamic Programming

Topic: Dynamic Open SQL Statements and Generate


Data Objects at Runtime
2-1

The copy template displays a selection screen where you can enter the name of a
transparent table. It then shows a screen that displays the contents of this table.
From this screen, you can either navigate back to the selection screen or end the
program.
This runtime behavior is implemented using standard ABAP programming techniques.
A docking container control instance that fills the whole screen has already been
generated and attached to the screen.

Model solution: SAPBC401_DYNS_CREATE_DATA_SQL

REPORT

sapbc401_dyns_create_data_sql.

DATA:
ok_code LIKE sy-ucomm,
popans.
DATA:
ref_docking TYPE REF TO cl_gui_docking_container,
ref_alv
TYPE REF TO cl_gui_alv_grid.
DATA ref_itab TYPE REF TO data.
FIELD-SYMBOLS <fs_itab> TYPE ANY TABLE.
PARAMETERS pa_tab TYPE dd02l-tabname DEFAULT 'SPFLI'.

(C) SAP AG

BC401

15-27

START-OF-SELECTION.
CREATE DATA ref_itab TYPE STANDARD TABLE OF (pa_tab)
WITH NON-UNIQUE DEFAULT KEY.
ASSIGN ref_itab->* TO <fs_itab>.
SELECT * FROM (pa_tab)
INTO TABLE <fs_itab>.
IF sy-subrc <> 0.
MESSAGE a000(rfw) WITH text-ndt.
ENDIF.
CALL SCREEN 100.
*&--------------------------------------------------------*
*&
Module clear_ok_code OUTPUT
*
*&--------------------------------------------------------*
MODULE clear_ok_code OUTPUT.
CLEAR ok_code.
ENDMODULE.
" clear_ok_code OUTPUT
*&--------------------------------------------------------*
*&
Module STATUS_0100 OUTPUT
*
*&--------------------------------------------------------*
MODULE status_0100 OUTPUT.
SET PF-STATUS 'ST100'.
SET TITLEBAR 'T100'.
ENDMODULE.
" STATUS_0100 OUTPUT
*&--------------------------------------------------------*
*&
Module init_controls_0100 OUTPUT
*
*&--------------------------------------------------------*
MODULE init_controls_0100 OUTPUT.
IF ref_docking IS INITIAL.

CREATE OBJECT ref_docking


EXPORTING
SIDE
extension
EXCEPTIONS
OTHERS
.
IF sy-subrc <> 0.
MESSAGE a015(rfw).
ENDIF.

= DOCK_AT_LEFT
= 2000
= 6

CREATE OBJECT ref_alv


EXPORTING
i_parent
= ref_docking
EXCEPTIONS
error_cntl_create = 1
error_cntl_init
= 2
(C) SAP AG

BC401

15-28

error_cntl_link
= 3
error_dp_create
= 4
OTHERS
= 5
.
IF sy-subrc <> 0.
MESSAGE a000(rfw) WITH text-aer.
ENDIF.
CALL METHOD ref_alv->set_table_for_first_display
EXPORTING
i_structure_name
= pa_tab
CHANGING
it_outtab
= <fs_itab>
EXCEPTIONS
invalid_parameter_combination = 1
program_error
= 2
too_many_lines
= 3
OTHERS
= 4
.
IF sy-subrc <> 0.
MESSAGE a033(rfw).
ENDIF.
ENDIF.
ENDMODULE.

" init_controls_0100

OUTPUT

*&--------------------------------------------------------*
*&
Module leave_programm INPUT
*
*&--------------------------------------------------------*
MODULE leave_programm INPUT.
CLEAR popans.
CALL FUNCTION 'POPUP_TO_CONFIRM_STEP'
EXPORTING
textline1
= text-dml
textline2
= text-rcn
titel
= text-cnc
cancel_display = ' '
IMPORTING
answer
= popans.
CASE popans.
WHEN 'J'.
LEAVE PROGRAM.
WHEN 'N'.
CLEAR ok_code.
ENDCASE.
ENDMODULE.
" leave_programm INPUT

*&--------------------------------------------------------*
*&
Module user_command_0100
*
*&--------------------------------------------------------*
(C) SAP AG

BC401

15-29

MODULE user_command_0100 INPUT.


CASE ok_code.
WHEN 'BACK'.
CLEAR popans.
CALL FUNCTION 'POPUP_TO_CONFIRM_STEP'
EXPORTING
textline1
= text-dml
textline2
= text-rbk
titel
= text-bak
cancel_display = ' '
IMPORTING
answer
= popans.
CASE popans.
WHEN 'J'.
LEAVE TO SCREEN 0.
WHEN 'N'.
ENDCASE.
WHEN OTHERS.
ENDCASE.

(C) SAP AG

BC401

15-30

Das könnte Ihnen auch gefallen