You are on page 1of 111

ABAP SAMPLE

programs with
quick Resolution

1
Defining Data with the ABAP Editor

Learning objective

After completing this topic, you should be able to define ABAP data objects in a given
scenario.

1. Creating an ABAP program

Advanced Business Application Programming (ABAP) is a programming language used for


developing and customizing SAP applications and programs.

The ABAP Editor is a development tool that SAP R/3 provides. This tool enables you to
create, edit, and execute ABAP programs. You use the SAP Easy Access window to
access the ABAP Editor.

The SAP Easy Access window has already been opened for you. To access the ABAP
Editor, you specify the correct transaction code in the command field.

You type SE38 in the command field, and then you click Enter to access the ABAP Editor:
Initial Screen.

The initial screen of the ABAP Editor appears. You can use this screen to open and
execute existing ABAP programs, and create new ABAP programs.

In addition to using a transaction code, you can use the SAP menu to access the ABAP
Editor. You double-click Tools - ABAP Workbench - Development - SE38 - ABAP Editor
in the SAP menu to do this.

To create a new ABAP program, you first need to specify the program name in the Program
field. Program names must begin with a "y" or a "z".

You type yabc11 in the Program field of ABAP Editor: Initial Screen, and then you click
Create to create a new program.

The ABAP: Program Attributes window appears.


You use this window to save the ABAP program and to specify the program details, such as
its title and other attributes, including the program type and the application area to which
the program belongs.

You need to specify the title and type of the program in the ABAP: Program Attributes
window before saving the program.

You use the Title field of the ABAP: Program Attributes window to specify a short
description of the program.

For example, if you want to create a program to generate a Bill Of Materials (BOM) for a

2
plant that manufactures plasma televisions, you can specify the program title as "Generate
BOM plasma TV".

In addition to the Title, you need to specify the type of the ABAP program. The possible
values that you can specify in the Type attribute are

Executable program
INCLUDE program
Module pool
Function group
Subroutine pool
Interface pool
Class pool
Executable program
Executable program indicates that the program can be executed independently without a
transaction code.
INCLUDE program
INCLUDE program indicates that the program can't be executed independently. Such
programs need to be called by other programs for execution using the INCLUDE
statement.
Module pool
Module pool indicates that the program can be executed only by using a transaction code
or a menu option.
Function group
Function group indicates that the program is a function that other programs can call for
execution.
Subroutine pool
Subroutine pool indicates that the program contains parts of programs that can be called
by other programs. You use PERFORM statements for calling Subroutine pool programs.
Interface pool
Interface pool indicates that the program contains interfaces that other programs can use
globally.
Class pool
Class pool indicates that the program contains interfaces that other programs can use
globally.

To create an executable ABAP program named "yabc11", you specify its title and type, and
save it.

You type Test Program in the Title field, you select Executable program from the Type
drop-down list, click Save, and then you click Local Object in the Create Object Directory
Entry window to create the ABAP program.

3
This opens the ABAP Editor: Change Report screen that displays the new ABAP program
that you have created. You use this screen to edit the source code of an ABAP program.

The program that the ABAP Editor: Change Report screen initially displays is only the basic
template of an ABAP program. You then develop the source code of the ABAP program by
using this basic template.

When you edit and save an ABAP program, it is an inactive version of the program. It is not
possible to execute this program. To execute an ABAP program, you first need to activate
it.

Say you now want to activate your ABAP program.

You click Activate, and then you click Continue on the Inactive Objects screen to activate
the ABAP program.

The status changes to "Active". The ABAP program can now be executed.

Question

Suppose you are a developer in Brocadero, a company that manufactures consumer


products. You need to create an executable ABAP program with the name
"zsales_inv" and the title "Generating Sales Invoice" for generating sales invoices.
You also need to activate the program. You need to perform these tasks by using
the ABAP Editor. The SAP Easy Access window has already been opened for you.

What steps should you perform to create and activate the desired ABAP program?

Options:

1. Type SE38 in the command field and click Enter. Then type zsales_inv in the Program
field and click Create. Type Generating Sales Invoice in the Title field, select
Executable program from the Type drop-down menu, and click Save. Then click Local
Object, click Activate, and finally click Continue.
2. Type SE83 in the command field and click Enter. Then type zsales_inv in the Program
field and click Display. Type Generating Sales Invoice in the Title field, select
INCLUDE program from the Type drop-down menu, and click Choose. Then click Local
Object, click Activate, and finally click Continue.

Answer

Type SE38 in the command field and click Enter. Then type zsales_inv in the
Program field and click Create. Type Generating Sales Invoice in the Title
field, select Executable program from the Type drop-down menu, and click Save.
Then click Local Object, click Activate, and finally click Continue.

4
2. Rules of the ABAP syntax

An ABAP program consists of multiple lines of code, known as statements, that are used to
define and manipulate data.

When writing statements in an ABAP program, you need to follow specific rules. This
ensures that the ABAP processor is able to correctly interpret and execute the statements
to produce the desired result.

An ABAP statement always begins with a keyword and ends with a period. At least one
space should separate the words in an ABAP statement.

For example, consider this ABAP statement.

write /20(5) 'Hello'.

In this ABAP statement, "write" is a keyword, the words are separated by spaces, and the
statement ends with a period.

An ABAP program also contains comments, which are included to improve the readability of
the ABAP program and are ignored during program execution.

Comment lines should begin with an asterisk (*) or double-quotes ("). For example,
consider this code.

*&-------------------------------------*
*& Creating Sales Report *
*&-------------------------------------*
SELECTION-SCREEN BEGIN OF BLOCK b2.

write / 'Sales Report'. "Display name

The first three lines of the code are comments that are ignored during the ABAP program
execution. In addition, the section of the code typed after the double-quotes is ignored.

Question

Suppose you are a developer and want to write an ABAP statement to display the
text "test".

Which of the following statements is correct according to the ABAP syntax?

Options:

1. *write /10(4), 'test'


2. *write /10(4)'test'.
3. write /10(4) 'test'.
4. write /10(4)'test'

5
Answer

The statement write /10(4) 'test'. is correct according to the ABAP syntax.

Option 1 is incorrect. An ABAP statement does not begin with an asterisk. The
words in an ABAP statement are not separated by commas. In addition, the ABAP
statement should end with a period.

Option 2 is incorrect. An ABAP statement does not begin with an asterisk. The
words in an ABAP statement should be separated by at least one space.

Option 3 is correct. According to the ABAP syntax, the words in an ABAP statement
should be separated by at least one space, and the statement should end with a
period.

Option 4 is incorrect. The words in an ABAP statement should be separated by at


least one space, and the statement should end with a period.

3. Identifying ABAP data types

When an ABAP program is executed, it performs logical operations on the local data in the
program. The data is stored as fields in the working memory of the program. A field is a
sequence of bytes.

You can specify the attributes such as data type and length of a field. For example, you can
specify that a field should only store numbers. In addition, you can specify that the numbers
should not be more than five digits in length.

The memory fields that store the program data during ABAP program execution are known
as data objects. These memory fields are assigned to a program when it executes, and are
released when the execution is complete. The free memory can then be assigned to other
programs.

There are two categories of data objects:

modifiable
nonmodifiable

You can change the value stored in a modifiable data object during program execution.

The modifiable data objects include variables, field strings, and internal tables.

The value of a nonmodifiable data object remains constant during program execution. You
specify the value of a nonmodifiable data object when defining the object.

The nonmodifiable data objects include literals and constants.

The three types of modifiable data objects are

6
Field strings
Internal tables
Variables
Field strings
Field strings are data objects that do not have a fixed size. The size of a field string
changes according to the size of the content in a field during ABAP program execution.
Internal tables
Internal tables are data objects that store data for manipulation by an ABAP program.

The data that an ABAP program needs during execution is first retrieved from the
database and stored in an internal table. The data is then manipulated by the ABAP
program when it is executed.
Variables
Variables are data objects that do not have a constant value. You can initialize the value
of a variable in an ABAP program. The value of a variable changes during program
execution.

The two types of nonmodifiable data objects are

Constants
Literals
Constants
Constants are data variables with a value and data type that remain unchanged. You can
define a constant as local or global.

The value and the data type of a local constant remain unchanged in the program where
it is defined. However, the value and the data type of a global constant remain unchanged
throughout all ABAP programs.
Literals
Literals are data objects with a value and data type that remain unchanged throughout a
program. It is possible to define both character string literals and numeric literals in an
ABAP program.

For example, 'Hello' is a character string literal and '-121' is a numeric literal.

Based on development requirements, you can use modifiable or nonmodifiable data objects
in an ABAP program.

When you define data objects, you need to specify the data type attribute of each object.
The ABAP processor performs logical operations on a data object on the basis of its data
type.

Some of the data types that ABAP supports are

7
character
date
hexadecimal
numeric
time
character
The character data type is denoted by "c". This data type supports alphanumeric values.

For example, an object "username" with the character data type can store a value
"chris01".
date
The date data type is denoted by "d". This data type supports numeric values in the range
0-9.

For example, an object "begin" with the date data type can store a value "09092007".
hexadecimal
The hexadecimal data type is denoted by "x". This data type supports all numeric values
in the range 0-9 and character values in the range A-F.

For example, an object "memory" with the hexadecimal data type can store a value
"FF40".
numeric
The numeric data type is denoted by "n". This data type supports numeric values in the
range 0-9.

For example, an object "age" with the numeric data type can store a value "25".
time
The time data type is denoted by "t". This data type supports numeric values in the range
0-9.

For example, an object "duration" with the time data type can store a value "12:30".

The size of the objects with character, numeric, or hexadecimal data types varies between
1 and 65,535 characters.

However, the size for date data type is eight characters and for the time data type is six
characters. The size for these data types is fixed.

Question

Match each data type with the values it supports.

Options:

8
1. Character
2. Hexadecimal
3. Numeric

Targets:

A. All alphanumeric values


B. Alphanumeric values in the range A-F and 0-9
C. Numeric values in the range 0-9

Answer

The character data type supports all alphanumeric values, the hexadecimal data
type supports alphanumeric values in the range A-F and 0-9, and the numeric data
type supports numeric values in the range 0-9.

The character data type supports all alphanumeric values. For example, it supports
the value "test01".

The hexadecimal data type supports values in the range A-F and 0-9. For example,
it supports the value "05CD".

The numeric data type supports the values in the range 0-9. For example, it supports
the value "5164".

4. Defining variables and literals

There are various sections or program blocks in an ABAP program. You specify ABAP
statements in specific sections based on the type of task that the statements perform.

The four sections of an ABAP program are

data declaration
initialization
start-of-selection
end-of-selection
data declaration
The data declaration section is used for defining the variables that you want to use in the
ABAP program.
initialization
The initialization section is used for assigning values to the variables. It is also used for
defining the INCLUDE programs that you need to call in the ABAP program.
start-of-selection
The start-of-selection section is used for calling the various functions that are required for
executing the ABAP program.

9
end-of-selection
The end-of-selection section is used for creating the functions that are required for
executing the ABAP program.

The three statements that are used to define variables are

data
parameters
select-options
data
The data statement is used to initialize the value of a variable while defining the variable
in an ABAP program. When the ABAP program is executed, it uses the value of the
variable initialized in the program.
parameters
The parameters statement is used to define a variable without initializing its value.
When the ABAP program is executed, the user needs to specify the value of the variable
to begin program execution.
select-options
The select-options statement is used to define variables that need a range of values
to be initialized. When the ABAP program is executed, the user needs to specify the
upper and lower limits of the value range for the variable in two input fields on a selection
screen.

To define a variable by using the data statement, you specify the name, size, and data
type of the variable.

data variable name(size) type data type.

For example, you can use the data statement to define a variable "username" that is 15
characters long and its data type is character.

data username(15) type c.

Suppose you want to use the data statement to define a variable "reports" that is five
characters long and its data type is numeric.

*&-----------------------*
*& Creating Report *
*&-----------------------------------------*
MISSING CODE type n.

You type data reports(5) to define the variable.

You have defined a numeric variable "reports".

10
*&-----------------------*
*& Creating Report *
*&-----------------------------------------*
data reports(5) type n.

When you define a variable by using the parameters statement, you specify the name,
size, and data type of the variable.

parameters variable name(size) type data type.

For example, you can use the parameters statement to define a variable "age" that is
three characters long and its data type is number.

parameters age(3) type n.

Suppose you want to use the parameters statement to define a variable "user" that is 12
characters long and its data type is character.

*&-----------------------*
*& Creating Report *
*&-----------------------------------------*
data reports(5) type n.
parameters MISSING CODE.

You type user(12) type c to define the variable.

You have defined the variable "user". The user needs to initialize the value of "user" during
program execution.

*&-----------------------*
*& Creating Report *
*&-----------------------------------------*
data reports(5) type n.
parameters user(12) type c.

To define a variable by using the select-options statement, you specify the variable
name and the title of the selection screen where the user initializes the value range for the
variable.

select-options title for variable name.

For example, say you want to define a variable "serial" with a value range that the user
specifies during program execution, and you want to name the selection screen as
"Number". You can use the select-options statement to define the variable.

select-options Number for serial.

11
Suppose you want to use the select-options statement to define a variable "list" that is
three characters long and its data type is numeric. The selection screen title should be
"Employees".

*&-----------------------*
*& Creating Report *
*&-----------------------------------------*
select-options MISSING CODE.

You type Employees for list to define the variable.

You have defined the variable "list" by using the select-options statement.

*&-----------------------*
*& Creating Report *
*&-----------------------------------------*
select-options Employees for list.

Question

Suppose you are a developer and you want to define a variable "Emp_Code". You
want the user should be able to specify the value range for the variable during
program execution.

Complete the missing code to define the variable.

*---------------------------------------*
* Employee Records *
*---------------------------------------*
write / 'Employee Payslip Record'. "Report title
MISSING CODE Emp_Code for S_No.

Answer

You use the select-options statement to define the variable.

When you want to use data objects with a value that remains unchanged, you define literals
in the ABAP program. Literals are mostly used when you need to display some text as
output.

To define a literal, you use single quotes ('). For example, you define a character string
literal "Samantha" by typing 'Samantha' and you define a numeric literal "-2134" by typing
'-2134'.

You use the write statement to display an output. For example, you can use the write
statement to display the value stored in a literal.

write / 'literal'.
12
Suppose you want to display the message "This is a literal". You can use the write
statement to define the message as a literal and display it.

write / 'This is a literal'.

Suppose you want to use the write statement to display the message "ABAP Editor". You
define a literal "ABAP Editor" in the ABAP program.

*&-----------------------------------------*
*& Creating Report *
*&-----------------------------------------*
data reports(5) type n.
write MISSING CODE.

You type / 'ABAP Editor' to define the literal.

You have defined the literal "ABAP Editor" and displayed it on the screen.

*&-----------------------------------------*
*& Creating Report *
*&-----------------------------------------*
data reports(5) type n.
write / 'ABAP Editor'.

Question

Suppose you want to display "SAP" by defining a literal in the write statement.

Type the code that enables you to display the desired output.

*---------------------------------------*
* Employee Records *
*---------------------------------------*
write / 'Employee Payslip Record'. "Report title
select-options Emp_Code for S_No.
MISSING CODE .

Answer

You use the code write / 'SAP' to do this.

Summary

You use the ABAP Editor to create, edit, and execute ABAP programs. You need to
activate an ABAP program before execution.

During ABAP program execution, data is stored in memory locations called data objects.

13
There are two categories of data objects: modifiable and nonmodifiable. The modifiable
data objects are variables, field strings, and internal tables. The nonmodifiable data types
are literals and constants.

The data type attribute of a data object specifies the type of data that the object can store.
The commonly used ABAP data types are character, date, hexadecimal, numeric, and time.

Various sections of an ABAP program are data declaration, initialization, start-of-selection,


and end-of-selection. You can define variables in the data declaration section of a program
by using the data, parameters, and select-options statements.

Performing Operations in ABAP

Learning objective

After completing this topic, you should be able to recognize how to perform assignments
and calculations in a given scenario.

1. Performing assignments

You use various modifiable data objects such as variables, field strings, and internal
tables to store values in ABAP programs.

You may need to manipulate these values. For example, you define a variable "quantity"
and want to increase its value. Alternatively, you may want to reset the value of the
variable.

Assignment statements enable you to manipulate the values of variables, field strings, and
internal tables.

The two most commonly used assignment statements are

clear
move

You use the clear statement to reset the value of a variable.

clear variable name.

For example, you can use the clear statement to reset the variable "counter", which
contains the value "102".

clear counter.

When the code is executed, the value of "counter" changes to "0".

14
Suppose the field string "company" stores the value "Brocadero". You want to reset the
value of the field string by using the clear statement.

data company type n value 55.


MISSING CODE company.

To do this, you type clear.

You have reset the value of the variable "company".

data company type n value 55.


clear company.

You use the move statement to assign the value of one variable to another variable.

move variable1 to variable2.

For example, the value of variable "a" is "10" and the value of variable "b" is "33". You can
use the move statement to assign the value of "a" to "b".

move a to b.

The value of "b" changes from "33" to "10".

Suppose the value of the variable "quantity" is "15" and the value of the variable "number"
is "27". You want to assign the value of "number" to "quantity" by using the move statement.

data quantity type n value 15.


data number type n value 27.
MISSING CODE to quantity.

To do this, you type move number.

You have assigned the value of the variable "number" to the variable "quantity".

data quantity type n value 15.


data number type n value 27.
move number to quantity.

Question

Suppose the variable "stock" contains the value "1524" and the variable "demand"
contains the value "56".

Which code snippets enable you to store the value of "stock" in "demand" and reset
the value of "stock" to "0"?

Options:

15
1. move demand to stock to store the value in "demand" and reset stock to reset the
value of "stock".
2. move stock in demand to store the value in "demand" and clear stock to reset the
value of "stock".
3. move stock to demand to store the value in "demand" and clear stock to reset the
value of "stock".

Answer

To store the value of "stock" in "demand", you use the code move stock to
demand, and to reset the value of "stock", you use the code clear stock.

2. Performing calculations

In addition to assignment operations, you can perform various logical operations, such as
addition, subtraction, and multiplication, on the variables you define in an ABAP program.
You use ABAP statements to perform numeric calculations.

An ABAP statement used for performing numeric calculations comprises two components:

operands
operators
operands
Operands are values on which the calculation is performed.

For example, in the statement a = b + c, the variables "a", "b", and "c" are operands.
operators
Operators are symbols that define the type of calculation that needs to be performed.

For example, in the statement a = b + c, the symbols "+" and "=" are operators.

The various ABAP statements that you use for performing numeric calculations are

add
divide
multiply
subtract
compute

You use the add statement to perform the addition operation on variables.

For example, you can use the add statement to add two variables, "variable1" and
"variable2", and store the result in variable2.

add variable1 to variable2.

16
Suppose the value of the variable "product" is "20" and of the variable "stock" is "46". You
want to add the values of both the variables and store the sum in the variable "stock". You
can use the add statement to do this.

add product to stock.

The statement "add a to b." is equivalent to "b = b + a.".

Suppose the variable "parcel" stores the value "540" and the variable "overnite" stores the
value "44". You need to calculate the sum of both variables and store the result in "parcel"
by using the add statement.

data parcel type n value 540.


data overnite type n value 44.
MISSING CODE to parcel.

You type add overnite to do this.

You have stored the sum of the variables "parcel" and "overnite" in the variable "parcel".

data parcel type n value 540.


data overnite type n value 44.
add overnite to parcel.

You use the divide statement to perform the division operation on variables. You can use
the divide statement to divide the value in "variable1" by the value in "variable2", and
store the result in "variable1".

divide variable1 by variable2.

For example, the value of the variable "effort" is "256" and that of "hours" is "48". You can
use the divide statement to divide "effort" by "hours" and store the result in "effort".

divide effort by hours.

The statement "divide effort by hours." is equivalent to "effort = effort/hours.".

Suppose you want to divide the value in "seconds" by the value in "a", and store the result
in "seconds" by using the divide statement.

data seconds type n value 120.


data a type n value 60.
divide MISSING CODE.

You type seconds by a to do this.

You have stored the result of division of "seconds" by "a" in "seconds".

17
data seconds type n value 120.
data a type n value 60.
divide seconds by a.

Question

Suppose the variable "bolts" contains the value "542" and the variable "nuts"
contains the value "465".

Store the sum of the variables "bolts" and "nuts" in the variable "bolts".

data bolts type n value 542.


data nuts type n value 465.
MISSING CODE bolts.

Answer

You type add nuts to to store the sum in "bolts".

You use the multiply statement to calculate the product of two numeric values. For
example, you can calculate the product of the values in "variable1" and "variable2", and
store the result in "variable1".

multiply variable1 by variable2.

Suppose the value of "cost" is "11" and that of "quantity" is "200". You can use the
multiply statement to multiply both the variables and store the result in "cost".

multiply cost by quantity.

The statement "multiply cost by quantity." is equivalent to "cost = cost * quantity.".

You use the subtract statement to calculate the difference in the values of two numeric
variables. For example, you can calculate the difference of "variable1" and "variable2", and
store the result in "variable2".

subtract variable1 from variable2.

Suppose the value of "profit" is "54" and that of "cost" is "23". You can use the subtract
statement to subtract "cost" from "profit" and store the result in "profit".

subtract cost from profit.

The statement "subtract cost from profit." is equivalent to "profit = profit - cost.".

Suppose you want to subtract "planned" from "effort" and store the sum in "effort" by using
the subtract statement.

18
data planned type n value 250.
data effort type n value 260.
subtract MISSING CODE.

You type planned from effort to perform the desired calculation.

You have stored the difference of values in "planned" and "effort" in "effort".

data planned type n value 250.


data effort type n value 260.
subtract planned from effort.

You use the compute statement to perform various mathematical calculations. Unlike add,
subtract, divide, and multiply, compute is a versatile statement that enables you to
execute various mathematical statements. In addition, it enables you to store the result of a
mathematical expression in a variable other than the ones included in the expression.

For example, you can execute a mathematical expression and store the result in the
variable "result".

compute result = mathematical expression.

For example, you can store the sum of the variables "b" and "c" in the variable "a" by using
the compute statement.

compute a = b + c.

The compute statement is optional. For example, the ABAP statement "a = b + c."
produces the same result as "compute a = b + c.".

Suppose you want to calculate the sum of the variables "domestic" and "international" and
store the sum in the variable "sales" by using the compute statement.

data domestic type n value 3000.


data international type n value 2500.
MISSING CODE.

You type sales = domestic + international to perform the desired calculation.

You have stored the sum of "domestic" and "international" in "sales".

data domestic type n value 3000.


data international type n value 2500.
sales = domestic + international.

Suppose you are a programmer at Brocadero. You need to create a program to calculate
the quantity of television screens available in the three warehouses of the company. You
also need to calculate the increase needed in the capacity of the manufacturing plant
required to meet the demand.
19
The variables that you require in the ABAP program have been defined for you.

*&------------------------------------------------------------*
*& Report STOCK
*
*&------------------------------------------------------------*
REPORT STOCK
data tvscr type n value 0. "Total number of screens
data w1 type n value 58. "Stock in warehouse 1
data w2 type n value 51. "Stock in warehouse 2
data w1 type n value 44. "Stock in warehouse 3
data dmnd type n value 900. "Monthly demand
data cap type n value 25. "Manufacturing capacity
data days type n value 30. "Days in a month
data inc type n value 0. "Increase in capacity

You need to calculate the total number of screens available. So you need to calculate the
sum of "w1", "w2", and "w3". You need to store the result in "tvscr". You can use the
compute statement to perform the calculation.

compute tvscr = w1 + w2 + w3. "Total stock

You then need to calculate the daily demand of the screens. To do this, you can use the
divide statement to divide the daily demand by "30".

divide dmnd by days. "Daily demand

You now need to calculate the difference in the current manufacturing capacity and the
daily demand. This difference represents the increase needed in the manufacturing
capacity. To calculate the desired difference, you use the subtract statement. You then
assign this value to the variable "inc" by using the move statement.

subtract cap from dmnd. "Required increase


move dmnd to inc. "Assign resultant value

Question

Suppose you are a programmer developing an ABAP program. You have defined
the variables "stock", "demand", "req", and "supply" in the ABAP program.

Calculate the difference of "demand" and "supply", and store the result in "req".

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

20
*
REPORT MATERIAL
data stock type n value 1524.
data demand type n value 56.
data supply type n value 52.
data requirement type n value 0.
data output type string value 'The requirement is' .
MISSING CODE.

Answer

You type req = demand - supply to perform the desired calculation. You can
also prefix compute in the statement.

Summary

You can perform various assignment and calculation operations on data in an ABAP
program. You use ABAP statements to perform data manipulations. The most commonly
used assignment statements are clear and move.

The most commonly used statements for performing mathematical calculations are add,
divide, multiply, subtract, and compute.

Table of Contents

| Top of page |

| Learning objective |

| 1. Performing assignments |

| 2. Performing calculations |

| Summary |

Copyright 2006 SkillSoft. All rights reserved.


SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

21
Using ABAP Statements
Learning objective

After completing this topic, you should be able to recognize how to control ABAP program
flow in given scenarios.

1. Using conditional statements

When creating ABAP programs, you need to control the program flow to obtain the desired
output. For example, you may want to check the result of a logical expression, and then
display the output on the screen based on the result.

To control the flow of an ABAP program, you can use various types of ABAP statements.

The commonly used ABAP statement types for controlling the ABAP program flow are

conditional
control
looping
conditional
You use conditional statements to define criteria for executing other ABAP statements.
The if and case statements are conditional statements that enable you to check logical
expressions in an ABAP program.
control
You use control statements for branching the ABAP program and controlling the
execution of the ABAP program. The exit, stop, and continue statements are control
statements that enable you to terminate, pause, or continue the execution of ABAP
programs.
looping
You use looping statements when you want to execute a set of ABAP statements multiple
times. The do and while statements are looping statements that enable you to execute
ABAP statements multiple times without significantly increasing the length of the program.

The if statement is the most commonly used conditional statement in ABAP programming.
The statement begins with the if keyword and ends with the endif keyword. The elseif
and else clauses are used to check the value of expression1 and expression2. If an
expression holds true, the corresponding ABAP statements are executed.

if expression1.
ABAP statements.
[elseif expression2.
ABAP statements.]
22
[else
ABAP statements.]
endif.

For example, you can execute different ABAP statements based on the value of the
variable "a".

if a = 0.
write / 'The value of a is equal to zero!'.
elseif a = 1.
write / 'The value of a is equal to one!'.
else.
write / 'The value of a is equal to one!'.
endif.

The elseif and else clauses are optional. If you only want to perform actions based on
the value of one expression, you don't use the elseif and else clauses in the if
statement.

if expression1.
ABAP statements.
endif.

You use the else clause when you want to perform alternate actions based on all other
expressions evaluating to false.

if expression1.
ABAP statements.
else expression2.
ABAP statements.
endif.

Suppose you want to use the else clause in the if statement to check the value of
"quantity". You want to display the output "The value is equal to zero!" when the value of
"quantity" is "0"; otherwise you want to display "The value is nonzero!".

if quantity = 0.
write / 'The value is equal to zero!'.
else.
write / 'The value is nonzero!'.
endif.

Suppose you want to display different outputs based on the value of "quantity" being equal
to 22, greater than 22, or less than 22. Specify the appropriate conditional statement to
check the condition quantity > 22.

if quantity = 22.
write / 'The value is equal to 22 !'.
MISSING CODE > 22.

23
write / 'The value is greater than 22 !'.
else.
write / 'The value is less than 22 !'.
endif.

You type elseif quantity to specify the conditional statement.

You have checked the value of the variable "quantity" by using the elseif clause in the if
statement.

if quantity = 22.
write / 'The value is equal to 22 !'.
elseif quantity > 22.
write / 'The value is greater than 22 !'.
else.
write / 'The value is less than 22 !'.
endif.

In addition to the if statement, you can use the case statement to execute ABAP
statements based on the value of a variable. You mostly use the case statement when you
want to trigger more than three actions.

The case statement begins with the case keyword and ends with the endcase keyword.
The when clause compares the value of a variable with another variable or a constant.
Based on the value of the variable, the appropriate ABAP statements are executed.

case variable.
when value1.
ABAP statements.
when value2.
ABAP statements.
endcase.

Suppose you are a developer developing an ABAP program. You have defined a variable
"counter". You want to check the value of "counter". You want to display "The value of
counter is one." when the value is "1", display "The value of counter is two." when the value
is "2", and display "The value of counter is three." when the value is "3".

data counter type n value 2.


data one type n value 1.
case counter.
when one.
write / 'The value of counter is one.'.
when 2.
write / 'The value of counter is two.'.
when 3.
write / 'The value of counter is three.'.
endcase.

24
This code compares the value of the variable "counter" with that of the variable "one". If
both the values are equal, the write statement is executed.

when one.
write / 'The value of counter is one.'.

This code checks if the value of the variable "counter" is equal to the constant "2", and
executes the write statement if the condition holds true.

when 2.
write / 'The value of counter is two.'.

This code compares the value of the variable "counter" with that of the constant "3". If both
values are equal, the write statement is executed.

when 3.
write / 'The value of counter is three.'.

Question

Suppose you have defined a variable "tvorder" that stores the number of televisions
for which an order has been placed. You want to display a specific output based on
the quantity of the order. The orders with quantity greater than five qualify as bulk
orders.

Complete the missing code that enables you to define the condition to check the
value of "tvorder".

data tvorder type n value 25.


MISSING CODE.
write / 'This is a bulk order.'.
else.
write / 'This is not a bulk order.'.
endif.

Answer

You type if tvorder > 5. to define the condition to check the value of "tvorder"

2. Looping and control statements

Looping statements enable you to execute ABAP statements multiple times without writing
the statement each time. This helps you reduce the length of the ABAP program.

The looping statements most commonly used are do and while. The do statement is an
unconditional looping statement. It executes a program block the number of times you
specify.

25
The while statement is a conditional looping statement. It executes a program block if a
logical expression holds true.

The do statement begins with the do keyword and ends with the enddo keyword. Using the
do statement, you can specify the number of times you want to execute the ABAP
statements enclosed within the do and enddo keywords.

do n times.
ABAP statements.
enddo.

Suppose you want to execute the write statement 15 times to display numbers from 1 to
15.

data num type n value 1.


MISSING CODE.
write / n.
n = n + 1.
enddo.

You type do 15 times to specify the looping statement.

You have defined a loop that is executed 15 times by using the do statement.

data num type n value 1.


do 15 times.
write / n.
n = n + 1.
enddo.

The loop begins with the while keyword and ends with the endwhile keyword. You
specify a logical expression with the while keyword.

The ABAP statements enclosed in the program block are executed in a loop till the logical
expression holds true. The execution of the loop is terminated if the logical expression is
false.

while logical expression.


ABAP statements.
endwhile.

For example, you can use the while statement to execute a loop and increment the value
of the variable "counter". When the value of "counter" equals 20, the loop execution is
terminated.

while counter < 20.


counter = counter + 1.
endwhile.
26
Control statements enable you to perform branching in an ABAP program and control its
execution. The commonly used control statements are

continue
exit
stop

You specify the continue statement in a loop to terminate the execution of a loop pass
and proceed to the next loop pass. The continue statement passes the program
execution to the beginning of the loop in which you have specified the statement.

continue.

For example, if you execute this ABAP program code, the continue statement is
encountered when the value of "counter" is "2". The execution of the loop pass is
terminated and the execution begins from the top of the loop. So the write statement is
not executed when the value of "counter" is "2".

Therefore, the output of the program execution is


The value of counter is: 1
The value of counter is: 3

data counter type n value 0.

do 3 times.
counter = counter + 1.
if counter = 2.
continue.
else.
write / 'The value of counter is:'.
write counter.
endif.
enddo.

The exit statement passes the ABAP program execution to the statement after the end of
the loop in which you have specified the statement. You use the exit statement when you
want to terminate the execution of a loop in an ABAP program.

exit.

For example, when the exit statement is encountered during the execution of this code,
the execution of the loop is terminated. Therefore, the write statement outside the loop is
executed to display the message "The loop has been terminated.".

data counter type n value 0.

do 3 times.
counter = counter + 1.

27
exit.
write / 'The value of counter is:'.
write counter.
enddo.
write / 'The loop has been terminated.'.

The stop statement terminates the execution of a block of code in the ABAP program and
passes program execution to the next block.

For example, you specify the stop statement in the "start of selection" section of an ABAP
program. When the stop statement is encountered during program execution, the
execution is passed to the "end of selection" section.

stop.

Suppose you want to create an ABAP program that uses the conditional, control, and
looping statements to display the first ten even numbers.

You want to define a variable "counter" that has an initial value "2". You then want to define
a loop that is executed ten times. You want to use the do and enddo statements to do this.
You also want to display "The even numbers are:" when program execution begins.

data counter type n value 2.


write / 'The even numbers are:'.
do 10 times.
* ABAP statements come here *
enddo.

You want to display the value of "counter" and increment the value by two each time the
loop is executed. Incrementing the value by two ensures that "counter" always contains an
even number.

data counter type n value 2.


write / 'The even numbers are:'.
do 10 times.
write / counter.
counter = counter + 2.
enddo.

Suppose you want to terminate the execution of the loop when the value of "counter" is "8".
You can check the value by using the if statement, and trigger the desired response.

data counter type n value 2.


write / 'The even numbers are:'.
do 10 times.
if counter = 8.
exit.
else.
write / counter.

28
endif.
counter = counter + 2.
enddo.

Question

Suppose you have defined a variable "quantity". You want to increment the value of
"quantity" five times and display an output based on the value. In addition, you want
to terminate the loop when the value of "quantity" is "3".

Complete the missing code that enables you to define the desired conditional
statement.

data counter type n value 0.


do 5 times.
quantity = quantity + 1.
MISSING CODE.
when 1.
write / 'This is the first loop.'.
when 2.
write / 'This is the second loop.'.
when 3.
exit.
endcase.
enddo.

Answer

You type case quantity to define the desired conditional statement.

Summary

You need to control the flow of ABAP programs to ensure that the programs produce the
desired results on execution. You can use various conditional, control, and looping
statements in ABAP to control ABAP program flow.

The conditional statements, such as if and when, enable you to check conditions by using
logical expressions in a program. You can use the result of such conditions to control the
ABAP program.

The control statements, such as continue, exit, and stop, enable you to terminate the
execution of the loops and program blocks in an ABAP program.

The looping statements, such as do and while, enable you to execute ABAP statements
multiple times without writing the statements each time you want to execute them.

Table of Contents
29
| Top of page |

| Learning objective |

| 1. Using conditional statements |

| 2. Looping and control statements |

| Summary |

Copyright 2006 SkillSoft. All rights reserved.


SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners

30
Creating an ABAP Program
Learning objective

After completing this topic, you should be able to create a simple ABAP program in a given
scenario.

Exercise overview

In this exercise, you're required to create a new ABAP program to display the desired result
in a given scenario.

This involves the following tasks:

creating a new program


performing data manipulation
controlling program flow

Task 1: Creating a new program

Suppose you are a developer and need to create a new ABAP program to display a list
containing numbers from 1 to 20. You need to create the program by using the ABAP
Editor.

Step 1 of 2

The SAP Easy Access window has been opened for you. You want to access the
ABAP Editor and create a new executable ABAP program. You want to specify the
program name as "ynumbers" and the program title as "Program to print 20
numbers".

What steps enable you to create the desired ABAP program?

Options:

1. Type SE38 in the command field and click Enter. Then type ynumbers in the Program field
and click Create. Type Program to print 20 numbers in the Title field, select
Executable program from the Type drop-down menu, and click Save. Finally, click
Local Object.
2. Type SE83 in the command field and click Enter. Then type ynumbers in the Program field
and click Create. Type Program to print 20 numbers in the Title field, select
Module pool from the Type drop-down menu, and click Choose. Finally, click Save.

Result

31
You type SE38 in the command field and click Enter. Then type ynumbers in the
Program field and click Create. Type Program to print 20 numbers in the
Title field, select Executable program from the Type drop-down menu, and click
Save. You finally click Local Object.

Step 2 of 2

You need to define a variable "counter" that contains the value "0". You use the
variable to store the numeric values that you need to display in the result. In
addition, you need to define a literal "message" that contains the value "The value of
counter has been reset. The new value is: 0".

Which ABAP statements enable you to define the desired data objects?

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
MISSING CODE
MISSING CODE
write / 'Here is the list of numbers:'. "displaying a
message

Options:

1. data counter type I value 0.


2. data counter value 0 type n.
3. data final type c value 'The final value of counter is 0'.
4. data final type c value "The final value of counter is 0".

Result

You type data counter type I value 0. to define the variable and type data
final type c value 'The final value of counter is 0'. to define
the literal.

Option 1 is correct. When you define a variable by using the data statement, you
specify the name, type, and value of the variable in the data statement. You can
also define a variable without specifying its value.

Option 2 is incorrect. When you use the data statement to define a variable, you
first define the variable type and then assign a value to it.

Option 3 is correct. When you define a literal by using the data statement, you
specify the name, type, and value of the literal.

Option 4 is incorrect. When you define a literal by using the data statement, you
enclose the value of the literal within single quotes (').

32
Here is the completed code defining the data objects.

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.

Task 2: Performing data manipulation

You have already created a new ABAP program "ynumbers" and defined the required
variables. You now want to introduce a loop in the program to display the list of numbers
from 1 to 20.

Step 1 of 3

You want to display the numbers from 1 to 20 by using a loop.

Which ABAP statement enables you to define the desired loop?

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
MISSING CODE "beginning of the loop
enddo. "end of the
loop

Options:

1. case 20 times.
2. do 20 times.
3. while 20 times.

Result

You type do 20 times. to define a loop that is executed 20 times.

Option 1 is incorrect. The case statement is a conditional statement and not a


looping statement. You use it to check the value of a variable. The case statement
is used along with the endcase and when statements.

33
Option 2 is correct. You use the do statement to define a loop. When defining a do
statement, you specify the number of times you want to execute the loop. The loop
begins with the do and ends with the enddo statement.

Option 3 is incorrect. The while statement is used to define a loop based on the
result of a logical expression. You need to specify the logical expression in the
while statement.

Here is the completed code that defines a loop by using the do statement.

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
do 20 times. "beginning of the
loop
enddo. "end of the loop

Step 2 of 3

You want to increment the value of "counter" by one each time the loop is executed.
You can print the value of "counter" each time to display numbers from 1 to 20.

Which ABAP statements enable you to perform the desired numeric operation?

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
do 20 times. "beginning of
the loop
MISSING CODE
enddo. "end of the
loop

Options:

1. add counter = counter +1.


2. add counter to 1.
3. compute counter = counter + 1.
4. counter = counter + 1.

34
Result

You can type compute counter = counter + 1. or counter = counter +


1. to increment the value of "counter".

Option 1 is incorrect. This is not the valid syntax for the add statement. You use the
add statement to calculate the sum of two variables and store the result in one of
them.

Option 2 is incorrect. You use the add statement to calculate the sum of two
variables and store the result in one of them.

Option 3 is correct. You use the compute statement to add a number to the value of
a variable.

Option 4 is correct. You use the compute statement to increment the value of a
variable. However, the keyword "compute" is optional. You can write the statement
without "compute".

Here is the completed code that defines an arithmetic expression to increment the value of
"counter" each time the loop is executed.

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
do 20 times. "beginning of the
loop
counter = counter + 1.
enddo. "end of the loop

Step 3 of 3

Each time the loop is executed, you want to store the updated value of "counter" in
the variable "out".

Which ABAP statement enables you to perform the desired assignment operation?

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
35
do 20 times. "beginning of
the loop
counter = counter + 1. "incrementing the value
MISSING CODE "assign the updated
value
enddo. "end of the
loop

Options:

1. clear counter to out.


2. clear out = counter.
3. move counter in out.
4. move counter to out.

Result

You type move counter to out. to store the updated value in the variable "out".

Option 1 is incorrect. You use the clear statement to change the value of a variable
to zero. You only specify the name of one variable in the clear statement.

Option 2 is incorrect. You use the clear statement to change the value of a variable
to zero. You only specify the name of one variable in the clear statement.

Option 3 is incorrect. You use the "to" keyword in the move statement.

Option 4 is correct. The move statement enables you to store the value of one
variable in another variable.

Here is the completed code that stores the updated value of the variable "counter" in the
variable "out".

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
do 20 times. "beginning of the
loop
counter = counter + 1. "incrementing the value
move counter to out. "assign the updated value
enddo. "end of the loop

Task 3: Controlling program flow

36
Each time the loop is executed, a new value is stored in the variable "out". You want to
display the value each time. This enables you to display a list of numbers from 1 to 20.

Step 1 of 3

Which ABAP statement enables you to display the updated value of "out" each time
the loop is executed?

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
do 20 times. "beginning of
the loop
counter = counter + 1. "incrementing the value
move counter to out. "assign the updated
value
MISSING CODE "display the updated
value
enddo. "end of the
loop

Options:

1. print / 'out'.
2. print / out.
3. write / 'out'.
4. write / out.

Result

You type write / out. to display the updated value of the variable "out".

Option 1 is incorrect. You use the write statement to display the value of a
variable. In addition, you do not enclose the variable name in single-quotes (').

Option 2 is incorrect. You use the write statement to display the value of a
variable.

Option 3 is incorrect. You do not enclose the variable name in single-quotes (').

Option 4 is correct. You use the write statement to display the value stored in a
variable.

Here is the completed code that enables you to display a list of numbers from 1 to 20.
37
*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
do 20 times. "beginning of the
loop
counter = counter + 1. "incrementing the value
move counter to out. "assign the updated value
write / out. "display the
updated value
enddo. "end of the loop

Step 2 of 3

Suppose you want to modify the code to ensure that the value 11 is not displayed in
the list. Therefore, you need to use conditional statements to check the value and
use control statements to control the execution of the loop.

Which ABAP statement enables you to control the flow of the ABAP program to
display the desired result?

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
do 20 times. "beginning of the loop
counter = counter + 1. "incrementing the value
move counter to out. "assign the updated value
MISSING CODE "check the value of the
variable
continue. "go to the beginning
of the loop
else.
write / out. "display the
updated value
endif.
enddo. "end of the loop

Options:

1. check out = 11.


2. if out = 11.
3. when 11.
38
4. when out = 11.

Result

You type if out = 11. to check the value of the variable "out".

Option 1 is incorrect. You use the if statement to trigger a response based on the
value of a logical expression.

Option 2 is correct. You use the if statement to check whether or not a logical
expression holds true.

Option 3 is incorrect. You use the if statement with the else and endif
statements.

Option 4 is incorrect. You do not use the when statement with the else and endif
statements. In addition, you do not define a logical expression in the when
statement.

Here is the completed code that displays a list of numbers from 1 to 20, except the number
11.

*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
do 20 times. "beginning of the loop
counter = counter + 1. "incrementing the value
move counter to out. "assign the updated value
if out = 11. "check the value of the
variable
continue. "go to the beginning of
the loop
else.
write / out. "display the updated
value
endif.
enddo. "end of the loop

Step 3 of 3

Suppose you want to modify the code further to ensure that the value 13 is not
displayed in the list.

Which conditional statement enables you to check the condition?

39
*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
do 20 times. "beginning of the loop
counter = counter + 1. "incrementing the value
move counter to out. "assign the updated value
if out = 11. "check the value of
the variable
continue. "go to the beginning
of the loop
MISSING CODE "check the second value
continue. "go to the beginning
of the loop
else.
write / out. "display the
updated value
endif.
enddo. "end of the loop

Options:

1. else if out = 13.


2. elseif out = 13.
3. if else out = 13.
4. ifelse out = 13.

Result

You type elseif out = 13. to check another condition for the variable "out".

Option 1 is incorrect. There should be no blank space in the elseif statement.

Option 2 is correct. You use the elseif statement with the if, else, and endif
statements.

Option 3 is incorrect. You use the elseif statement to check the value of a logical
expression.

Option 4 is incorrect. You use the elseif statement to check the value of a logical
expression.

Here is the completed code that displays a list of numbers from 1 to 20, except the numbers
11 and 13.

40
*&----------------------------------------------------*
*& Report YNUMBERS *
*&----------------------------------------------------*
data counter type I value 0.
data out type I value 0.
data final type c value 'The final value of counter is 0'.
write / 'Here is the list of numbers:'.
do 20 times. "beginning of the loop
counter = counter + 1. "incrementing the value
move counter to out. "assign the updated value
if out = 11. "check the value of the
variable
continue. "go to the beginning of
the loop
elseif out = 13. "check the second value
continue. "go to the beginning of
the loop
else.
write / out. "display the updated
value
endif.
enddo. "end of the loop

Table of Contents

| Top of page |

| Learning objective |

| Exercise overview |

| Task 1: Creating a new program |

| Task 2: Performing data manipulation |

| Task 3: Controlling program flow |

Copyright 2009 SkillSoft. All rights reserved.


SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

41
Working with Internal Tables
Learning objective

After completing this topic, you should be able to recognize how to read and modify data
from the database using internal tables in a given scenario.

1. Defining internal tables

Report programs are ABAP programs that extract the desired data from databases and
display the extracted data in the requisite format for analysis.

When you run a report program, it displays two types of screens: selection and output.

The selection screen is the first screen where you provide a selection criteria.

Based on the selection criteria, a list is displayed on the second screen, which is also called
the output screen. A list is the report you create.

For example, you can create a report program to display marketing or sales reports based
on a specified range of dates.

Note

A report program may not have a selection screen.

A report program doesn't display the data stored in database tables directly on the screen.

It first fetches the data from database tables into a temporary data type object called
internal table.

The report program then reads the data from the internal table and modifies it as required.

The program then displays the data on the screen.

An internal table is stored in the SAP Web Application Server's (SAP Web AS) memory,
and the table remains in the memory as long as the corresponding ABAP program is
running.

The structure of the internal table consists of two parts:

body
header line
body
42
The body contains all records of the internal table. The number of rows and columns of
the body depends on the number of rows and columns you fetch from the corresponding
database table. The name of an internal table always refers to its body.
header line
The header line is an optional part of internal tables whose structure and name are the
same as that of the body, but contains only one row. The header line functions as a
buffer. If you use the header line, each row that is inserted into or read from an internal
table is first stored in the header line.

To access a field in the header line, you use this syntax:

header_line_name-field_name

Note that an internal table can also be read without the header line using work area. You
can also insert data into an internal table using work area without the header line.

Before you start using an internal table, you need to define its structure using the data
statement.

You define the body of an internal table by using internal_table_name occurs n,


where n denotes the default number of records in the internal table.

data : begin of internal_table_name occurs n,


field 1 (data type) (like database_table_name-dbfield 1),
field 2 (data type) (like database_table_name-dbfield 2),
end of internal_table_name.

You define the header line of an internal table by using begin of before the body
definition.

Then you specify the comma-separated field names, along with their data types, that the
internal table can contain. You can assign the data type of a field in a database table to a
field in an internal table by using like.

You end the definition of the internal table by using the end statement.

In addition to defining an internal table with a new structure, you can define an internal table
by copying the fields of an ABAP Data Dictionary (DDIC) structure.

This may be required when you need to use some standard structure to create an internal
table.

For this, you use like in the internal table definition line.

data : internal_table_name like copied_internal_table_name occurs n.

43
When you use like, the internal table doesn't contain a header line by default.

You can mention a header line for the internal table by using with header line at the
end of the occurs clause.

data : internal_table_name like copied_internal_table_name occurs n with header line.

Suppose you need to create an internal table "itab_billing" for a report program that lists all
the billing documents with their document numbers, dates, and prices based on a specified
date range. The default number of records you want for the internal table is 10.

data : begin of MISSING CODE,


document_number like billing-document_number, "Billing
document
date like billing-date, "Creation date
price like billing-price, "Total price
end of itab_billing .

To do this, you type itab_billing occurs 10 in your code.

You have created the "itab_billing" internal table. Now you can use the table to store the
data required for the billing document report program.

data : begin of itab_billing occurs 10,


document_number like billing-document_number, "Billing
document
date like billing-date, "Creation date
price like billing-price, "Total price
end of itab_billing .

Question

Suppose you need to create a sales report program. This program displays the
monthly sales figure of various sales persons. It fetches data from the database
table "sales" and displays data from the table fields name, date, and amount. For
this, you need to define an internal table with ten default records used by the report
program.

Complete the code to define the internal table.

data : MISSING CODE ,


name like sales-name, "Sales person
date like sales-date, "Sales date
amount like sales-amount, "Sales amount
end of itab_sales.

Answer

44
To define the required internal table, you use begin of itab_sales occurs
10,.

2. Fetching data into internal tables

After you define an internal table, you can fetch data from database tables into the internal
table. You can then use the internal table data to create a list.

To fetch data from database tables into an internal table, you use

the select statement


the select...endselect and append statements
the select statement
You use the select statement to fetch all or specific fields from a database table into an
internal table. The select statement fetches all the records of the database table at one
go.
the select...endselect and append statements
You use the select...endselect statement to fetch each row of a database table one
by one into the header line of an internal table. Then within the select...endselect
statement you can modify the header line data and use the append statement to write the
data from the header line to the internal table body.

You use these statements when you need to modify the data extracted from a database
table before writing the data to an internal table.

However, note that using the select statement, and then looping through the internal
table to modify the fields is more efficient than selecting one row at a time from the
database using select, append, and endselect.

When you use the select statement, you need to specify the field names whose data you
want to fetch from a database table. In addition, you use the into table clause to specify
the internal table name and the from clause to specify the database table name.

select database_table_name~field1
database_table_name~field2
into table internal_table_name
from database_table_name.

Note

To fetch all the fields of a database table, you specify * after select instead of the
database table's field names. In addition, specifying the database table name along
with the field names is optional.

45
Suppose you need to fetch data from the database table "materials" into the
"itab_materials" internal table to create a list of materials procured from all vendors. The list
should display the number, procurement date, and type of the material.

select materials~material_number
materials~procurement_date
materials~type
MISSING CODE itab_materials MISSING CODE materials.

To do this, you type into table and from in the code

You have completed the code to fetch the required data from the "materials" table into the
internal table "itab_materials" to create a list of the material procured from all vendors.

select materials~material_number
materials~procurement_date
materials~type
into table itab_materials from materials .

When using the select...endselect and append statements, you place the append
statement inside the select...endselect statement.

select database_table_name~field1
database_table_name~field2
from database_table_name into header_line_name
"code to modify the header line data comes here
append internal_table_name.
endselect.

Suppose you need to create a list of your company's products and their prices. In the list,
you need to add a sales tax of 2% to the current prices. To create this list, first you need to
fetch data from the database table "products" into the "itab_products" internal table.

MISSING CODE * from products into itab_products


"code to add 2% to product price comes here
MISSING CODE itab_products.
endselect.

To do this, you type select and append in the code.

You have completed the code to fetch data from the "products" table into the
"itab_products" table and update the prices of the products in the "itab_products" table with
2% sales tax.

select * from products into itab_products


"code to add 2% to product price comes here
append itab_products .
endselect.

46
Question

Suppose you need to create a list of all items sold to date. To create the list, you
need to fetch the code, type, and name of all items from the database table "items"
into the internal table "itab_items."

What actions would you perform to do this?

Options:

1. Use the select statement to fetch the required rows, use the into table clause to specify
the internal table name, and then use the from clause to specify the database table name
2. Use the loop at...endloop statement to fetch the required rows, use the into clause to
specify the internal table name, and then use the like clause to specify the database table
name

Answer

You use the select statement to fetch the required rows, you use the into table
clause to specify the internal table name, and then you use the from clause to
specify the database table name.

3. Reading data from internal tables

After you have fetched data from a database table into an internal table, you can read the
data from the internal table to populate the output screen of an interactive report.

To read data from the internal tables, you use either of the two statements:

Loop at...endloop
Read table
Loop at...endloop
You use the loop at statement when you need to display one or more rows from the
internal table on the screen.

Here is the syntax of this statement:

loop at internal _table_name from m to n .


"code to process the internal table data comes here
endloop .

In the syntax, m denotes the row number from where the data needs to be read and n
denotes the row number till which the data needs to be read.
Read table
You use the read table statement when you need to display only a specific row of an
internal table on the screen.
47
Here is the syntax of this statement:

read table internal_table_name index i .

Here i denotes the row number you want to read.

Suppose an internal table "itab_customers" contains customer account records. All the
account records that lie between rows 49 and 76 are the accounts that were acquired
during the current year. You want to read and display these account details from the
internal table.

MISSING CODE itab_customers from 50 to 75.


"code to display the data on the screen comes here
endloop.

To do this, you type loop at in the code.

You have completed the code to read and display the required account details from the
internal table "itab_customers." Now you can display the list of customer accounts acquired
during the current year.

loop at itab_customers from 50 to 75.


"code to display the data to the screen comes here
endloop.

Suppose an internal table has data sorted in decreasing order of the total amount due from
vendors. You need to read details of the vendor who has the maximum amount due.

MISSING CODE itab_vendors index 1.

To do this, you type read table in your code.

You have completed the code to read details of the vendor who has the maximum amount
due. You can now list the details of the vendor who has the maximum due amount.

read table itab_vendors index 1.

Question

Suppose an internal table "itab_materials" contains records that store material


details. Material records from 100 to 115 contain information about the material that
the company no longer produces. The management of your company wants to view
these material details to plan production of the materials it wants to produce again.

What actions do you perform to do this?

Options:

48
1. Use the loop at...endloop statement to read the internal table "itab_materials," and the
from clause to read the rows between 100 and 115 of the internal table
2. Use the select...endselect statement to read the internal table "itab_materials," and
the into clause to read the rows between 100 and 115 of the internal table
3. Use the read table statement to read the internal table "itab_materials," and the from
clause to read the rows between 100 and 115 of the internal table

Answer

You use the loop at...endloop statement to read the internal table
"itab_materials," and you use the from clause to read the rows between 100 and
115 of the internal table.

4. Modifying data in internal tables

When you want to display data from database tables, sometimes you may need to modify
the existing data before displaying it.

For example, to create a report to analyze the impact of the standard bonus to be given to
all employees of a company, you may add the bonus amount to the salary field of a relevant
internal table.

After you have fetched data from database tables to internal tables, you may modify the
existing data in the internal tables.

For this, you can modify the header line data and then use the modify statement to update
a specific row in the internal table.

modify internal_table_name index i.

The modify statement modifies the internal table data with that of the header line at row
number i.

You can use the modify statement inside the loop at...endloop statement. If used
inside, index i is optional; otherwise, index i is mandatory. If you don't specify index i,
the data in the current row is updated.

Suppose your company decides to pay a 10% bonus to its workers. The management of
your company needs to analyze the financial obligation of this decision. You need to read
data from the internal table "itab_workers" and modify the table after adding 10% to each
worker's salary.

loop at itab_workers .
" code to add 10% to the salary come here
MISSING CODE itab_workers .
endloop .

To do this, you type modify in the code.


49
You have completed the code to update the internal table "itab_workers" after adding 10%
to each worker's salary. You can now display the modified data on the screen.

loop at itab_workers .
" code to add 10% to the salary come here
modify itab_workers .
endloop .

In addition to the modify statement, you can use the insert statement to modify an
internal table. However, unlike the modify statement, the insert statement inserts a new
row in the internal table.

insert internal_table_name index i.

The insert statement inserts a new row with values in the header line before the row
number i.

Similar to the modify statement, you can use the insert statement in the loop
at...endloop statement. If used inside, index i is optional; otherwise, index i is
mandatory. If you don't specify index i, a row is inserted before the current row.

Suppose a new employee has joined your company. You need to add a row to the internal
table "itab_employees," which stores employees details, for the new employee.

" variable to store total records in the internal table


data : records(20) type n value 0 .

loop at itab_employees .
" Calculating the total number of records in the table
records = records+1 .
endloop .
" Code to update the header line comes here
MISSING CODE itab_workers index records .

To do this, you type insert in the code.

You have completed the code to insert a new record in the "itab_employees" table.

" variable to store total records in the internal table


data : records(20) type n value 0 .

loop at itab_employees .
" Calculating the total number of records in the table
records = records+1 .
endloop .
" Code to update the header line comes here
insert itab_workers index records .

Question
50
Suppose you need to create a report program to display a list of products that your
company manufactures from the internal table "itab_products." Before displaying the
records, you need to add 2% to the products prices in the internal table.
Management requires this report to analyze the effect of the 2% increase in its
product prices on the company's revenue. To update the price, you need to modify
the internal table.

Complete the code to do this.

loop at itab_products.
''code to add 2% to product price comes here
MISSING CODE itab_products.
endloop.

Answer

You use the modify statement to add 2% to product prices in the internal table.

5. A sample program using internal tables

Suppose you are an ABAP application developer working for Brocadero, a manufacturing
company. You need to create a Purchase Order (PO) Journal report for Brocadero.

Each row in the report should display information about a purchase order PO number, the
purchasing group that created the PO, and the total PO amount.

The data required for the PO Journal report is spread across two database tables.
Information about PO numbers and corresponding purchasing groups is stored in the "PO"
table, and information about the PO number and PO amount of an item line within the PO is
stored in the "PO_Items" table.

This means that the "PO" table has rows with a unique PO number and the "PO_Items"
table may have multiple rows for a PO number based on the number of items present within
the PO number. PO_amount is mentioned against each line item of a PO number.

To create the PO Journal report, you first need to define the required internal tables to store
data from the database. Say that you create an internal table to store data from the PO
table and the calculated total amount of a PO.

Report PO Journal

data: begin of itab_PO_header occurs 0,


PO_Number like PO-Number, " PO number
PO_Group like PO-Group, " Purchasing Group
PO_Amount like PO_Items-Amount , "Total PO amount
end of itab_PO_header .

51
And you create another internal table to store data from the PO_Items table and to
calculate the total amount of a PO.

data: begin of itab_PO_items occurs 0,


PO_Number like PO_Items-Number,
PO_Amount like PO_Items-Amount,
end of itab_PO_items .

After defining the internal tables, you need to fetch data from the appropriate database
tables and populate the corresponding internal tables.

select PO~Number PO~Group


into itab_PO_header from PO.

select PO_Items~Number PO_Items~Amount


into itab_PO_items from PO_Items.

After you have fetched data into the itab_POJournal_header table, you need to calculate
the total amount of a PO number. For this, you need to use the itab_POJournal_item table.

" variable to store total amount of a PO


data : total_amount(20) type n value 0.

loop at itab_PO_header.
total_amount = 0.
loop at itab_PO_items.
"if the PO numbers of both the tables don't match
if itab_PO_items-PO_Number NE itab_PO_header-
PO_Number.
continue. "continue with the internal loop
else.
total_amount = total_amount + itab_PO_items-
PO_Amount.
endif.
endloop. "loop for the itab_PO_items table ends

After the calculation, you need to store the calculated value in the itab_POJournal_header
table.

" assigning the total PO amount to the header line of


" itab_PO_header
itab_PO_header-PO_Amount = total_amount .
" modifying itab_PO_header with the value of its header line
modify itab_PO_header .
endloop. "loop for the itab_PO_header table ends

After you have updated the itab_POJournal_header table with the total PO amount, you can
display the table data on the screen.

Supplement
52
Selecting the link title opens the resource in a new browser window.

Code window

View the full content of the code to create the PO Journal report.

Question

In a report program, you want to extract all rows from a database table, update data
in each extracted row, and then populate an internal table with the updated data.

Which statements would you use to perform these actions?

Options:

1. append
2. loop at...endloop
3. modify
4. select...endselect

Answer

You use the append and select...endselect statements to extract all rows
from a database table, update data in each extracted row, and then populate an
internal table.

Option 1 is correct. You use the append statement to add a row to the end of an
internal table. After you modify the data of an extracted row from the database table
using the headerline of the internal table, you can add the modified row from the
header line to the internal table using the append statement.

Option 2 is incorrect. You use the loop at...endloop statement to read data in
internal tables row by row. Here you want to fetch data from a database table into an
internal table. You can't do this using the loop at...endloop statement.

Option 3 is incorrect. You use the modify statement to modify data in an internal
table. Here data extracted from the database table needs to be updated before
adding to the internal table. Therefore, here you cannot use the modify statement.

Option 4 is correct. You use the select...endselect statement to fetch data


from a database table row by row into an internal table. Because here you want to
update each row extracted from the database table before adding the row to the
internal table, you need to use the select...endselect statement.

Summary

Internal tables are temporary data type objects that ABAP report programs use to fetch and
store data from databases and to modify and display the stored data.
53
To fetch data from database tables into internal tables, you use the select or
select...endselect and append statements.

To read data from internal tables, you use the loop at...endloop and read table
statements.

To modify internal tables, you use the modify and insert statements.

Table of Contents

| Top of page |

| Learning objective |

| 1. Defining internal tables |

| 2. Fetching data into internal tables |

| 3. Reading data from internal tables |

| 4. Modifying data in internal tables |

| 5. A sample program using internal tables |

| Summary |

Copyright 2006 SkillSoft. All rights reserved.


SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

54
Classical Reporting in ABAP
Learning objective

After completing this topic, you should be able to recognize how to control a report
program using events and messages in a given scenario.

1. Classical reporting

Report programs enable you to fetch desired data from database tables into internal tables,
read data from internal tables, modify the data in internal tables, and display the data in a
desired format for analysis.

You can create two types of report programs:

simple or classical report programs


interactive report programs
simple or classical report programs
You use a simple or classical report program to create a classical report in which you
fetch data from databases, process the data without changing the data in the database,
and display the processed data as a static list. Classical reports are not user interactive.
interactive report programs
An interactive report program fetches data from databases and generates a report with
which you can interact by using menus, typing input, and using function keys and push
buttons. Based on the user interaction, an interactive report program displays a detailed
static list and can call transactions and other reports.

Both classical and interactive report programs have modular structures. To make a report
program modular, you can use different components, also called processing blocks, of
report programs. Each component contains a group of ABAP statements and is executed at
a specific time.

These are two important components of classical report programs:

Event block
Subroutine
Event block
You can divide a report program into different event blocks. Each block contains one or
many lines of code and is executed based on an event, such as data input by users, that
occurs during the execution of a report program. This helps you customize your report
program to respond to a particular event in a way you want.

55
For example, in a report program, the initialization event block is executed immediately
after the program is loaded. You can write code to initialize variables inside this block.
Subroutine
A subroutine in a report program is a reusable block of code that can be executed
multiple times based on report needs. You can call and execute a subroutine from any
point, such as an event block, in a report program. You can also execute the subroutines
of one program from another program.

For example, you can write code to add two numbers in a subroutine. Then you can call
and execute this subroutine whenever you need to add two numbers in a program.

During the execution of classical report programs, control passes among different
components of the program.

However, the flow of control doesn't depend on the sequence of components in the source
code.

During the execution of classical report programs, the event blocks are run by the ABAP
runtime environment whereas the subroutines are called from within the owner report
program or by other report programs.

The ABAP runtime loads and runs an event block depending on the event that occurs.

After the execution of the event block, the control goes back to the ABAP runtime.
Depending on the next event that occurs, the ABAP runtime then executes the
corresponding event block.

During the execution of an event block, when the statement to execute a subroutine is
encountered, the control is passed by the event block to the subroutine.

After the execution of the statements in the subroutine, control goes back to the caller event
block.

Question

Which of the statements are true about the execution of report programs?

Options:

1. After the execution of a subroutine, control goes back to the ABAP runtime
2. Event blocks are run by the ABAP runtime environment
3. Subroutines are called from within the owner report program or by other report programs
4. The flow of control depends on the sequence of processing blocks in the source code

Answer

Event blocks are run by the ABAP runtime environment, and subroutines are called
from within the owner report program or by other report programs.
56
Option 1 is incorrect. A subroutine is executed from within an event block in a report
program when a statement to execute the subroutine is encountered. After the
subroutine is executed, control returns to the next statement in the event block.

Option 2 is correct. During the execution of report programs, if you want to respond
to a specific event, you need to implement the corresponding event block. When an
event occurs, the ABAP runtime passes the control to the corresponding event
block.

Option 3 is correct. Subroutines are processing blocks that are executed when the
ABAP statements to execute them are encountered. You can write an ABAP
statement to execute a subroutine either within the report program that contains the
subroutine or within a report program that doesn't contain the subroutine.

Option 4 is incorrect. Events in report programs occur in a predefined sequence. The


corresponding event blocks are executed in that sequence. Subroutines are
executed when the ABAP statements to execute them are encountered.

2. Events in classical reporting

Being event-driven, the execution of report programs is controlled by different events. You
may choose to make your report programs respond to these events by including required
ABAP statements in the corresponding event blocks.

An event block starts by specifying the event name and ends where the next event name
starts.

These are six important events that occur in sequence during the execution of report
programs:

Initialization
At selection-screen
Top-of-page
Start-of-selection
End-of-selection
End-of-page
Initialization
When a report program executes, initialization is the first event that occurs.

When creating a report program, you type Initialization. to start the corresponding
event block.

This event occurs only one time during the execution just before display of the selection
screen of the report program.

In the initialization event block, you perform initialization activities such as

57
assigning a default value to a variable.

The selection screen, if any, is displayed after this event.


At selection-screen
The at selection-screen event occurs immediately when you choose to execute a report
program after entering selection criteria on the selection screen.

When developing a report program, you start the corresponding event block by typing At
selection-screen.

If you don't have a selection screen in the report program, this event will not occur.

You use the at selection-screen event block to process user input before starting to
fetch data from database tables based on the user input.

For example, you can verify user input before displaying a list.

Top-of-page
The top-of-page event occurs immediately after the at selection-screen event. In addition,
when a report list has multiple pages to display, this event occurs every time a new page
starts.

You can start the top-of-page event block in your report program by typing Top-of-
page.

The top-of-page event signifies the start of the output of a report program. You can use
this event block to provide a heading and other header information such as date to your
report list.
Start-of-selection
The start-of-selection event occurs immediately after the top-of-page event.

In a report program, you start the corresponding event block by typing start-of-
selection.

You write the select statements to fetch data from database tables and process and
display the data within the start-of-selection event block.
End-of-selection
The end-of-selection event occurs after the start-of-selection event.

In a report program, you start the corresponding event block by typing end-of-
selection.

You may choose to first fetch all the required data from database tables into internal
58
tables within the start-of-selection event block and then process and display the
data within the end-of-selection event block.

This may become necessary when you need to fetch data from many database tables
and data processing logic is complex. In this case, you may want to segregate the data
fetching statements from the data processing statements for easy debugging or
modification of the program in the future.
End-of-page
The end-of-page event occurs when the end of page of a report is encountered while
generating the report list.

You can start the end-of-page event block in your report program by typing End-of-
page.

You can use this event black to provide some footer information for the report list.

It is important that you allocate some lines to the end-of-page area of a report list in the
line-count parameter of the report statement.

Here is a sample code.

report test line-count 60 (4) .

In this code, the total number of lines for the report list is 60, out of which the last four are
reserved for the end-of-page area.

Among the important classical report events, initialization is triggered first followed by at
selection-screen if a selection screen is present. Then the top-of-page and start-of-
selection events occur in sequence. Then the end-of-page event occurs if the end of a
report page is encountered, and the end-of-selection event occurs if the start-of-selection
event block ends. Some events occur only one time and some occur multiple times.

Writing ABAP statements in event blocks is not mandatory.

If you don't use an event block, the ABAP runtime puts all the ABAP statements inside the
default event block, start-of-selection. In this case, the code statements are
executed serially.

In cases where you use some or all the event blocks in your report program and place
some ABAP statements outside the event blocks, the ABAP statements are executed as
part of the start-of-selection event block.

However, if any declarative statement, such as defining variables, is not included within an
event block, this statement is executed when the program is loaded and not within the
start-of-selection event block.

59
Suppose you created a report program to generate a list of billing documents. For this, you
need to write an ABAP statement to fetch records from the database table "billings" inside
the appropriate event block.

report BillingInfo .
tables: billing .
parameters : charge type N.
data : begin of itab_billing occurs 0,
document_number like billing-document_number,
party like billing-party .
top-of-page .
" report footer
write: / 'PAGE-NO', SY-PAGNO .
MISSING CODE .
select document_number party from billing .
write: / itab_billing-document_number .
write: / itab_billing-party .
endselect .
end-of-page .
" report header
write: / 'Billing Information' .

To do this, you type start-of-selection in the code.

Now the select statement will be executed when the start-of-selection event occurs.

report BillingInfo .
tables: billing .
parameters : charge type N.
data : begin of itab_billing occurs 0,
document_number like billing-document_number,
party like billing-party .
top-of-page .
" report footer
write: / 'PAGE-NO', SY-PAGNO .
start-of-selection .
select document_number party from billing .
write: / itab_billing-document_number .
write: / itab_billing-party .
endselect .
end-of-page .
" report header
write: / 'Billing Information' .

Suppose you have created a report program to display a list of assets in your company. In
the list, you need to create a customized header for each page. For this, you need to write
appropriate ABAP statements in an appropriate event block.

MISSING CODE
" code to create list header comes here.
60
To do this, you type top-of-page in the code.

You have completed the code to create a header for each page of the list.

top-of-page.
" code to create list header comes here.

Question

Suppose you have created a classical report program to list all the customers with
outstanding amounts. In the program, you accept the late payment charge
percentage from the user and, based on that, you update the total outstanding
amount before displaying it. When creating the program, you did not use an event
block. Now you want to include each ABAP statement inside the appropriate event
block.

What actions would you perform to do this?

Options:

1. You use the end-of-page event block for the statements creating report footer, then use
the end-of-selection event block for the statements modifying the internal table, then
use the start-of-selection event block for the statements fetching data from
database table, and then use the top-of-page event block for the statements creating
report header.
2. You use the end-of-page event block for the statements creating report footer, then use
the at selection-screen event block for the statements modifying the internal table,
then use the initialization event block for the statements fetching data from
database table, and then use the end-of-selection event block for the statements
creating report header.

Answer

You use the end-of-page event block for the statements creating the report footer,
then you use the end-of-selection event block for the statements modifying the
internal table. After this, you use the start-of-selection event block for the
statements fetching data from the database table, and then you use the top-of-
page event block for the statements creating the report header.

3. Messages in classical reporting

During report program execution, you might need to communicate with the end user. You
can use the message statement in your report programs to do this.

By using message statements, you can also handle any error occurring during report
program execution and control the flow of the program.

message 'message_string' Type 'message_type' .

61
In the syntax, message_string is the message you want to communicate to the user and
message_type is the type of message.

There are six types of messages:

A - Abend
E - Error
I - Info
S - Status
W - Warning
X - Exit
A - Abend
You choose the A message type to terminate the report program after displaying a
customized message.

For example, to run a confidential report program, the user must enter a password. If an
incorrect password is entered three times, you can use this message type to display a
customized message and abort the program.
E - Error
By choosing the E message type, you can display an error message on the status bar of
the same screen where the error occurs. The data in the input fields are refreshed for the
user to enter new values. You can use this message type when a user enters data that
doesn't conform to the data type expected.

For example, in an input field where numbers should be typed, the user enters
characters.
I - Info
When you want to display some information in a dialog box, you can use the I message
type. When a user responds to this type of message, the program execution starts from
the statement next to the message statement.

You use this message type when you want to display information that a user should know
before proceeding.
S - Status
You can use the S message type to display a message on the status bar of the next
screen. Program execution continues immediately after the message statement.

You use this message type when you need to show the status of some processing based
on a user request, such as the number of rows fetched from a database table based on
user input.
W - Warning
You use the W message type to display warning messages to a user in response to an
error. The message is displayed on the same screen where the error occurs. Unlike an

62
error message, after a warning message the user input fields are not reset and the user
can correct the input.

You can use this message type when, for example, user input does not match any record
in the database.
X - Exit
You use the X message type when you need to handle a runtime error and display the
error message to the user before the program terminates.

Suppose in a report program, you need to display a sales document based on a date range.
Fetching data from the database tables into internal tables may take time because,
depending on the date range, the number of records to be fetched may be large. Therefore,
you need to display a status message while the fetching process continues.

select document_number sales_person date amount


form into itab_sales from sales .
message 'Fetching data...' Type MISSING CODE .
endselect .

To do this, you type 'S' in the code.

You have completed the code to display the status message when the
select...endselect statement executes.

select document_number sales_person date amount


form into itab_sales from sales .
message 'Fetching data...' Type 'S' .
endselect .

In the message statement, instead of typing the message string every time, you can store
frequently used message strings in a message class with a unique message ID. You can
then use the message ID in the message statement to display the required message string.

message ID 'message_id' Type 'message_type' .

A message class is a group of related messages with unique message IDs that you can use
any number of times in message statements. Each message class is also associated with a
unique message class ID.

You can create your own message class on the screen Message Maintenance: Initial
Screen. To open this screen, you use the SE91 transaction code.

Suppose you want to create a message class object with the ID "ZProcessing," and save it
in a package "Z001." You use packages to group related ABAP objects.

To create a message class object, you type ZProcessing in the Message class text box,
you click Create, you click Save on the standard toolbar, you type Z001 in the Package text
box of the Create Object Directory Entry dialog box, you click Save, and then you click
63
Continue on the Prompt for local Workbench request dialog box.

Alternatively, you can press F5 to start creating the message class object.

You have created a message class object. Now you can start adding customized messages
to the message class.

Suppose you need to create a message "Processing. Please wait..." for display every time
a long data processing action is performed. You want to add this message to the message
class "Zprocessing" you created earlier.

To add the message to the message class, you click Change, type Processing.
Please wait... in the Message short text field of the first row with message ID 000 on
the Messages tabbed page, and click Save.

Alternatively, you can press F6 to change the message class and press CTRL+S to save
the changes.

You have created a message. Now you use this message in your report programs by
referring to its message ID "000" in the message statement.

Question

Suppose to execute a report program, a user needs to enter a valid password. In the
program, you need to check if a user has entered wrong passwords three times. If
yes, you need to display an appropriate message and terminate the program.

Complete the code to do this.

message 'Wrong Password.' Type MISSING CODE .

Answer

To display an appropriate message before terminating a report program, you use the
"A" message type.

Summary

A classical report is the simplest type of report in which data is fetched from database
tables, processed, and then displayed. You can control the flow of the execution report
programs by using processing blocks, such as event blocks and subroutines.

Important events in classical reports are initialization, at selection-screen, top-of-page, start-


of-selection, end-of-page, and end-of-selection. You can make classical report programs
respond to these events by writing ABAP statements inside appropriate event blocks.

In addition to processing blocks, you can use messages to control the flow of the execution
64
of a report program. Using the message statement, you can communicate with users during
program execution. Depending on the situation, you can use different types of messages
A, E, I, S, W, and X. You can define your own messages, which are used often, and group
them into a message class.

Table of Contents

| Top of page |

| Learning objective |

| 1. Classical reporting |

| 2. Events in classical reporting |

| 3. Messages in classical reporting |

| Summary |

Copyright 2006 SkillSoft. All rights reserved.


SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

65
Interactive Reporting in ABAP
Learning objective

After completing this topic, you should be able to recognize how to create interactive report
programs for a given scenario.

1. Interactive reporting

Unlike the output of classical report programs, you can make the output of interactive report
programs respond to user interactions and display detailed information.

The output of interactive reports consists of two types of lists:

Basic list
Secondary list
Basic list
A basic list is displayed on the first output screen of interactive report programs. For
example, you can fetch data from database tables to display the payment details of a
customer.

The user can interact with each row of the basic list to view the corresponding detailed
information.

Within one interactive report, you can have only one basic list.
Secondary list
When you click a particular row in a basic list, the corresponding detailed information is
displayed in a secondary list. For example, if each row in the basic list displays the
payment details of a customer, you can make each row branch further to show the
contact details of the corresponding customer.

Within one interactive report, you can have up to 20 secondary lists.

Interactive reports allow you to interact in many ways:

by selecting a row in the basic list


by using menu commands
by using push buttons

You can call transactions and other reports based on user interaction.

Question

66
What are the features of interactive reports?

Options:

1. Interactive reports consist of two types of lists: basic and secondary


2. Secondary lists can respond to user interaction
3. You can interact with interactive reports by using menu commands
4. You can interact with interactive reports only to create secondary lists

Answer

Interactive reports consist of two types of lists, basic and secondary, and you can
interact with interactive reports by using menu commands.

Option 1 is correct. Interactive reports consist of basic and secondary lists. A basic
list is displayed first. A user can interact with this list to display detailed secondary
lists.

Option 2 is incorrect. You can interact with basic lists to display detailed secondary
lists. You can't interact with secondary lists.

Option 3 is correct. You can interact with interactive reports in many ways, such as
by selecting a line in the basic list, using menu commands, and using push buttons.

Option 4 is incorrect. In addition to displaying secondary lists, you can use


interactive reports to call transactions and other reports based on user interaction.

Based on the type of interaction with the basic list, a corresponding event is triggered. The
three types of events that can be triggered are

at line-selection
at pf<nn>
at user-command
at line-selection
The at line-selection event occurs when a user double-clicks a row in a basic list. You can
respond to this event by writing the required ABAP statements in the at line-
selection event block.
at pf<nn>
The at pf<nn> event occurs when a function key is pressed. Here "nn" denotes the
number of the function key. It can range between 01 and 24 for all function keys pressed
individually and along with the Shift key. For example, pf1 denotes the F1 function key
and pf24 denotes Shift+F12.

You can respond to these events by writing the required ABAP statements in the relevant
at pf<nn> event block.
at user-command

67
The at user-command event occurs when a user interacts with push buttons in a list, such
as a button labeled as "OK." You can assign your own function codes to push buttons and
then respond accordingly to user interactions.

You can check the function code of the user interaction using the if...endif and
case...endcase statements.

Suppose you have created a basic list of IT equipment in your company using the
"itab_ITAsset" internal table and the "IT_Asset" database table. On double-clicking a row in
the basic list, a secondary list should display the allocation information of the corresponding
IT equipment. You need to write ABAP statements to create the secondary list in an
appropriate event block.

start-of-selection .
'' Basic List
select asset_number acquired_date asset_value
into itab_ITAsset from IT_Asset .
write: / itab_ITAsset-asset_number .
write: / itab_ITAsset-acquired_date .
write: / itab_ITAsset-asset_value .
endselect .

MISSING CODE .
" code to create the secondary list comes here.

To begin the appropriate event block, you type at line-selection in the code.

You have completed the code to include the ABAP statements to create the secondary list
in the at line-selection event block. Now during report execution, a secondary list will
be created when the user double-clicks a row in the basic list.

start-of-selection .
'' Basic List
select asset_number acquired_date asset_value
into itab_ITAsset from IT_Asset .
write: / itab_ITAsset-asset_number .
write: / itab_ITAsset-acquired_date .
write: / itab_ITAsset-asset_value .
endselect .

at line-selection .
" code to create the secondary list comes here.

Suppose you have a basic list that displays the customers of your company and the
products they have bought to date. When a user selects a row in the basic list and presses
F1, a secondary list showing customer details corresponding to that row should be
displayed. Alternatively, when a user presses Shift+F12, a secondary list displaying
detailed product information should be displayed. You need to write the required ABAP
statements to create the secondary lists in appropriate event blocks.

68
start-of-selection .
"create the basic list here.
MISSING CODE .
"create the secondary list displaying customer details here.
MISSING CODE .
"create the secondary list displaying product details here.

To begin the appropriate event block, you type at pf1 and at pf24 in the code.

You have completed the code to write ABAP statements related to creating the secondary
list displaying customer details in the at pf1 event block. In addition, you have completed
the code to write the ABAP statements related to creating the secondary list displaying
product details in the at pf24 event block.

start-of-selection .
"create the basic list here.
at pf1 .
"create the secondary list displaying customer details here.
at pf24 .
"create the secondary list displaying product details here.

Suppose you have created a basic list of vendors and their outstanding amount using the
"itab_vendors" internal table and the "vendors" database table. When the user selects a
row in the basic list and presses Enter, a secondary list displaying vendor details should
appear. Assume you have assigned a function code "20" to the Enter key. You need to
write ABAP statements to create the secondary lists in appropriate event blocks.

start-of-selection .
'' Basic List
select vendor_code name amount_outstanding
into itab_vendors from vendors .
write: / itab_vendors-vendor_code .
write: / itab_vendors-name .
write: / itab_vendors-amount_outstanding .
endselect .

MISSING CODE .
If sy-ucomm=20 .
"system variable sy-ucomm stores function code of the key pressed
" code to create the secondary list comes here
endif.

To begin the appropriate event block, you type at user-command in the code.

You have completed the code to write ABAP statements to create secondary lists in the at
user-command event block. Now the secondary list showing vendor details will appear
when a user presses Enter after selecting a line in the basic list.

69
start-of-selection .
'' Basic List
select vendor_code name amount_outstanding
into itab_vendors from vendors .
write: / itab_vendors-vendor_code .
write: / itab_vendors-name .
write: / itab_vendors-amount_outstanding .
endselect .

at user-command .
If sy-ucomm=20 .
"system variable sy-ucomm stores function code of the key pressed
" code to create the secondary list comes here
endif.

Question

Suppose you have created a basic list displaying the accounts receivable report
using the "itab_billing" internal table and the "billing" database table. Now when a
user double-clicks a row in the basic list, you need to display a secondary list
displaying detailed information of your company's customers. When a user selects a
row in the basic list and presses F2, a secondary list displaying detailed information
about billing documents should be displayed.

What actions would you perform to complete this?

Options:

1. Use the at line-selection and at pf2 events to display the secondary lists when a
user double-clicks a line in the basic list and presses F2.
2. Use the at user-command event to display the secondary lists when a user double-clicks a
line in the basic list and presses F2.
3. Use the at pf2 event to display the secondary lists when a user double-clicks a line in the
basic list and presses F2.

Answer

You use the at line-selection and at pf2 events to display the secondary lists
when a user double-clicks a line in the basic list and presses F2.

2. Transporting data in interactive reports

You create secondary lists based on the row or field of a basic list on which the user
interacts. To make the name and value of the field available to the secondary list, you need
to transport the name and value from the basic list to the secondary list during report
execution.

70
You can transport data from basic lists to secondary lists using either of two commonly
used statements:

hide
get cursor
hide
The hide statement is a static way of passing values from a basic list to a secondary list.
This means that in the source code, you need to specify the field whose value you want to
pass from a basic list to a secondary list.

The hide statement must have a variable as its argument. It can be a field name of a
basic list or any other variable. In addition, you can specify a variable that is not
necessarily displayed on screen.
get cursor
The get cursor statement is a dynamic way of passing values from a basic list to a
secondary list. This means that during report execution, you can retrieve the name and
value of the field of a basic list with which a user interacts and transport the data to the
secondary list.

The hide statement stores the value of the variable "h" in a Hide area for the current output
line on screen. The Hide area can be compared to a table in which the ABAP runtime
stores the name and value of each Hide field for specified lines in a basic list.

hide h.

Suppose you have created a basic list of IT equipment in your company using the internal
table "itab_ITAsset." During report execution, you want all the values of the asset number
field to be stored in the Hide area. When a user double-clicks a row in the basic list, you
want to use the value of the asset number field and the "itab_ITAllocation" internal table to
create a secondary list that displays the allocation information of the corresponding IT
equipment.

" basic list

select asset_number acquired_date asset_value


into itab_ITAsset from IT_Asset .
write: / itab_ITAsset-asset_number .
MISSING CODE itab_ITAsset-asset_number .
write: / itab_ITAsset-acquired_date .
write: / itab_ITAsset-asset_value .
endselect .

at line-selection .
" secondary list
loop at itab_ITAllocation .
" if the asset number of itab_ITAllocation table matches
" the asset number of basic list row on which the user double-

71
clicked
" create the secondary list
if itab_ITAllocation-asset_number = itab_ITAsset-asset_number .
write: / itab_ITAllocation-asset_number .
write: / itab_ITAllocation-employee_name .
write: / itab_ITAllocation-allocation_date .
endif .
endloop .

To do this, you type hide in the code.

You have completed the code to store all the values of the asset number field of the basic
list in the Hide area and create the secondary list based on the basic list row on which the
user double-clicked.

" basic list

select asset_number acquired_date asset_value


into itab_ITAsset from IT_Asset
write: / itab_ITAsset-asset_number .
hide itab_ITAsset-asset_number .
write: / itab_ITAsset-acquired_date .
write: / itab_ITAsset-asset_value .
endselect .

at line-selection
" secondary list
loop at itab_ITAllocation
" if the asset number of itab_ITAllocation table matches
" the asset number of basic list row on which the user double-
clicked
" create the secondary list
if itab_ITAllocation-asset_number = itab_ITAsset-asset_number .
write: / itab_ITAllocation-asset_number .
write: / itab_ITAllocation-employee_name .
write: / itab_ITAllocation-allocation_date .
endif .
endloop .

The get cursor statement retrieves the name and value of the field on which the cursor is
placed during user interaction at runtime into the "f" and "v" variables, respectively.

get cursor Field f Value v.

Suppose you created a basic list that displays customers of your company and the products
they have bought to date. At runtime, if a user selects the customer code or the customer
name field from the basic list, the secondary list must display corresponding customer
details, such as address. Otherwise, a secondary list displaying information on other
customers who have bought the same product should be displayed. To achieve this, you

72
should be able to retrieve the name and value of the field on which the cursor is placed
during user interaction.

data: f(20) type C,


v(10) type N .

" basic list

select customer_code name product


into itab_Customer_Prod from Customer_Prod .
write: \ itab_Customer_Prod-customer_code .
write: \ itab_Customer_Prod-name .
write: \ itab_Customer_Prod-product .
endselect .

at line-selection .
" secondary list

MISSING CODE Field f Value v .


If f = "customer_code" or "name" .
''create a secondary list to display customer details here
using the value of v.
else .
''create the secondary list on other customers here using the
value of v.
endif .

To do this, you type get cursor in the code.

You have completed the code to create the required secondary lists.

data: f(20) type C,


v(10) type N .

" basic list

select customer_code name product


into itab_Customer_Prod from Customer_Prod
write: \ itab_Customer_Prod-customer_code .
write: \ itab_Customer_Prod-name .
write: \ itab_Customer_Prod-product .
endselect .

at line-selection
" secondary list

MISSING CODE Field f Value v .


If f = "customer_code" or "name" .
''create a secondary list to display customer details here
using the value of v.
73
else .
''create the secondary list on other customers here using the
value of v.
endif .

Question

Suppose you need to create a basic list for your company's warehouse, displaying
the quantity-in-hand status of material in the warehouse. To find out alternative
vendors to meet emergency demand for a material, a warehouse officer should be
able to double-click each row of the basic list to create a secondary list displaying
information about the vendors who have supplied the selected material in the past.

Complete the code to store all material codes displayed in the basic list that can be
retrieved to create the secondary list when the user interacts with the basic list.

select material_code material_name quantity


into itab_material from material .
write: \ itab_material-material_code .
write: \itab_material-material_name .
write: \itab_material-quantity .
MISSING CODE itab_material-material_code.
endselect .

Answer

To store the materials codes that can be retrieved during report execution based on
user interaction, you use the hide statement.

Summary

In interactive reports, you can make a basic list respond to user interactions to display the
desired, detailed secondary list. Based on how a user interacts, you can respond to the
interaction by writing desired ABAP statements in the event blocks at line-selection,
at pf<nn>, and at user-command.

In addition to using these event blocks to create secondary lists, you need to transfer the
name and value of the field on which the user interacts in the basic list. To do this, you use
either the hide or the get cursor statement.

Table of Contents

| Top of page |

| Learning objective |

| 1. Interactive reporting |
74
| 2. Transporting data in interactive reports |

| Summary |

Copyright 2006 SkillSoft. All rights reserved.


SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

75
Creating an Interactive Report Program
Learning objective

After completing this topic, you should be able to create an interactive report program for a
given scenario.

Exercise overview

In this exercise, you're required to create an interactive report program for a given scenario.

This involves the following tasks:

creating internal tables


using events and messages
transporting data between lists

Suppose you are working as an ABAP programmer for Awards Sportswear, a sports
apparel manufacturing company. The finance manager of the company wants to view billing
information such as billing document number, the business unit name issuing the billing
document, and the total billing amount for all the business units of the company in one
basic list.

In addition, the manager wants to be able to explore every document number in the basic
list to view detailed information of every billing document such as document number,
items in the document, and billing amount for each item. In addition, the manager wants to
be able to explore every business unit in the basic list to view detailed information about the
unit, such as unit code, address, and unit head's name.

Task 1: Creating internal tables

Data for the required reports is stored in the database tables "Billing_BU," "Billing," and
"BU." To create the report, first you need to create three internal tables one to create the
basic list and the other two to create the two secondary lists.

Step 1 of 4

You want to create an internal table "itab_billing_bu" from the database table
"Billing_BU" to create the basic list.

Type the code that indicates the creation of the internal table.

data: begin of itab_billing_bu MISSING CODE 0,


document_number type Billing_BU-document_number,
76
BU_code type Billing_BU-BU_code,
billing_amount type billing-billing_amount,
end of itab_billing_bu .

Result

You type occurs to indicate the creation of the itab_billing_bu internal table.

Step 2 of 4

You want to create another internal table "itab_billing" from the database table
"Billing" to create the secondary list displaying detailed information about billing
documents. You want to use the structure of the ABAP data dictionary (DDIC)
structure "ZBilling."

Complete the code to define the internal table "itab_billing."

data : itab_billing MISSING CODE ZBilling occurs 0 .

Result

You use the like clause to define the internal table itab_billing based on the DDIC
structure ZBilling.

Assume you have created the third internal table "itab_bu" from the database table "BU" to
create the secondary list that displays detailed information about a business unit.

data: begin of itab_bu occurs 0,


BU_code type Billing_BU-BU_code,
head_name type BU-head_name,
BU_address type BU-BU_address,
end of itab_bu .

Step 3 of 4

After defining the three internal tables based on the fields you need to display in
respective lists, you want to fetch data from the respective database tables as is into
the internal tables.

Which ABAP statement would you use to populate the three internal tables?

MISSING CODE document_number BU_code into itab_billing_bu


from Billing_BU .
77
MISSING CODE * into itab_billing from Billing .

MISSING CODE * into itab_bu from BU .

Options:

1. insert
2. append
3. read table
4. select

Result

You would use the select statement to populate the three internal tables with data
from the respective database tables.

Option 1 is incorrect. You use the insert statement to modify an internal table by
adding a new row at a specified location. You can't use this statement to fetch data
from the respective database tables into the three internal tables.

Option 2 is incorrect. You use the append statement to add a new row to the end of
an internal table. You can't use this statement to populate the three internal tables
with data from the respective database tables.

Option 3 is incorrect. You use the read table statement to read data from one row
of an internal table at a time. But you can't use this statement to read data from the
respective database tables and populate the internal tables with that data.

Option 4 is correct. You use the select statement to fetch data from a database
table into an internal table. Using this statement, you can choose to fetch all or
selected fields from the respective database tables into the three internal tables.

Step 4 of 4

After populating the internal tables, you need to create the basic and secondary lists.
In the basic list, the billing amount for a billing document should reflect the total
amount of all item lines within the billing document. For this, you need to read the
rows of the itab_billing table, add the amount of all rows with the same billing
document number, and then update the amount field of the corresponding row in the
itab_billing_bu table.

What actions should you peform to do this?

Options:

1. Read the itab_billing table using the loop at...endloop statement and update the
amount field of the itab_billing_bu table using the modify statement

78
2. Read the itab_billing table using the select...endselect statement and update the
amount field of the itab_billing_bu table using the append statement
3. Read the itab_billing table using the select statement and update the amount field of the
itab_billing_bu table using the append statement

Result

You use the loop at...endloop statement to read the itab_billing table and the
modify statement to update the amount field of the itab_billing_bu table.

Task 2: Using events and messages

After you update the itab_billing_bu table, you write ABAP statements to create the basic
and secondary lists.

Step 1 of 2

You want to modularize the report program and enable it to respond to the required
events. You want to include the ABAP statements required to fetch data from the
database tables "Billing_BU," "Billing," and "BU" to create the lists in an appropriate
event block. In addition, you decide to include the ABAP statements creating the two
secondary lists in the event block that is executed when a user double-clicks the
basic list.

Which event blocks would you use for this?

MISSING CODE .
"creating basic list
select document_number BU_code into itab_billing_bu from
Billing_BU .

MISSING CODE
"creating secondary lists

select * from into itab_billing from Billing .

select * from into itab_bu from BU .

Options:

1. Initialization
2. start-of-selection
3. at pf12
4. at line-selection

Result

79
You would use the start-of-selection event block to write the ABAP
statements to fetch data from the three database tables into the respective internal
tables and the at line-selection event block to write the ABAP statements to
create the two secondary lists.

Option 1 is incorrect. The initialization event block is triggered by the ABAP


runtime immediately after a report program is loaded. You use this event block to
initialize the variables of your report program. You shouldn't write statements in this
event block either to fetch data from the three database tables into respective
internal tables or to create the two secondary lists.

Option 2 is correct. The start-of-selection event block is executed


immediately after the top-of-page event. After you use the top-of-page event
block to create the report header, you can use the start-of-selection event
block to fetch data from the three database tables into the respective internal tables.
However, because the two secondary lists should be created only after a user
double-clicks a row in the basic list, you can't use this event block to write ABAP
statements to create the two secondary lists.

Option 3 is incorrect. The at pf12 event block is executed when a user selects a
line in the basic list and presses F12. Therefore, you can't use this event block either
to fetch data from the three database tables into the respective internal tables or to
create the two secondary lists.

Option 4 is correct. The at line-selection event block is executed when a user


double-clicks a line in the basic list. Therefore, you can use this event block to write
ABAP statements to create the two secondary lists, but you can't use this event
block to write the select statements to fetch data from the three database tables
into the respective internal tables.

Step 2 of 2

The finance manager wants the report to inform users that a secondary list will be
displayed when the user double-clicks a row in the basic list.

Which ABAP statement would you use to inform users in this case?

at line-selection .

MISSING CODE 'A secondary list will be displayed.' type 'I'


.

Result

You would use the message statement to inform users in this case.

Task 3: Transporting data between lists


80
To create the two secondary lists based on the line and the field a user double-clicks in the
basic list, you need to retrieve the name and value of the field at runtime.

Step 1 of 1

To create the two secondary lists, first you need to retrieve the name and value of
the field on which the user double-clicks, and then based on the name of the field,
you need to create the appropriate secondary list with information corresponding to
the value of the field. In addition, when a user double-clicks the total amount field of
the basic list, the report should notify the users about the same.

Which ABAP statement would you use to access the name and value of the field of
the basic list on which the user double-clicks during report execution?

data: f(10) type c , " variable to store the name of the


" basic list field on which a user double-clicks
v(10) type c . " variable to store value of the basic list
field
" on which a user double-clicks

at line-selection .

message 'A secondary list will be displayed.' type 'I' .

MISSING CODE Field f Value v .

" creating secondary lists


if f = 'billing_amount' .
message 'Can't select this field.' type 'E' .
elseif f = 'document_number' .
loop at itab_billing .
if itab_billing-document_number = v .
" code to create the secondary list displaying billing
" document details comes here
endif .
else .
if itab_billing-BU_code = v .
" code to create secondary list displaying
" business unit details comes here
endif .
endif .

Result

You use the get cursor statement to access the name and value of the field of
the basic list on which the user double-clicked during report execution.

Table of Contents
81
| Top of page |

| Learning objective |

| Exercise overview |

| Task 1: Creating internal tables |

| Task 2: Using events and messages |

| Task 3: Transporting data between lists |

Copyright 2006 SkillSoft. All rights reserved.


SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

82
ABAP Classes
Learning objective

After completing this topic, you should be able to recognize how to create and instantiate a
class in ABAP.

1. Features of object-oriented programming

An ABAP program consists of various program blocks, such as data declaration, start-of-
selection, and end-of-selection. The program blocks are executed in sequence.

This is known as the procedural programming model, which is the classical approach to
programming.

The procedural programming model uses functions and subroutines that can be called in
the program. The data and the functions are not linked.

Object-oriented programming is based on the concept of classes. A class is a collection of


similar objects with properties similar to that of the class. An object is an instance of a class.

For example, if there are two departments Finance and HR in a company, "Finance"
and "HR" are the objects of the class "Department". They have properties similar to that of
"Department".

Object-oriented programming uses methods that can be called in a program. The data and
methods are linked and belong to the class in which they are defined.

Object-oriented programming offers various benefits over procedural programming. The


benefits are

it enables you to implement business models


it enables you to reuse the code when creating a new program
multiple programmers can develop specific sections of a program
programs are easier to edit because changes in a specific section don't affect the entire
program
programs are easy to understand because they contain separate program blocks
the size of program code is less

A class contains three components. These are

attributes
methods
events
83
attributes
Attributes are variables that you define in a class. Attributes specify the data type of the
objects that a class supports.

For example, you can define a variable "name" with the character data type and a
variable "emp_code" with the numeric data type in a class. Therefore, the class supports
objects of the character and numeric data types.
methods
Methods are the functions that a class supports. Methods receive values from and pass
values to a program.

For example, you can define a method "display_data" that displays the name of an
employee based on employee code.
events
Events are functions that are triggered based on the result of a condition. When an event
is triggered, special program blocks, called event handlers are executed.

Question

Identify the features of object-oriented programming.

Options:

1. Code can be reused


2. Data and methods are linked
3. Programs are lengthy
4. Programs are difficult to understand

Answer

Object-oriented programming enables you to reuse the code of a program in another


program, and the data and methods in an object-oriented program are linked.

Option 1 is correct. Object-oriented programming enables you to reuse the code of a


program in other programs.

Option 2 is correct. The data and methods in object-oriented programs are linked
and belong to the class in which you define them.

Option 3 is incorrect. Object-oriented programs are small in length.

Option 4 is incorrect. Object-oriented programs are easy to understand because


they contain separate program blocks.

2. Defining a class and its attributes

84
Classes form the basis of object-oriented programming. There are two types of classes:

local
global

Local classes can only be accessed by programs on the local application server. You define
local classes by using the ABAP Editor.

Global classes can be accessed by the programs on all the application servers. You define
global classes by using a tool called Class Builder.

A class consists of

a definition part
an implementation part

You define various components attributes, events, and methods in the definition part.

The implementation part contains the code for the events and methods defined in the
definition part.

The three sections in the definition part of a class are

public
protected
private
public
The public section contains components that all other classes can access.

Suppose there are three classes "A", "B", and "C". if you define a variable
"company_code" in the public section of the class "A", the classes "B" and "C" can also
access the variable "company_code".
protected
The protected section contains components that a superclass and its subclasses can
access.

For example, you have defined a superclass "department" and its subclass "finance". If
you define a variable "employee" in the protected section of "department", both
"department" and "finance" can access "employee". However, any other classes can not
access the variable "employee".
private
The private section contains components that only the superclass can access. The
subclasses can't access the private components.

For example, you have defined a superclass "department" and its subclass "finance".

85
Now, if you define a variable "employee" in the private section of "department", then only
"department" can access "employee".

When defining a class, you specify the keyword class along with the class name. You also
specify the keywords definition or implementation to indicate the part of the class
you are defining.

*-------------------------------------------------------*
* class name definition *
*-------------------------------------------------------*
class name definition.
public section.

protected section.

private section.
endclass.

*-------------------------------------------------------*
* class name implementation *
*-------------------------------------------------------*
class name implementation.

endclass.

Suppose you need to define a class "employee". You want only the class "employee" and
its subclasses to be able to access the variable "first_name" and the method
"display_attributes". You need to type the appropriate section name.

*-------------------------------------------------------*
* class employee definition *
*-------------------------------------------------------*
class employee definition.
MISSING CODE.
data first_name(10) type c.
data last_name(10) type c.
" code to define the method comes here
endclass.

*-------------------------------------------------------*
* class employee implementation *
*-------------------------------------------------------*
class employee definition.
" code to implement the method comes here
endclass.

You type protected section to do this.

You have defined the protected section of the class "employee".

86
*-------------------------------------------------------*
* class employee definition *
*-------------------------------------------------------*
class employee definition.
protected section.
data first_name(10) type c.
data last_name(10) type c.
" code to define the method comes here
endclass.

*-------------------------------------------------------*
* class employee implementation *
*-------------------------------------------------------*
class employee definition.
" code to implement the method comes here
endclass.

Question

You want to define a class "airplane" and implement it. In addition, you want to
define a character variable "flight_name" that only "airplane" and its subclasses can
access. Therefore, you need to define the variable in the correct section of the class.

Which code snippets enable you to define the appropriate section of the class, and
define the required variable in that section?

Options:

1. private section to define the section, and flight_name to define the variable.
2. protected section to define the section, and data flight_name to define the
variable.
3. public section to define the section, and flight_name data to define the variable.

Answer

To define the section of the class, you use the code protected section and to
define the variable, you use the code data flight_name.

Attributes are the components of a class. It is important to define the attributes of a class
because the attributes store the data in an ABAP program. You then manipulate the data
and perform logical operations to produce the desired result.

You can categorize attributes as public, protected, or private based on the section of the
class where you define the attributes.

In this code, the variable "counter" is a protected attribute of the class "employee".
Therefore, the class "employee" and its subclasses can access the attributes.

Similarly, you can define the public and private attributes of a class.
87
class employee definition.
protected section.
data counter type i.
private section.
endclass.

Question

Suppose you have defined a class "products". You want to define a numeric variable
"product_no" that only the class "products" and its subclasses can access.

Which code snippets enable you to define the appropriate section of the class and
define the variable?

Options:

1. private section to define the section and


data product_no to define the variable.
2. protected section to define the section and
data product_no to define the variable.
3. public section to define the section and
variable product_no to define the variable.

Answer

To define the section, you use the code protected section, and to define the
variable, you use the code data product_no.

3. Working with methods

Methods are components of a class. Methods receive data from a program, process the
data, and return the output to the program.

If you want to use methods in an ABAP program, you need to first define them in the
definition part of a class. You then write the complete code of the method in the
implementation part of the class.

You use the methods statement to define a method in a class. You need to specify the
method name in the methods statement.

methods : method name.

Suppose you define a method "display_attributes" in the class "employees". Only the
objects of the class "employee" can access this private method.

class employees definition.


private section.

88
methods : display_attributes.
endclass.

When you need to define a method that receives data from the program, you use the
keyword importing. You specify the name of the data object in the methods statement.

methods method name importing variable type data type.

Suppose you want to define a method "get_name" that receives data from the program and
stores it in the variable "name". The variable is 15 characters long.

methods get_name importing name(15) type c.

When you want to return the output of the method to the program, you use the keyword
exporting to define the method.

methods method name exporting variable type data type.

You use this code if you want to define a method "display_name" that passes the value
stored in the variable "name" to the calling program.

methods display_name exporting name(15) type c.

Suppose you want to define a method "display_info" that uses a variable "code" to pass an
output to the calling program.

class employee definition.


private section.
methods display_info MISSING CODE code type c.
endclass.

You type exporting to define the method.

You have defined a private method "display_info" that only the class "employee" can
access.

class employee definition.


private section.
methods display_info exporting code type c.
endclass.

After you have defined a method in the definition section of a class, you need to write the
code for implementing the method in the implementation section of the class.

You enclose the ABAP statements implementing the method within the method and
endmethod statements.

89
method method name.
ABAP statements.
endmethod.

For example, you can implement the method "display_attributes" that passes the value
stored in "name" to the calling program.

method employee.
write : / 'Name of the employee is:', name.
endmethod.

After you have defined and implemented a method in a class, you can call the method in
the ABAP program for execution. You use an object to call a method in the program.

When calling a method, you specify the calling object name, the called method name, the
variable name, and the value. However, the parameters variable name and value are
optional.

object name->method name( variable name = value ).

For example, you can call the method "display_attributes" by using the object "emp_name".
However, you do not specify the variable name and the value because the method does not
receive data from the program.

emp_name->display_attributes( ).

Suppose you have defined and implemented a method "get_attributes" in a class "airplane".
The method receives the value of "flight_num" from the program. You have defined an
object reference "flight_list" that you use to call the method.

class airplane definition.


private section.
class-methods get_attributes importing flight_num type c.
data name type string.
endclass.
class airplane implementation.
method get_attributes.
name = flight_num.
endmethod.
endclass.

start-of-selection.
data flight_list type ref to airplane.
create object flight_list.
MISSING CODE.

You type flight_list->get_attributes( flight_num(5) = 'JJ25' ) to call the


method.

90
You have called the static method "get_attributes".

class airplane definition.


private section.
methods get_attributes importing flight_num type c.
data name type string.
endclass.
class airplane implementation.
method get_attributes.
name = flight_num.
endmethod.
endclass.

start-of-selection.
data flight_list type ref to airplane.
create object flight_list.
flight_list->get_attributes( flight_num(5) = 'JJ25' ).

Question

You have defined a class "vehicle" that contains the method "estimate_fuel" to
display the amount of fuel required for a vehicle to travel a specified distance. You
want all the classes to be able to access the method "estimate_fuel" by using
objects.

Type the code to define the appropriate method.

class vehicle definition.


public section.
MISSING CODE : estimate_fuel type i.
endclass.

Answer

You use the methods statement to define a method that a program can call using
objects.

4. Working with events

Events are type of methods that are triggered based on a condition you specify.

When triggered, an event triggers the execution of special program blocks known as event
handlers. The event handlers may be present in another program.

You define an event by using the events statement.

events event name.

91
Events only contain output parameters. If you want to specify output parameters for an
event, you use the keyword exporting along with the parameters.

events event name exporting variable name type data type.

Suppose you want to define an event "increment" that passes the value of "counter" to its
event handler.

events increment exporting counter(3) type n.

You need to define an event handler to specify the program code that needs to be executed
when an event is triggered.

You use the set handler statement to define an event handler.

set handler object name->method name for variable.

You can use the object "emp_name" to call the method "display_name" when the event
triggers the event handler. The variable "name" is the input parameter for the method.

set handler emp_name->display_name for name.

When you have defined an event in a class, you can trigger the event in the program by
using the raise event statement.

raise event event name.

You can trigger an event based on the result of a condition. Suppose you want to trigger the
event "display_name" if the value of "emp_code" is "12455".

if emp_code = 12455.
raise event display_name.
else.
continue.
endif.

Suppose you want to check the value of "counter" and trigger an event "display_value"
when the value is "10". When triggered, the event calls a method "display" to display the
message "The value of counter equals 10". You need to define an event handler for the
event.

class numbers definition.


private section.
events display_value exporting value type n.
methods display.
endclass.
class numbers implementation.
* code to implement the method comes here*
endclass.

92
start-of-selection.
data counter type n value 0.
counter = counter + 1.
if counter = 12455.
raise event display_value.
else.
continue.
endif.
MISSING CODE emp_name->display for counter.

You type set handler to define the event handler.

You have defined the event handler for the event "display_value".

class numbers definition.


private section.
events display_value exporting value type n.
methods display.
endclass.
class numbers implementation.
* code to implement the method comes here*
endclass.

start-of-selection.
data counter type n value 0.
counter = counter + 1.
if counter = 12455.
raise event display_value.
else.
continue.
endif.
set handler emp_name->display for counter.

Question

You want to define a public event "display_info" in the class "products". You want to
trigger the event if the value of product code is "pp0023". When the event handler is
triggered, you want to call the method "define" to display the product code.

Which code snippets enables you to define the event, trigger the event, and handle
the event?

Options:

1. event display_info to define the event, raise events display_info to trigger the
event, and set handler to handle the event.
2. events display_info to define the event, raise event display_info to trigger the
event, and set handler to handle the event.

93
3. event display_info to define the event, raise events display_info to trigger the
event, and set handlers to handle the event.

Answer

To define the event, you use the code events display_info, to trigger the
event, you use the code raise event display_info, and to handle the event,
you use the code set handler.

5. Working with classes

When you have defined and implemented a class, you can call the methods of the class in
an ABAP program. You need to instantiate a class before you call it in a program.
Instantiating a class involves defining an object reference to call the class.

An object reference is a data object that passes values to and receives values from a class.
An object reference is known as a pointer.

Before you call the method of a class, you need to define a variable of the class.

data variable name type ref to class name.

Suppose you have defined a method "display_info" in the class "airplane". You want to
define a variable "flight_num" of the class "airplane".

data flight_num type ref to airplane.

After you have defined a variable of a class, you use the create statement to create an
object. You can then call a method of the class by using the object.

create object object name.


object name->method name( ).

You can create an object "flight_num" to call the method "display_details" of the class
"airplane".

start-of-selection.
data flight_num type ref to airplane.
create object flight_num.
flight_num->display_details( ).

Suppose you have defined a class "raw_material" that contains a method "display_stock".
You want to call the method in the program. You need to create an object
"material_number" to instantiate the class.

class raw_material definition.


protected section.
methods display_stock. exporting stock type n.

94
endclass.

start-of-selection.
data material_number type ref to raw_material.
MISSING CODE material_number.
material_number->display_stock( ).

You type create object to instantiate the class.

You have instantiated the class "raw_material" by creating the object "material_number".
You can use the object to call the methods of the class "raw_material".

class raw_material definition.


protected section.
methods display_stock. exporting stock type n.
endclass.

start-of-selection.
data material_number type ref to raw_material.
create object material_number.
material_number->display_stock( ).

Question

Suppose you have defined a method "display_name" in the class "employee". You
want to call the method in the main program by using an object "r_dis" of the class
"employee".

Which code snippets enable you to define the variable, create the object, and call
the method?

Options:

1. data r_dis type employee to define the variable, data object r_dis to create the
object, and r_dis -> display_name( ) to call the method.
2. data r_dis type employee to define the variable, data object r_dis to create the
object, and r_dis->display_name( ) to call the method.
3. data r_dis type ref to employee to define the variable, create object r_dis
to create the object, and r_dis->display_name( ) to call the method.

Answer

To define the variable, you use the code data r_dis type ref to employee,
to create the object, you use the code create object r_dis, and to call the
method, you use the code r_dis->display_name( ).

Summary

95
ABAP supports two programming models: procedural and object-oriented. The object-
oriented programming is based on the concept of classes. The data and methods in an
object-oriented program are linked and belong to the class where you define them.

You define the components attributes, events, and methods of a class in various
sections public, protected, and private.

Methods receive data from a program, process the data, and return the output to the
program.

Events are triggered based on a condition. When an event is triggered, special program
blocks called event handlers are executed.

When you have defined and implemented a class, you can call the methods of the class by
instantiating the class.

Table of Contents

| Top of page |

| Learning objective |

| 1. Features of object-oriented programming |

| 2. Defining a class and its attributes |

| 3. Working with methods |

| 4. Working with events |

| 5. Working with classes |

| Summary |

Copyright 2006 SkillSoft. All rights reserved.


SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

96
Properties of ABAP Objects
Learning objective

After completing this topic, you should be able to recognize how to implement inheritance,
encapsulation, and polymorphism using classes in given scenarios.

1. Properties of ABAP objects

ABAP objects offer various features such as inheritance, encapsulation, and polymorphism.
These features enable you to implement complex scenarios without writing long code
snippets. In addition, these features enable you to implement data security.

Inheritance is the property of classes, where subclasses are derived from a superclass. The
subclasses inherit the properties and the components methods, events, and attributes
of the superclass.

For example, the subclasses "boeing" and "airbus" inherit the properties of the class
"airplane".

Inheritance eliminates the need to redefine the components of a class if the subclasses
want to use the components of the superclass. A subclass can access the public and
protected components of the superclass. In addition to the components of the superclass, a
subclass can create its own components.

Encapsulation is the process of defining components in a class to ensure that the data of
the objects is not accessible from outside the class. Encapsulation enables you to
implement data security by hiding the implementation details of the methods of a class.

For example, if you define a method "fuel_efficiency" in a class "vehicle", the subclasses
"car" and "truck" can access the method. However, the implementation details of calculating
the efficiency are hidden from the subclasses.

You define attributes, methods, and events in the public, protected, or private sections of a
class based on the type of access you want to allow. For example, if you define a private
method in a class, only the class can access the method.

Polymorphism is the property that enables you to implement one method in multiple ways. It
enables one method to produce different types of output when multiple subclasses call it.

For example, you define a method "total_fare" to calculate airline fare based on travel
distance. Two classes, "business" and "economy", use the same method to calculate the
fare. However, the implementation of the method is different in both classes.

Question

Match each property of classes to its description.

97
Options:

1. Encapsulation
2. Inheritance
3. Polymorphism

Targets:

A. Enables a class to hide the implementation details of its methods


B. Enables a method to produce different types of output when multiple subclasses call it
C. Enables you to derive subclasses from a superclass

Answer

Encapsulation enables a class to hide the implementation details of its methods,


polymorphism enables a method to produce different types of output when multiple
subclasses call it, and inheritance enables you to derive subclasses from a
superclass.

When you implement encapsulation, the user only needs to call a method in a
program to perform the desired task. The details of how the method performs the
task are hidden from the user.

Inheritance enables subclasses to access the components of the superclass. The


subclasses inherit the properties of the superclass.

Polymorphism enables multiple classes to access one method to produce different


types of output. To implement polymorphism, you redefine the method in each class.

2. Implementing inheritance

Inheritance enables subclasses to inherit the components of the superclass. It eliminates


the need to redefine methods each time a subclass needs to use the methods.

To define a subclass, you use the keyword inheriting in the class statement.

class subclass definition inheriting from superclass.


ABAP statements.
endclass.

Suppose you have defined a method "total_stock" in the class protected section of the class
"raw_material". In addition, you have derived the subclass "lcd_screen" from the class
"raw_material".

class raw_material definition.


protected section.
data stock type n.
methods : total_stock redefinition.

98
endclass.
class raw_material implementation.
*code to implement the method comes here*
endclass.

class lcd_screen definition inheriting from raw_material.


endclass.

If you want the subclass to access the method of the superclass, you need to create an
object of the subclass in the start-of-selection section of the main program.

start-of-selection.
data r_stock type ref to lcd_screen.
create object r_stock.

Therefore, inheritance enables the object "r_stock" of the subclass to access the method
"total_stock" of the superclass.

r_stock->total_stock( ).

Suppose you have defined a class "vehicle" that contains "fuel", a numeric variable. Now
you want to define "car", a class that should be able to access the variable "fuel". So you
define "car'" as a subclass of the "vehicle" superclass.

class vehicle definition.


protected section.
data fuel type n.
endclass.

class car MISSING CODE vehicle.


endclass.

To do this, you type definition inheriting from.

You have defined the subclass "car", which can access the variable "fuel" of the class
"vehicle".

class vehicle definition.


protected section.
data fuel type n.
endclass.

class car definition inheriting from vehicle.


endclass.

Question

Suppose you have defined a variable "fare" in the class "air_fare". You want to
define a subclass "economy" that can access the variable "fare".

99
Which code enables you to define the subclass?

class air_fare definition.


protected section.
fare type i.
endclass.
MISSING CODE
endclass.

Options:

1. class air_fare definition inheriting from economy.


2. class definition air_fare inheriting from economy.
3. class definition economy inheriting from air_fare.
4. class economy definition inheriting from air_fare.

Answer

The code class economy definition inheriting from air_fare.


enables you to define the subclass.

Option 1 is incorrect. You specify the name of the subclass before specifying the
name of the superclass.

Option 2 is incorrect. You specify the name of the subclass between the keywords
class and definition. The name of the superclass should be specified after the
keyword from.

Option 3 is incorrect. You specify the name of the subclass between the keywords
class and definition.

Option 4 is correct. You specify the name of the subclass between the keywords
class and definition, and you specify the name of the superclass after the
keyword from.

3. Implementing encapsulation

Encapsulation is the process of defining the components methods, events, and attributes
of a class so that only select classes can access the components.

Suppose you want to encapsulate the variable "name" and the method "display_info" in the
class "employee". You want to ensure that only the class "employee" should be able to
access these components. Therefore, you define the objects in the private section of the
class.

class employee definition.


private section.
100
data name(15) type c.
methods display_info.
endclass.

In addition to defining the components in a class, you can implement encapsulation by


using interfaces, which are special classes that do not contain the implementation part.
After you have defined methods, events, and attributes in an interface, you can implement
them in other classes.

All the classes in a program can access the components defined in an interface. However,
this is not the case with the components defined in a class. Therefore, interfaces enable
you to create more flexible programs.

You use the interface and endinterface statements to define an interface.

interface interface name.


ABAP statements to define components.
endinterface.

When you want to access the components of an interface in a class, you need to define the
interface in the class by using the interfaces statement.

interfaces interface name.

You can encapsulate "name" as a protected variable and "display_name" as a protected


method in an interface "employee".

interface employee.
data name(15) type c.
methods display_name.
endinterface.

After you have encapsulated the components in an interface, you can call them in various
classes of the program. To access the components, you need to define the interface in the
class.

class managers definition.


protected section.
interfaces employee.
endclass.

Then you can implement the method "display_name" of the interface "employee" in the
class "managers". After implementing the method, you can call it in the main program by
instantiating the class.

class managers implementation.


method display_name.
* code of the method comes here *

101
endmethod.
endclass.

Question

Suppose you want to implement encapsulation in an ABAP program by using an


interface "int". So you want to define a method "method1" and a variable "variable1"
that all the classes in the program can access.

Type the code that enables you to define the interface.

MISSING CODE.
data variable1.
methods method1.
endinterface.

Answer

You type interface int to define the desired interface.

4. Implementing polymorphism

Polymorphism is a property that enables one method to produce different types of output
when different classes call it. Polymorphism enables you to reuse the method of a class in
its subclasses.

For example, the subclasses "car" and "truck" of the class "vehicle" access the method
"fuel_needed" to calculate the quantity of fuel that a vehicle requires for traveling a specific
distance. Polymorphism enables the method to return different outputs to each class, based
on the fuel efficiency of the vehicle type.

You redefine a method in a subclass by using the redefinition keyword in the methods
statement.

methods method name redefinition.

This code redefines the method "display_attributes" in the subclass "products".

class products definition inheriting from company.


methods display_attributes redefinition.

Suppose you have defined a method "fuel_needed" in the class "vehicle". The method
calculates the quantity of fuel that a vehicle requires for traveling a specific distance.

Here, you have assumed the fuel efficiency of the vehicle as ten units of fuel per unit of
distance traveled.

102
class vehicle definition.
public section.
methods : fuel_needed importing im_distance type i.
data distance type i.
fuel type i.
endclass.

class vehicle implementation.


method fuel_needed.
distance = im_distance.
fuel = distance / 10.
write : total fuel needed = ' , fuel.
endmethod.
endclass.

You want to define the subclasses "car" and "truck" that use the method "fuel_needed" to
display the quantity of fuel that a car and a truck need, respectively. You have assumed the
fuel efficiency of a car as 15 units and that of a truck as 5 units of fuel per unit of distance
traveled.

You want the method "fuel_needed" to produce different results when "car" and "truck" call
it. Therefore, you need to redefine the method in both the subclasses. First you define the
subclass "car".

class car definition inheriting from vehicle.


public section.
methods : fuel_needed redefinition.
endclass.

class car implementation.


method fuel_needed.
distance = im_distance.
fuel = distance / 15.
write : / 'total fuel needed for a car is:' , fuel.
endmethod.
endclass.

After you have defined the subclass "car", you define the subclass "truck" that redefines the
method "fuel_needed" based on the fuel efficiency of a truck.

class truck definition inheriting from vehicle.


public section.
methods : fuel_needed redefinition.
endclass.

class truck implementation.


method fuel_needed.
distance = im_distance.
fuel = distance / 5.
write : / 'total fuel needed for a truck is:' , fuel.
103
endmethod.
endclass.

You now want to call the method "fuel_needed" by using the classes "car" and "truck".
Therefore, you first define the variables of the subclasses and then create objects for both
the classes in the start-of-selection section.

data r_car type ref to car.


data r_truck type ref to truck.
data fuel type i.
parameter r_dis type i.

start-of-selection.
create object r_car.
create object r_truck.

You call the method by using the objects you have created. The method produces a
different result for each subclass.

Therefore, polymorphism enables you to use one method multiple times to produce
different results.

data r_car type ref to car.


data r_truck type ref to truck.
data fuel type i.
parameter r_dis type i.

start-of-selection.
create object r_car.
create object r_truck.
r_car->fuel_needed( im_distance = r_dis ).
r_truck->fuel_needed( im_distance = r_dis ).

Question

You have defined the methods "effort" and "display_info" in the class "vehicle". In
addition, you have defined the subclasses "car" and "bike". When called, "effort"
displays the number of hours required to manufacture a specified number of
vehicles. The average number of hours required for manufacturing are different for a
car and a bike. Consequently, you want different values of time required to be
displayed for each subclass.

Type the code that enables the subclass "car" to implement polymorphism.

class car definition inheriting from machine.


protected section.
methods : MISSING CODE.
endclass.

104
Answer

You type effort redefinition to implement polymorphism by redefining


"estimate" in the subclass "car".

Summary

ABAP objects offer various features such as encapsulation, inheritance, and polymorphism
that enable you to implement complex scenarios without greatly increasing the length of
ABAP programs.

Inheritance is the property that enables subclasses to use the objects of a class. This
eliminates the need to redefine objects in the subclasses.

Encapsulation is the property where only specific classes can access the objects of a
particular class. Encapsulation enables you to implement data security because the
implementation details of how a function performs a task are hidden from the user.

Polymorphism is a property that enables a method to produce specific types of output


based on the class that calls the method. This is done by redefining a method in the
subclasses where you want to call the method.

Table of Contents

| Top of page |

| Learning objective |

| 1. Properties of ABAP objects |

| 2. Implementing inheritance |

| 3. Implementing encapsulation |

| 4. Implementing polymorphism |

| Summary |

Copyright 2006 SkillSoft. All rights reserved.


SkillSoft and the SkillSoft logo are trademarks or registered trademarks
of SkillSoft in the United States and certain other countries.
All other logos or trademarks are the property of their respective owners.

105
Using Classes in ABAP
Learning objective

After completing this topic, you should be able to recognize how to work with ABAP classes
in a given scenario.

Exercise overview

In this exercise, you're required to create an ABAP program that displays the flight fares
based on a given distance.

This involves the following tasks:

defining a class
implementing object properties
accessing a class

Suppose you need to create an ABAP program called "z_Airplane_Fare" that displays the
fares for the business and economy classes based on the distance a user specifies.

report z_Airplane_Fare.

Task 1: Defining a class

You begin by defining a class "air_fare" that contains public methods and attributes.

report z_Airplane_Fare.
class air_fare definition.
* code for the class comes here *
endclass.

Step 1 of 2

Suppose you have defined the classes "car", "bike", and "truck". You want to define
a method "estimate" in the class "bike" to calculate the time required to manufacture
a vehicle. You want to enable the classes "car" and "truck" to access "estimate".

Which section in the class "bike" do you use to define the method?

Options:

1. public
2. private
3. protected

106
Result

You define the method in the public section of the class "bike" to enable "car" and
"truck" to access it.

Option 1 is correct. All the classes in a program can access the methods, events,
and attributes defined in the public section of a class.

Option 2 is incorrect. When you define methods, events, and attributes in the private
section of a class, only the class can access them.

Option 3 is incorrect. Only the class and its subclasses can access the methods,
events, and attributes you define in the protected section of a class.

Step 2 of 2

You want to define a method "display_fare". The method computes the fare based
on the value of the total travel distance it receives from the main program.

Type the code that enables you to define the method.

class air_fare definition.


public section.
MISSING CODE display_fare importing im_distance type i.
data distance type i.
fare type i.
endclass.
class air_fare implementation.
method display_fare.
distance = im_distance.
fare = distance * 10.
endmethod.
endclass.

Result

You use the methods keyword to define a method.

Task 2: Implementing object properties

You have defined the class "air_fare" and want to define its subclasses that access its
components.

class air_fare definition.


public section.
methods : display_fare importing im_distance type i.
data distance type i.

107
fare type i.
endclass.
class air_fare implementation.
method display_fare.
distance = im_distance.
fare = distance * 10.
endmethod.
endclass.

Step 1 of 2

You want to define the subclasses "business" and "economy" that access the
components of the superclass "air_fare".

Which code snippets enable you to define the subclasses "business" and
"economy"?

Options:

1. class business definition inheriting from air_fare to define "business",


and class economy definition inheriting from air_fare to define
"economy"
2. class definition business inheriting from air_fare to define "business",
and class definition economy inheriting from air_fare to define
"economy"

Result

To define the subclass "business", you use the code class business
definition inheriting from air_fare, and to define the subclass
"economy", you use the code class economy definition inheriting from
air_fare.

Step 2 of 2

After you have defined the subclasses of "air_fare", you implement the subclasses.
You want to reuse the method "display_fare" to display different fares for the same
distance when the subclasses "business" and "economy" call the method in the
program.

Type the code that enables you to reuse the method "display_fare" in the subclass
"business".

class business definition inheriting from air_fare.


public section.
methods MISSING CODE.
endclass.
class business implementation.

108
method display_fare.
distance = im_distance.
fare = distance * 50.
write : / 'The fare for the business class is:' , fare.
endmethod.
endclass.

Result

You type display_fare redefinition to redefine the method in the subclass


"business".

Task 3: Accessing a class

You have defined the class "air_fare" that contains the method "display_fare". In addition,
you have redefined the method "display_fare" in the subclasses "business" and "economy".
Therefore, you have implemented encapsulation, inheritance, and polymorphism in the
program.

class business definition inheriting from air_fare.


public section.
methods : display_fare redefinition.
endclass.
class business implementation.
* code to implement the class comes here *
endclass.
class economy definition inheriting from air_fare.
public section.
methods : display_fare redefinition.
endclass.
class economy implementation.
method display_fare .
distance = im_distance.
fare = distance * 30.
write : / 'The fare for the economy class is:' , fare.
endmethod.
endclass.

Step 1 of 2

You want to call the method "display_fare" in the main program to display the fares
based on the distance that the user specifies. You need to define a variable
"r_business" of the subclass "business", and create an object reference to call the
method.

Which code snippets enable you to define the variable, and create the desired
object?

Options:
109
1. create ref to business to define the variable, and type object r_business to
create the object
2. data ref to business to define the variable, and create ref r_business to create
the object
3. type ref to business to define the variable, and create object r_business to
create the object
4. type ref to display_fare to define the variable, and create object r_business
to create the object

Result

To define the variable, you use the code type ref to business, and to create
the object, you use the code create object r_business.

Step 2 of 2

You have created the object references for the subclasses "business" and
"economy". You want to call the method "display_fare" by using the object
references you created.

Which code snippets enable you to call the method from the subclasses "business"
and "economy"?

Options:

1. r_business -> display_fare to call from "business", and r_economy ->


display_fare to call from "economy"
2. r_business->display_fare to call from "business", and r_economy->display_fare
to call from "economy"
3. r_economy -> display_fare to call from "business", and r_business ->
display_fare to call from "economy"
4. r_economy->display_fare to call from "business", and r_business->display_fare
to call from "economy"

Result

To call the method from "business", you use the code r_business-
>display_fare, and to call the method from "economy", you use the code
r_economy->display_fare.

Table of Contents

| Top of page |

| Learning objective |

| Exercise overview |

110
| Task 1: Defining a class |

| Task 2: Implementing object properties |

| Task 3: Accessing a class |

111

You might also like