You are on page 1of 97

1/16/2011

1
Spring 2011 Enterprise Programming
ABAP FUNDAMENTALS
What is ABAP?
Originally: Allgemeiner Berichts-Aufbereitungs-Prozessor (Generic
Report Preparation/Generation Processor)
Now: Advanced Business Application Programming
Created by SAP initially for report creation. Later evolved into full
language. Made public for program customization and
enhancement by companies.
Notable for its database abstraction (logical databases) and ease of
database interaction. Embedded SQL statements in code (Open
SQL). Platform independent.
Extended in 1998 to include Object support (ABAP Objects).
Developing using OO model recommended, but legacy procedural
coding still supported.

1/16/2011
2
Learning ABAPNetWeaver Programming Core
http://www.sap.com/services/education/catalog/netweaver/curriculum.epx?context=%5b%5bABAP_CORE%5d%5d%7c
NetWeaver Training Competencies and Options
https://training.sap.com/courses-and-curricula/netweaver
1/16/2011
3
What is SAP NetWeaver?
Technical foundation for SAP applications
(ERP, CRM, SCM, etc.).
Provides internal connectivity
(integration) between SAP modules
and external connectivity with other
systems.
Eases integration between systems.
Provides framework for development.
Supports development in Java and ABAP


Graphic copyright SAP
Prehistory of NetWeaver
Graphic copyright SAP
1/16/2011
4
SAP Basis Adminsample job ad
3-tiered architecture
Presentation Layer
Database Layer
Application Layer
1/16/2011
5
3-tiered architecture + ABAP
Presentation Layer
Application Layer
Database Layer
ABAP Execution
ABAP Program &
Data Storage
ABAP Programming
& Output
3-tiered architecture + ABAP (General)
Presentation Layer Application Layer Database Layer
Run Transaction/Program
Screen
Screen
ABAP Program
Program Logic
Program Repository
Database Table(s)
Screen
Local Data
Variables
Based on content from Unit 2, BC100, figures 25-35
1/16/2011
6
Developing in an Established Environment
Programming in an environment with many pre-existing named
components.
Name collision can break existing functionality.
Program namespaces beginning A through X are reserved for use by
SAP. Y and Z can be used by customers.
Modification/programming only possible
with a developer key and appropriate
configuration. (SCC4)
Key is client and username dependent.
Keys provided by SAP based on license
agreement. May require additional
payment.

Typical Company SAP Landscape
Typical landscape involves multiple systemsdevelopment (DEV),
testing (QAS), production (PROD), training (TRN).
Developed components move from system to system via transports.
Development done within packages which are tied to transport
requests. Requests are exported/imported for transportation. (e.g.
DEV QAS)
Transport management key system administration task to ensure
dependencies and system integrity maintained.

1/16/2011
7
Typical Company Installation Landscape
Server
SAP ERP
Client xxx
Development
(DEV)
Server
SAP ERP
Client xxx
Test/Quality
Assurance
(QAS)
Server
SAP ERP
Client xxx
Production
(PROD)
Server
SAP ERP
Client xxx
Training
(TRN)
Transport Transport
Programming Process
1. Create new or select existing package.
2. Create new or select existing transport request for package.
3. Begin creating a new program.
4. Enter developer key to authorize development (if not done
previously).
5. Create, debug program. Save.
6. Test. Revise as necessary.
7. Activate program.
8. Transport package.

Items that will not be transported can be assigned to the local
package $TMP.
Within our development landscape, transports are essentially to
dummy systems.
1/16/2011
8
Beginning Programming
ABAP Development Rules:
ABAP programs made up of individual sentences/statements.
Each statement begins with a keyword.
Conventional to type keywords in all uppercase letters and
variables, operators, etc. in all lowercase.
Built in Pretty Printer
Each statement ends with a period.
Statements can be indented as desired.
Statements can extend over multiple lines.
Lines with * in column 1 are comment lines.
Double quotes () are to-end-of-line comments.

Source: SAP BC100, Page 60-61
Various settings can be maintained through Utilities Settings, ABAP
Editor
Launch directly with transaction SE38 or SE80 for ABAP Workbench.
To avoid name collision, in all development done on our system begin
your programs with the prefix Zxx_ where xx is your individual user
number (the last 2 digits of your user name).
If you do your own practice development, enter source code from
various sources, etc. you must comply with this requirement.
If you have access to multiple SAP systems note that this number will
vary among systems.
If you want to create multiple instances of the same program
(practice, redo, etc.), end instances with _01, _02, etc.


ABAP Editor
1/16/2011
9
Programming BasicsBegin Creating New Program
Option 1: Use transaction SE80 to launch ABAP Development
Workbench.
Select Package, and enter the name of the package you wish to
work with.
If package not previously created, will be prompted to create




For class: Zxx_PKGcc (where c is sequential number starting 00)

Programming BasicsPackage and Transport Creation
If no transport request exists, create one. Use search feature if one
exists.
Use your name in the Description. The system will provide a
request number.


Pre-populated to last
request (if exists)
To create new request
1/16/2011
10
Programming BasicsProgram Creation
Right click on package in the Object Name list and select Create
Program.








Program name in ALL CAPS (remember naming rules).
Unless needed (to be discussed later) TOP INCLUDE should be off.

Programming BasicsCreation Sequence
Titlebrief program description.
TypeExecutable program
StatusTest Program








Save/check this dialog and the one that shows the package and the
transport request.

1/16/2011
11
Programming BasicsBegin Creating New Program
Option 2: Use transaction SE38 to launch ABAP Editor.
Specify Program Name. Select Create.








Cannot create a new package with this sequence! But if one already
exists, can use it.
Programming BasicsEnter, Check, Pretty Print, Run
Use editor to enter code.
Many right-click options.
Check operation validates syntax.
Pretty Printer cleans up code layout.
Direct Processing to run.
1/16/2011
12
Additional ABAP Workbench Notes
Appendix
The following slides show screen shots for reference which are
displayed live in lecture.
1/16/2011
13
SE16 showing table TSTCT limited to English
SCC4
1/16/2011
14
SE38 ABAP Editor
SE80 ABAP Workbench
1/16/2011
15
Copyrights
Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries,
xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+,
POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF,
Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of
IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
Oracle is a registered trademark of Oracle Corporation.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, and other SAP products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business
Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects S.A. in the
United States and in other countries. Business Objects is an SAP company.
Other products mentioned in this presentation are trademarks of their respective owners.
Presentation prepared by and copyright of Dr. Tony
Pittarese, East Tennessee State University, Computer and
Information Sciences Dept. (pittares@etsu.edu)
Podcast lecture related to this presentation available via
ETSU iTunesU.
1/23/2011
1
Spring 2011 Enterprise Programming
INTRODUCTION TO ABAP
PROGRAMMING: SYNTAX
FUNDAMENTALS
From the textbookChapter Two
ABAP Workbench
Object Navigator (SE80)
Forward navigation
Packages
Transports
Creating database tables
Field names, data elements, and data types
Data element: object that describes the data type and semantic
meaning of a table field (SAP online glossary)
Domain: defines valid value ranges for fields. Similar fields can be
grouped into a domain. Changing that domain changes all the
fields.
Keyword Documentation

1/23/2011
2
ABAP Variables and Data Types
Data type: description of the kind of data a variable may hold and the
range of acceptable values based on storage allocated.
Technical and (potentially) semantic meaning
Data object: actual variable or constant (of a stated type) that has
been defined.

Complete Data Types
Fixed size, specified format data storage.
Incomplete Data Types
Storage size can vary, so must be set upon variable declaration.
ABAP Standard Data Types
i integer 4 byte whole number +/- 2.1 billion
f float 8 bytes, 15-16 significant digits
c string up to 65k characters
n numeric string up to 65k characters (non-math number)
string string dynamic length up to 2 GB long!
xstring hex string dynamic length byte sequence
x byte sequence up to 65k bytes
d date 8 characters in form YYYYMMDD
t time 6 characters in from HHMMSS
p packed number precise whole or floating number up to 16
bytes
Bold italics indicate incomplete data types (size set on declaration)
1/23/2011
3
Variable Declarations
DATA varname TYPE [type specification]


Use of chained statements (more typical):


Other variations (considered obsolete) exist.
LIKE can be used to declare a variable based on a prior declaration




DATA age TYPE i. "complete data type
DATA siblings TYPE i VALUE 7. "w/ initialization
DATA state TYPE c LENGTH 2 VALUE 'TN'. "incomplete
DATA: age TYPE i,
siblings TYPE i VALUE 7.
When specifying default values for numeric data with decimals, the
value must be placed within single quotes.
DATA state2 LIKE state. "only data type 'copied'
Declaring your own data typesprogram local
TYPES allows declaring local data types that are more specific than
standard types.
TYPES typename TYPE [type specification]
This can be used to give a standard type a more descriptive name for
your application or to more specifically define variable composition.



TYPES cannot have a user-specified default value.
TYPES declarations are local to program. Global type declarations are
possible through use of the ABAP Dictionary, allowing type
management across entire system.



TYPES: userval TYPE i,
usercode TYPE n LENGTH 10,
rate TYPE p LENGTH 3 DECIMALS 2.
1/23/2011
4
Declaring your own data typesglobal
ABAP Dictionary (SE11)
Enter name of type to be created in Data type field.
To avoid name collision for class, start your type names with Znn_
Select Create and choose the class of data type.
Describe the data type and provide its technical specification.
Specify how the field will be labeled in reports.
Activate.
Use in programs.

Can generate a list of all repository elements that use the data type.
Choose Where-Used List icon from SE11 initial screen.
What is the value of defining and using global data types?
Quick Practice
1/23/2011
5
Constants
CONSTANTS allows specification of fixed data objects.
CONSTANTS name TYPE type VALUE value.



A number of system-maintained constants exists. These are all within
structure SYST. Can see list through dictionary, data type SYST.
Reference values by using the identifier SY-COMPONENT. For example,
SY-MANDT will display the current client number.






CONSTANTS a_const TYPE d VALUE '19681214'.
CONSTANTS b_con TYPE p LENGTH 3 DECIMALS 2 VALUE
'37.46'.
Arithmetic and assignment
Valid arithmetic operators: +, -, *, /, ** (exponentiation), DIV (integer
division), MOD.
Parenthesis can be used to set order of precedence.
Operators and parentheses are keywords and must be separated
from other statement elements by at least one space.
Assignment syntax:
MOVE var2 TO var1.
var1 = var2.
varx = 3 + 7 * 2.
If variables of different type, automatic type conversion attempted.
CLEAR varx. Resets varx to default type-related value.

1/23/2011
6
Writing output
WRITE is used for basic output.
WRITE 10 'Output'.
Output is written beginning in column 10.
WRITE (3) 'Output'.
Output is written in field of size 3. * used to show number truncation
(if any). String truncation note noted.
WRITE (*) 'Output'
Output is written in field of sufficient size, without extra spacing.
WRITE 10(3) 'Output'.
Combination of above techniques.
WRITE / 'Output'.
Output written on the next line
WRITE /10(3) 'Output'.
Combination of above techniques.


Parameters
PARAMETERS prompts the user for runtime value at program start.
(Called a selection screen.) Syntax is the same as DATA.



Parameter name must be 8 characters or less.
User is prompted with the parameter name.
DEFAULT can be used to specify a default value in the field.
PARAMETERS age TYPE i.
PARAMETERS: var1 TYPE c LENGTH 8,
var2 TYPE i.
PARAMETERS var1 TYPE c LENGTH 8 DEFAULT 'NONE'.
1/23/2011
7
Quick Practice
Literal text
ABAP is multilingual. Coding in string literals (prompting, etc.) defeats
language independence and should only be done in testing.
The solution for this is text symbols.
Text symbols belong to each program in the text pool for that program.
The various texts are placed in the text pool and assigned a 3-character
alphanumeric code (xxx).
This code is then used by specifying either
TEXT-xxx instead of the literal.
literal(xxx) where literal is the message in the native language.
Access the text pool to define text symbols by either:
From editor select Goto Text Elements Text Symbols
Using the syntax above to reference a text symbol in coding. Then double
click on the text symbol entered.
Goto Translation will translate the text symbols.
1/23/2011
8
Logical Expressions
Logical expressions evaluate to true or false.
In ABAP, logical expression cannot be assigned to variables (no
boolean data type).
Logical expressions are used in conditional code sequences.

Relational Operators
Operator Operation
=, EQ Is equal to
<>, NE Is not equal to
<, LT Is less than
>, GT Is greater than
<=, LE Is less than or equal to
>=, GE Is greater than or equal to
Boolean Operators
Operator Operation
AND Logical and
OR Logical or
NOT Logical not
NOT is placed before an expression
to negate its result.

NOT var_a LT var_b.
Conditional code execution: IF, ELSEIF, ELSE
IF logical_expression.
1 or more statements.
ENDIF.

IF logical_expression.
1 or more statements.
ELSE.
1 or more statements.
ENDIF.

IF logical_expression.
1 or more statements.
ELSEIF logical_expression.
1 or more statements.
ENDIF.

IF var_a LT var_b.
WRITE / var_a.
ENDIF.

IF var_a LT var_b.
WRITE / var_a.
ELSE.
WRITE / var_b.
ENDIF.

IF var_a LT var_b.
WRITE / var_a.
ELSEIF var_b LT var_c.
WRITE / var_b.
ENDIF.


1/23/2011
9
Conditional code execution: CASE
CASE data_object.
WHEN value.
1 or more statements.
WHEN value.
1 or more statements.
WHEN OTHERS.
1 or more statements.
ENDCASE.


CASE var_a.
WHEN 1.
WRITE \ 'uno'.
WHEN 2.
WRITE \ 'dos'.
WHEN OTHERS.
WRITE \ 'other'.
ENDCASE.
Quick Practice
1/23/2011
10
Using the Debugger to test programs
Program must be saved and activated before debugging.
Set a breakpoint indicating where you want the program to stop in
the execution and display the debugger.
Use Direct Processing to begin execution. Program runs to
breakpoint.
In the source code display, double click any variable you wish to
watch.
Add/remove additional breakpoints by single clicking to left of line.
Step through code using controls in upper leftsingle step, execute,
return, continue (runs until next breakpoint).
Watched variable values can be changed.
A watchpoint can be set of a variable and the program will run until
that variable's value changes
Looping
DO value TIMES.
1 or more statements.
ENDDO.

WHILE condition.
1 or more statements.
ENDWHILE.

DO.
1 or more statements.
IF abort_condition.
EXIT.
ENDIF.
ENDDO.
DO var_a TIMES.
WRITE / 'Hi'.
ENDDO.

WHILE var_a < 10.
var_a = var_a * 2.
ENDWHILE.

DO.
var_a = var_a * 2.
IF var_a > 200.
EXIT.
ENDIF.
ENDDO.
ABAP supports definite iteration, pre-test iteration, and post-test
iteration.
Within loops sy-index is a system managed loop counter.
1/23/2011
11
Exiting Loops
EXIT: Loop exits immediately. Jump to statement that follows loop
block.
CONTINUE: Restart next loop iteration.






CHECK condition: Restart next loop iteration (continue) if false.
WHILE sy-index < 10.
WRITE / sy-index.
IF sy-index < 3.
CONTINUE.
ENDIF.
WRITE 'After ENDIF'.
ENDWHILE.
WHILE sy-index < 10.
WRITE / sy-index.
CHECK sy-index < 3.
WRITE 'After CHECK'.
ENDWHILE.
Quick Practice
1/23/2011
12
Copyrights
Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries,
xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+,
POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF,
Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of
IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
Oracle is a registered trademark of Oracle Corporation.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, and other SAP products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business
Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects S.A. in the
United States and in other countries. Business Objects is an SAP company.
Other products mentioned in this presentation are trademarks of their respective owners.
Presentation prepared by and copyright of Dr. Tony
Pittarese, East Tennessee State University, Computer and
Information Sciences Dept. (pittares@etsu.edu)
Podcast lecture related to this presentation available via
ETSU iTunesU.
1/31/2011
1
Spring 2011 Enterprise Programming
BASIC PRINCIPLES OF
ABAP
From the textbookChapter Three
Role of NetWeaver in ABAP development
3 layered architecture:
Presentation Layer
Web Dynpro ABAPweb-based interfaces
Business Server Pages (BSP)server-side ABAP
for the Web
DynproSAP GUI interfaces
Application Layer
ABAP Objects
XSLT and STABAPXML
JavaScriptimplemented as a server-side script to support BSPS
Persistence Layer
Open SQLtranslates standardized SQL into DBMS-specific SQL
Native SQLnon-translated DBMS-specific SQL

1/31/2011
2
From the textbookChapter Three
ABAP program design
Global declaration part
Creation of data types, data objects, objects,
and other structures
Implementation part
Code logic using items from global declaration
Launching ABAP programs using SA38
Launching ABAP programs via Transaction Code
Dialog transactionsdesignated program loaded and run
OO transactionsdesignated method of selected object is run
Launching ABAP programs programmatically
CALL TRANSACTION progname, LEAVE TO TRANSACTION progname

From the textbookChapter Three
ABAP program types
Class poolsglobal class definition. Created via
Class Builder. No typical source code.
Interface poolsglobal interface definition.
Created via Class Builder.
Function groups/poolsfunction libraries
Subroutine pools
Executable programs
Module pools
Type groupsdefines types for general global use
Includes
Source code include via INCLUDE progname
Top Includeglobal declarations visible to included programs

1/31/2011
3
Discussion Topics
Analyzing Runtime Errors with ST22
Defining and Calling Subroutines
Parameter Passing
Messages
String Manipulation in ABAP
Complex Data Types
Structures
Internal Tables
Internal Table Operations


Analyzing Runtime Errors
In the event a runtime error causes a program to crash, transaction
ST22 is used to analyze the dump produced by the crash.
1/31/2011
4
ST22 Analyze Runtime Errors
Subroutines
Similar to functions in other languages. Provides encapsulation of
functionality. Permits parameter passing using different methods.
Basic Syntax:





It is typical for subroutine definitions to be placed at the end of
program source code. (internal subroutine)
Subroutines can see and manipulate global program data, but that is
considered very poor design. (Violates principle of encapsulation.)

FORM mysubroutine. "subroutine definition
1 or more statements here.
ENDFORM.
PERFORM mysubroutine. "subroutine call
1/31/2011
5
Parameter passing to subroutines
Actual parameters (caller) are copied/transferred to formal
parameters listed in the subroutine (callee) interface.
Parameter passing methods:
Call by Valueformal parameter value copied to actual parameter.
Call by Referenceactual parameter becomes local alias for formal
parameter. Subroutine operates on original formal parameter (no
copy made). Changes to actual parameter effective in formal
parameter when subroutine terminates.
Call by Value and Resultformal parameter value copied to actual
parameter. At end of subroutine (if reached successfully), the
actual parameter's final value is copied back to the formal
parameter.
Parameter typing
Actual parameters are typed upon data object creation in the main
program.
Formal parameters may be listed without type or with TYPE ANY. This
generic typing allows parameters of any type to be passed to the
subroutine.
Generic typing may result in a runtime error if an operation is
performed which is invalid for the type of data received.
Formal parameters may be listed with a TYPE clause to set a fixed
type. This concrete typing may result in an automatic type
conversion attempt (if possible).
For incomplete data types (p, n, c, x) a LENGTH clause is not set.
Formal parameters may use user-defined local or global types.
1/31/2011
6
Parameter passing mechanicscall by value









Note subroutine definition places formal parameter name within
value(). This indicates it is the value of the data object which is
passed (i.e. it is copied).
The call lists the actual parameter (note that value() is not indicated).
Use of USING indicates that the value of the actual parameter in the
caller cannot change based on the subroutine.
FORM mysubroutine "subroutine definition
USING
value(subvar1) TYPE i.
1 or more statements here.
ENDFORM.
PERFORM mysubroutine "subroutine call
USING
mainvar1.
Parameter passing mechanicscall by reference
Note value() not used. This indicates that value is not copied. Subroutine is
operating on the 'original' data object.
Since the subroutine is operating on the original actual parameter, changes
it makes are effective on the original when the subroutine completes.
If the module will be making changes, use CHANGING. If it will not be
making changes, use USING. The difference between USING and
CHANGING in this context is strictly for clarity of design.









FORM mysubroutine "subroutine definition
USING [or CHANGING]
subvar1 TYPE c.
1 or more statements here.
ENDFORM.
PERFORM mysubroutine "subroutine call
USING [or CHANGING]
mainvar1.
1/31/2011
7
Parameter passing mechanicscall by value and result
The use of value() indicates that a copy of the data object's value is
passed to the subroutine.
The use of CHANGING indicates that at the successful end of the
subroutine, the final value of the formal parameter will be copied
back to the actual parameter (caller).
FORM mysubroutine "subroutine definition
CHANGING
value(subvar1) TYPE ANY.
1 or more statements here.
ENDFORM.
PERFORM mysubroutine "subroutine call
CHANGING
mainvar1.
Parameter Passing Syntax Summary
Caller (actual parameters) Callee (formal parameters)
Using Changing Using Changing Value()
Call by value

Call by value and result

Call by reference with no
change in subroutine

Call by reference with
change in subroutine

Any time a copy operation is a part of parameter passing, the actual
parameter will be listed within value() in the subroutine definition.
Any time the subroutine will change the value of the formal
parameter, CHANGING is used with formal and actual parameters.
With Call by Reference use of USING is a design 'contract' to not
change the value. This is not enforced by ABAP.
1/31/2011
8
Test your Understanding
PERFORM mysubroutine
USING
mainvar1
mainvar2
CHANGING
mainvar3
mainvar4.
FORM mysubroutine
USING
subvar1
value(subvar2)
CHANGING
value(subvar3)
subvar4.
ENDFORM.
Note the placement of periods in the syntax!
Identify the type of
parameter passing used for
each parameter shown.
Parameter Passingcomplete example
PERFORM mysubroutine
USING
mainvar1
mainvar2
CHANGING
mainvar3
mainvar4.
FORM mysubroutine
USING
subvar1
value(subvar2)
CHANGING
value(subvar3)
subvar4.
ENDFORM.
Note the placement of
periods in the syntax!
1/31/2011
9
Parameter passing rules
Although a subroutine can operate on global data, this is poor design
and should never be done. The risk of maintenance errors is greatly
increased.
Select the most conservative method of parameter passing based on
design goals:
Call by value has the benefit of providing data object security.
Changes in the variable in the subroutine will not affect the main
data object.
Call by value and call by value and result have the disadvantage of
overhead associated with making data object copies. Avoid for
large data objects.
Quick Practice
1/31/2011
10
Exiting subroutines
A subroutine terminates normally if the flow of control reaches
ENDFORM or a RETURN statement is reached. Flow of control is
returned to the statement after the calling statement.
Call by Value and Return parameters written back to calling
parameters before returning flow of control.
A STOP statement or display of an error message causes the
subroutine to terminate and the overall program to exit.
Call by Value and Return parameters not written back to calling
parameters.
Sending Messages
MESSAGE 'message text' TYPE '[type]'.
Used to note special program conditions. Types of messages:









*Depends on GUI settings
Type Meaning Behavior Location
I information Display message. Program continues after
user dismisses message.
Modal dialog box
S set message Display message. Program continues
without interruption
Status bar or modal
dialog box*
W warning Display message. Behavior depends on
context.
Status bar or modal
dialog box*
E error Display message. Behavior depends on
context.
Status bar or modal
dialog box*
A termination Program terminated Modal dialog box
X short dump Runtime error triggered with dump Dump to screen
1/31/2011
11
Time for a short break
Useful ABAP Statements: String Manipulation
ABAP provides a number of language constructs for working with
string-type data. These work for data types string, c, d, t, and n.

CONCATENATE s1 s2 INTO s3 [SEPARATED BY s4].
S3 must be of sufficient size or the new string will be truncated.

1/31/2011
12
String Manipulation
FIND s1 IN s2.
FIND [FIRST OCCURRENCE OF or ALL OCCURENCES OF]
s1 IN s2.
FIND s1 IN s2 [IGNORING CASE or RESPECTING
CASE].
Result of find operation stored in sy-subrc.
sy-subrc set to 0 if found.
sy-subrc set to 4 if not found.
FIND ALL OCCURRENCES OF s1 IN s2 MATCH COUNT x.
Number of found strings stored in x.
Regular expression processing is possible as well. (FIND REGEX)
String Manipulation
REPLACE s1 IN s2 WITH s3.
REPLACE [FIRST OCCURRENCE OF or ALL OCCURENCES
OF] s1 IN s2 WITH s3.
REPLACE s1 IN s2 [IGNORING CASE or RESPECTING
CASE] WITH s3.
Result of replace operation stored in sy-subrc.
sy-subrc set to 0 if a replacement was done.
sy-subrc set to 2 if a replacement was done, but the result was
truncated due to variable size.
sy-subrc set to 4 if not found.
REPLACE ALL OCCURRENCES OF s1 IN s2 WITH s3
REPLACEMENT COUNT x.
Number of replaced strings stored in x.

1/31/2011
13
String Manipulation
SPLIT s1 AT char INTO s2 s3 [s4 ].
Can create as many substrings as relevant.
If insufficient substrings listed, the remaining text and the separator
are placed into the last substring listed.

Quick Practice
1/31/2011
14
Complex data types--structures
Complex data types can be defined to create structured variables
(also called structures)
TYPES:
BEGIN OF struct_type_name,
field_name TYPE type,
field_name TYPE type, [] as needed
END OF struct_type_name.
Components of a structure are referenced using a hyphen:
structure_variable_name structure_component_name
Structures can be nested.
Structure variable a1 can be copied to structure variable a2 using:
MOVE-CORRESPONDING a1 TO a2.
Only like name components are copied. All others ignored.
Structure Example
TYPES:
BEGIN OF address_struct,
address1 TYPE c LENGTH 60,
address2 TYPE c LENGTH 60,
city TYPE c LENGTH 60,
state TYPE c LENGTH 2,
zip TYPE n LENGTH 5,
zipext TYPE n LENGTH 4,
END OF address_struct.
Note this comma!
DATA str TYPE address_struct.
str-address1 = '10061 Bristol Park Road'.
str-city = 'Cantonment'.
str-state = 'FL'.
str-zip = '37614'.
str-zipext = '6610'.
1/31/2011
15
Practice Working with Structures
Introducing SAP's training database tables
SAP provides a set of database tables based on airplane flight related
data (flights, airports, meals, customers, etc.)
Some tables of interest:
SAIRPORT airport information
SCARR airline information
SPFLI flight schedules
SBOOK flight bookings
SCUSTOM flight customers
Transaction SE16 can be used to view table contents
1/31/2011
16
Complex data typesInternal Tables
Similar to database table concept, but stored in memory.
Number of records restricted only by capacity of system.
Useful for temporarily storing data from database for processing,
preparing data for output, or preparing data for other use.
Data in an internal table can be accessed by searching the table based
on key column values or indexes (row numbers).
Keys may be unique or non-unique. Searching an internal table with
non-unique keys may result in more than 1 record returned per
search.
Three types of internal tables:
Standardsimilar to DB table (row and key access possible)
Sorteddata always sorted by keys (row and key access possible)
Hashed Tablekeys must be unique (only key access possible)
Internal Table TYPE Creation
A internal table is a dynamic sequence of items of the same type
typically structures, but other data types are possible.
TYPES:
Table_type_name
TYPE [table type] TABLE OF [data type]
WITH [ UNIQUE | NON-UNIQUE] KEY
List_of_keys.





A standard table can only have non-unique keys, hashed tables can
only have unique keys, and sorted can have either.
TYPES:
address_table_type
TYPE STANDARD TABLE OF address_struct
WITH NON-UNIQUE KEY
address1 zip.
1/31/2011
17
Internal Table Creation and Data Filling Example
Training table SCARR is of type SBC400_T_SCARR.
Use SE11 to view the table and data type in ABAP Dictionary.
Create an internal table of the same type as SCARR:

Create a structure that matches the columns contained in the internal
table just created:

Copy the contents of database table to an internal table:

Write the contents of the internal table to the screen as a list


DATA itable TYPE sbc400_t_scarr.
DATA str LIKE LINE OF itable.
SELECT * FROM scarr INTO TABLE itable.
LOOP AT itable INTO str.
WRITE: / str-mandt, / str-carrid, / str-carrname,
/ str-currcode, / str-url, /.
ENDLOOP.
Single Record Table Operations
Append
Adds data object to the end of the table
APPEND data_obj TO table_obj.
Insert
In standard table, same as append. In sorted table, inserted based
on sort order. In hashed table, inserted based on hash algorithm.
INSERT data_obj INTO TABLE table_obj.
Read
Copies a table row into a specified data object
Row selection can be based on index number or table key.
READ TABLE table_obj INDEX n INTO data_obj.
READ TABLE table_obj WITH TABLE KEY field =
'value' INTO data_obj.


1/31/2011
18
Single Record Table Operations
Change
Changes a table row
Based on index:
MODIFY tbl_obj INDEX n FROM obj.
MODIFY tbl_obj INDEX n FROM obj TRANSPORTING
comp [comp].
Based on key value:
MODIFY TABLE tbl_obj FROM obj TRANSPORTING comp
[comp].
Delete
Deletes a row
DELETE tbl_obj INDEX n.
DELETE TABLE tbl_obj WITH TABLE KEY key = value.

Multiple Record Table Operations
LOOP ATENDLOOP
Loops through entire table (or portion) copying rows into a data object.
LOOP AT tbl_obj INTO obj.
LOOP AT tbl_obj INTO obj FROM index.
LOOP AT tbl_obj INTO obj TO index.
LOOP AT tbl_obj INTO obj WHERE col = val.
DELETE
Deletes row(s) matching condition
DELETE tbl_obj FROM index.
DELETE tbl_obj TO index.
DELETE tbl_obj WHERE col = val




1/31/2011
19
Multiple Record Table Operations
INSERT
Copies rows from one internal table to another
INSERT LINES OF tbl_obj [condition] INTO
tbl2_obj [condition].
Append
Appends rows from one internal table to another
APPENDS LINES OF tbl_obj [conditon] TO
tbl2_obj.



Quick Practice
1/31/2011
20
Copyrights
Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries,
xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+,
POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF,
Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of
IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
Oracle is a registered trademark of Oracle Corporation.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, and other SAP products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business
Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects S.A. in the
United States and in other countries. Business Objects is an SAP company.
Other products mentioned in this presentation are trademarks of their respective owners.
Presentation prepared by and copyright of Dr. Tony
Pittarese, East Tennessee State University, Computer and
Information Sciences Dept. (pittares@etsu.edu)
Podcast lecture related to this presentation available via
ETSU iTunesU.
2/7/2011
1
Spring 2011 Enterprise Programming
ABAP OBJECTS, PART 1
Discussion Topics
Class Definition
Attributes
Methods
Simple Object Instantiation

2/7/2011
2
Object Oriented ABAP Development
OO often considered superior to procedural programming due to
encapsulation of data with related functionality.
ABAP Objects similar conceptually to languages like C++ and Java.
Backwards compatible with procedural ABAP, so objects can be used
in procedural coding.
Some language constructs considered deprecated (yet still supported
in procedural ABAP) are disallowed in ABAP objects.
Just as in other OO languages, ABAP Objects supports:
Inheritanceone class shares structure and behavior with another
Polymorphismdifferent (but related) objects have the same
communication interface
Eventsobjects respond when triggered. Objects can trigger an
event.

OO ABAP
Classdefinition of the structure and functionality of an object-to-be.
Defines data the object will contain (attributes) and related
functionality (methods).
ABAP class syntax divides the class definition (containing attribute
declarations and method interface definitions) and the class
implementation (method functionality definitions).




Can be defined locally or globally (using Class Builder trans SE24).
Objectinstantiation of a class, storing actual data and/or allowing
method execution.
CLASS exampleclass DEFINITION.
ENDCLASS.
CLASS exampleclass IMPLEMENTATION.
ENDCLASS.
2/7/2011
3
Attribute Definition
A class definition may define the following: types, constants, data
objects (attributes), and method interfaces.
Items may be designated publicavailable from outside the object,
or privateavailable only within the object itself.
A public attribute may be designated READ-ONLY.
Within the class definition, the public section must come before the
private section.














CLASS exampleclass DEFINITION.
TYPES "definition of data types
PUBLIC SECTION. [PRIVATE SECTION.]
CONSTANTS "definition of constants
DATA "definition of data objects
DATA name TYPE type READ-ONLY. "read-only
ENDCLASS.
Static Attributes
A static attribute is an attribute whose value is shared among all
objects in a class and is not dependent on instantiation.
Often used for things like object instance counters.
Since the data belongs to the class and is shared among the objects, it
is declared as CLASS-DATA.

CLASS exampleclass DEFINITION.
PUBLIC SECTION. [PRIVATE SECTION.]
CLASS-DATA name TYPE type.
ENDCLASS.
Attributes (static or instance) may use VALUE upon declaration to set
a default value.
2/7/2011
4
Quick Practice
Method Definition
In the class definition, the method definition indicates a method's
interface.
Method parameters
Method return type (method signature)
Method exception (to be covered later)
Methods may be designated as public or private.
A private method may only be called from within another method
of the class.
CLASS-METHODS may be defined. These methods may only access
static attributes.
Class methods may be invoked either using the name of the class or
on an object of the class.
An object does not need to be instantiated to invoke a class
method.
2/7/2011
5
Method Parameters
Method parameter types:
IMPORTINGinput parameters
Used to transfer data to a method. May be designated as OPTIONAL. May
have a DEFAULT value specified.
Value of parameter may not be changed in method definition. (system
enforced)
EXPORTINGoutput parameters
At end of method value of formal parameter copied back to actual.
Export parameters are always optional (by default).
Intent is for the incoming value of the parameter to not be used (not system
enforced).
CHANGINGcombination of above
Passed to method for use. Can be changed.
May be designated as OPTIONAL. May have a DEFAULT value specified.
With any of the above, parameters may be designated pass by value.
Method return values
A method may be defined to return a single value.
This is specified by listing RETURNING in the interface.
If RETURNING is indicated, EXPORTING and CHANGING parameters
may not be specified.
The return operation is not done with an explicit RETURN statement
but rather by assigning a value to the name of the data object listed
in the RETURNING statement.
A method with a return value is called a functional method. Unlike
other methods, functional methods they can be called within other
statements such as IF, CASE, and WHILE.

2/7/2011
6
Example method definition
CLASS exampleclass DEFINITION.
PUBLIC SECTION. "attributes not shown
METHODS method1
IMPORTING var1 TYPE i OPTIONAL
value(var2) TYPE i
EXPORTING var3 TYPE i
CHANGING var4 TYPE i.
METHODS method2
IMPORTING var1 TYPE I DEFAULT 4
RETURNING value(retval) TYPE i.

PRIVATE SECTION.
"method and/or attribute definition
ENDCLASS.
Order:
Importing
Exporting
Changing
Returning
Method Implementation
Code for functionality of a method placed in class implementation.
Parameter names and types are not listed, as they have already been
declared in the function definition.
CLASS exampleclass IMPLEMENTATION.
METHOD method1.
"code for method1 goes here. In this code
"var1 and var2 can be used, var3 should be set
"to a value for export, and var4 will
"potentially be changed
ENDMETHOD.
METHOD method2.
"similar to above, only var1 can be used and
RETURN retval. "retval must be returned.
ENDMETHOD.
ENDCLASS.
2/7/2011
7
Constructor
A class may define a constructor method named constructor.
The method must be public and only have importing parameters.
The constructor is not called explicitly, but rather is called implicitly
when a new object is created.
Constructors are useful for:
Initializing attributes for an object.
Allocating resources for the object.
Modifying static attributes (programmatically).
Triggering other activities that need to happen when a new object
is created.
A static constructor method can be created named class_constructor.
This method will be called first time an object of this class is
created or a static attribute or static method of the class is used.
Self-reference
Within a method, reference to object attributes or other methods is
generally unambiguous. In the event of ambiguity (a parameter has
the same name as an attribute), you can refer to the object, its
attributes, and its methods using me.
Syntax: me->attributename
2/7/2011
8
Quick Practice
Object Creation
Objects are created by defining an object reference variable and then
creating the object.
The START-OF-SELECTION keyword indicates where the runtime
environment should begin control flow.





Further instantiation details (showing parameter) passing shown in
the lesson immediately following.
* Object definitions here
START-OF-SELECTION.
DATA objectname TYPE REF TO classname.
CREATE OBJECT objectname.
2/7/2011
9
Copyrights
Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries,
xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+,
POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF,
Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of
IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
Oracle is a registered trademark of Oracle Corporation.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, and other SAP products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business
Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects S.A. in the
United States and in other countries. Business Objects is an SAP company.
Other products mentioned in this presentation are trademarks of their respective owners.
Presentation prepared by and copyright of Dr. Tony
Pittarese, East Tennessee State University, Computer and
Information Sciences Dept. (pittares@etsu.edu)
Podcast lecture related to this presentation available via
ETSU iTunesU.
3/14/2011
1
Spring 2011 Enterprise Programming
ABAP OBJECTS, PART 2
Discussion Topics
Working with static method and attributes
Object Instantiation

3/14/2011
2
Working with classes in programs
Classes, when instantiated, become objects.
Not all classes need to be instantiated to be used within programs.
Static attributes (CLASS-DATA)
Static methods (CLASS-METHODS)
To reference a static public attribute:
classname=>attributename
myvar = classname=>attributename
To call a static method:
CALL METHOD classname=>methodname. "traditional
classname=>methodname( ). "as of Web AS 6.10
Static vs. instance: Static uses => Instance uses -> Other syntax
elements are the same.
Calling methods
Cannot be a space before opening parenthesis. Must be one after.
If only one importing parameter in method definition, list the actual
parameter in the parenthesis by listing data object name only.
class=>method( data1 ).
If several importing parameters, parameters must be listed in pairs:
formal parameter = actual parameter.
class=>method( par1 = data1 par2 = data2 ).
If there are parameters of types other than importing, the type of
parameter passing must be listed.
class=>method( EXPORTING p1 = d1 p2 = d2
IMPORTING par3 = data3
CHANGING par4 = data4 ).


3/14/2011
3
Calling methods
Functional methods (those that return a value)
The value to be returned by be listed in the method call interface
using the parameter passing type RECEIVING.
class=>method( IMPORTING p1 = d1
RECEIVING par4 = data4 ).
The value to be returned may be captured through assignment
(more typical).
data3 = class=>method( d1 ).


Calling methods
Parameter passing types defined in the method definition correspond
to parameter passing types in the caller but are not the same.



Method Definition Method Call
IMPORTING EXPORTING
EXPORTING IMPORTING
CHANGING CHANGING
RETURNING RECEIVING
Method Call Method Definition
I am exporting a
value to you
I am importing a
value from you
3/14/2011
4
Let's Practice
Static Rules
Static methods can only access static attributes.
Static method may define local data objects.
Instance methods can access static and instance attributes.
3/14/2011
5
Object Creation
Objects are created by defining an object reference variable and then
creating the object.
The START-OF-SELECTION keyword indicates where the runtime
environment should begin control flow.









* Object definitions here
START-OF-SELECTION.
DATA objectname TYPE REF TO classname.
CREATE OBJECT objectname.
Copyrights
Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries,
xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+,
POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF,
Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of
IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
Oracle is a registered trademark of Oracle Corporation.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, and other SAP products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business
Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects S.A. in the
United States and in other countries. Business Objects is an SAP company.
Other products mentioned in this presentation are trademarks of their respective owners.
Presentation prepared by and copyright of Dr. Tony
Pittarese, East Tennessee State University, Computer and
Information Sciences Dept. (pittares@etsu.edu)
Podcast lecture related to this presentation available via
ETSU iTunesU.
CLASS exampl e DEFI NI TI ON. 1
PUBLI C SECTI ON. 2
CLASS- METHODS met hod0. 3
4
CLASS- METHODS met hod1 5
I MPORTI NG var 1 TYPE i . 6
7
CLASS- METHODS met hod2 8
I MPORTI NG var 1 TYPE i 9
var 2 TYPE i 10
EXPORTI NG var 3 TYPE i 11
CHANGI NG var 4 TYPE i . 12
13
CLASS- METHODS met hod3 14
I MPORTI NG var 1 TYPE i 15
RETURNI NG val ue( var 2) TYPE i . 16
ENDCLASS. 17
18
CLASS exampl e I MPLEMENTATI ON. 19
METHOD met hod0. 20
WRI TE / ' Hi f r ommet hod0' . 21
ENDMETHOD. 22
23
METHOD met hod1. 24
WRI TE: / ' You ar e a ni ce par amet er ' , ( *) var 1. 25
ENDMETHOD. 26
27
METHOD met hod2. 28
var 3 = var 1 * var 2. 29
var 4 = var 3 * 2. 30
ENDMETHOD. 31
32
METHOD met hod3. 33
var 2 = var 1 * 7. 34
ENDMETHOD. 35
ENDCLASS. 36
37
START- OF- SELECTI ON. 38
39
DATA: dat a1 TYPE i VALUE 3, 40
dat a2 TYPE i VALUE 6, 41
dat a3 TYPE i VALUE 9, 42
dat a4 TYPE i VALUE 12. 43
44
3/14/2011
1
Spring 2011 Enterprise Programming
ABAP DICTIONARY BASICS
AND DATABASE INTERACTION
ABAP Dictionary
The ABAP Dictionary (SE11) allows
Centralized type definition and management
Creation of user-defined data elements, structures, and table types
Definition of tables, indexes, and views
Definition of services that support program development
Table locking and lock releasing
Defining input help (F4)
Defining field help (F1)
Changes within the ABAP Dictionary are immediately in effect for
those programs which use that dictionary elements.
3/14/2011
2
Data Definition
Data Types Three types can be defined:
Data Element
Structure
Table Types (internal tables)
The Type Group option provided by the Dictionary that is primarily
there to support older development. (Type Groups were available
before Data Types were supported.)
Type Groups now are primarily used to define non-object-oriented
constants.
Domain data is available to support the definition of data types, but
domain data is not accessible in an ABAP Program.
There are 24 data specifications in the domain that are used in Data
Dictionary Data Types.
Data Element
Data Objects and the Data Dictionary
Domain
Database Table
Fields
Structure
Components
Internal Table
Line structure
ABAP
Program
3/14/2011
3
Tables in the ABAP Dictionary
Tables consist of columns (fields) and rows (entries).
In the ABAP Dictionary tables have names, and general attributes
such as a delivery class and maintenance authorization.
A table has one or more key fields, designated as the primary key.
Table fields are commonly based on data elements which are based
on domain data.
Table fields may be typed without reference to a data element. In
this case the field is said to be direct typed.
Tables have technical settings which govern how the system should
optimize the data storage and access the table.
What is the expected table size?
Should the table be buffered? Should changes to the table be
logged?
Transparent tables
When a table is defined in the ABAP Dictionary it is a transparent
table. When the transparent table is activated, it is created in the
underlying DBMS.
The DBMS-specific table is the same name as the ABAP Dictionary
transparent table name.
The field types in the DBMS-specific table are converted to
whatever the appropriate data type definition is in the DBMS.
Underlying elements of the table (such as field order, etc.) may be
changed as necessary.
The transparent table in the ABAP Dictionary is the database-
independent representation of the underlying table, and is used in
ABAP programming.

3/14/2011
4
SAP WAS Architecture
Presentation Layer
Database Layer
Application Layer ABAP Dispatcher
Work
Process
Work
Process
Work
Process
Buffer
DB
Work
Process
Buffer
DB
Disks
DB
Disks
Open SQL
Open SQL statements in ABAP program converted to database-
specific SQL by the database interface.
It is possible to access database with Native SQL, but the code is
then database specific and less transportable.
Many Open SQL statements mirror those of "traditional" SQL, but
with subtle differences and refinements.
3/14/2011
5
SAP LUW Concept
SAP LUW (Logical Unit of Work)set of logical changes to a database
that all belong together.
A LUW is done in accordance with the "all or nothing" principle.
If entire sequence cannot be done, the operation is rolled back.






Commit operation committed implicitly or via ABAP statement
COMMIT WORK. Rollback done via statement ROLLBACK WORK.
Database
"Sealed"
Status
Change Change Change
Database
"Sealed"
Status
Database LUW
Rollback possible at any point in this sequence.
Database
Commit
Necessity of LUW
SAP ERP is three tiered client-server architecture. On the application
server, end user applications are executed via work processes.
Multiple work processes in effect simultaneously. By partitioning
database operations into LUWs, database integrity can be
maintained and a work process can access and release database
resources rapidly.
3/14/2011
6
Database Locking
To avoid simultaneous/concurrent changes to database tables from
multiple programs, locks are used.
Example: The command SELECT SINGLE field FROM dbtable FOR
UPDATE will lock the record selected in anticipation of a pending
change.
At the end of the LUW, the lock is released.
To lock a resource for a more extended sequence, the system
maintains a global lock table which manages locks set
programmatically for various resources.
To set the lock: ENQUEUE lockobject.
To release the lock: DEQUEUE lockobject.
Open SQL
Open SQL contains only Data Manipulation Language (DML)
commands. Data Definition Language (DDL) operations are done
using the ABAP Dictionary.
Four basic Open SQL commands:
SELECT
UPDATE
INSERT
DELETE

3/14/2011
7
Database related sy fields
sy-subrc is set after all database operations.
0 = successful completion.
Other values indicate different error types.
sy-dbcnt is set to the number of records affected by the last
operation.
Select Statement
5 clauses:
SELECT <result>
Determines fields to be chosen and whether 1 record or multiple will
be retrieved.
SELECT SINGLEretrieves 1 row: the first match.
FROM <table>
INTO <target>
Specifies data object where result will be stored.
Results loaded based on order specified, unless CORRESPONDING
FIELDS OF added to statement.
WHERE <condition>
Specifies which rows are to be chosen.
sy-subrc
0 = success
4 = empty resultset (no data found)
3/14/2011
8
MANDT field
Most system tables contain an MANDT field designating a client.
Open SQL commands by default are done for the current client only.
To override this behavior add the CLIENT SPECIFIED clause to the
command.
Allows a client number to be specified, for example in a WHERE
clause in a query.
If CLIENT SPECIFIED is used but no client-limiting code is included,
data for all clients is returned.
DATA iTab TYPE TABLE OF spfli.
DATA str LIKE LINE OF iTab.

SELECT mandt carrid connid cityfrom cityto FROM spfli
INTO CORRESPONDING FIELDS OF TABLE iTAB.

LOOP AT iTab INTO str.
WRITE: / str-mandt, str-carrid, str-connid,
str-cityfrom, str-cityto.
ENDLOOP.
DATA iTab TYPE TABLE OF spfli.
DATA str LIKE LINE OF iTab.

SELECT mandt carrid connid cityfrom cityto FROM spfli
CLIENT SPECIFIED INTO CORRESPONDING FIELDS OF TABLE iTAB.

LOOP AT iTab INTO str.
WRITE: / str-mandt, str-carrid, str-connid,
str-cityfrom, str-cityto.
ENDLOOP.
3/14/2011
9
SELECT loop
If INTO clause indicates INTO TABLE, result put into internal table in a
single step operation called an array fetch.
If INTO clause does not specify INTO TABLE, data copied iteratively to
a data object (or objects).
Creates a select loop where body of the loop can specify actions to
be taken on the data object during each iteration.
Loop ends with the ENDSELECT statement.
DATA str TYPE SPFLI. "structure matching table row
SELECT CARRID CONNID CITYFROM CITYTO FROM SPFLI
INTO CORRESPONDING FIELDS OF str.
WRITE: / str-CARRID, 'flight', str-CONNID,
str-CITYFROM, 'to', str-CITYTO.
ENDSELECT.
WRITE: / sy-dbcnt, 'rows output.'.
Select loop into individual data objects
In lieu of a structure as the copy destination, a set of individual data
objects may be specified:
SELECT fields FROM table INTO (var1, var2) WHERE
DATA: my-client TYPE c LENGTH 3,
my-carrid TYPE c LENGTH 3,
my-connid TYPE c LENGTH 4.

SELECT mandt carrid connid FROM spfli CLIENT
SPECIFIED INTO (my-client, my-carrid, my-connid).
WRITE: / my-client, my-carrid, my-connid.
ENDSELECT.

WRITE: / sy-dbcnt, 'rows output.'.
3/14/2011
10
INSERT
INSERT INTO dbtable VALUES structure.
INSERT INTO dbtable FROM structure.
INSERT dbtable FROM TABLE internaltable.
sy-subrc
0 = success
4 = insertion not possible as line with same key already present
For FROM TABLE option if even one line of internaltable cannot be
inserted due to duplicate key in dbtable, the entire operation is
rolled back.
If desire all valid rows to be inserted, add ACCEPTING DUPLICATE
KEYS to the statement.
Duplicate rows still skipped, but other rows inserted.
sy-subrc set to 4 to indicate this condition, sy-dbcnt set to number
of rows successfully inserted.



UPDATE a single record or multiple records
UPDATE dbtable FROM str.
Key field values in str are used for row selection.
UPDATE dbtable SET field = value field = value WHERE keyfield =
value AND keyfield = value.
Only fields specified in SET clause are changed.
If conditions specified in WHERE are not unique keys, multiple
records may be changed.
UPDATE dbtable FROM TABLE internaltable.
sy-subrc
0 = success
4 = update not possible (key not found or other problem)
sy-dbcnt set to number of updated rows

3/14/2011
11
MODIFY
If record does not exist, INSERT operation done. If record exists,
UPDATE operation done.
MODIFY dbtable FROM structure.
MODIFY dbtable FROM TABLE internaltable.
sy-subrc
0 = success
4 = modify not possible (key not found or other problem)
sy-dbcnt set to number of updated rows


DELETE
DELETE FROM dbtable WHERE key = value AND key = value
DELETE FROM dbtable WHERE condition.
DELETE FROM dbtable FROM TABLE internaltable.
Key fields as found in internaltable deleted from dbtable.
sy-subrc
0 = success
4 = delete not possible (key not found or other problem)
sy-dbcnt set to number of updated rows


3/14/2011
12
Joins
It is possible to join tables in a query.
SELECT * FROM table1 INNER JOIN table2 ON table1~field =
table2~field WHERE <condition>.
Called a link in ABAP. If the join done in a program it is a dynamic
link.
Pre-existing links, static links, are defined in the ABAP Dictionary.
These are called views.

Additional details on joins are beyond the scope of this class, but are
well documented in the ABAP documentation.
Copyrights
Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries,
xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+,
POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF,
Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of
IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
Oracle is a registered trademark of Oracle Corporation.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, and other SAP products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business
Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects S.A. in the
United States and in other countries. Business Objects is an SAP company.
Other products mentioned in this presentation are trademarks of their respective owners.
Presentation prepared by and copyright of Dr. Tony
Pittarese, East Tennessee State University, Computer and
Information Sciences Dept. (pittares@etsu.edu)
Podcast lecture related to this presentation available via
ETSU iTunesU.
3/22/2011
1
SELECTION SCREENS AND
LIST PROCESSING EVENTS
Spring 2011 Enterprise Programming
Getting Data from User at Runtime
PARAMETERS is the most basic type of input acceptance.
Using Parameters generates a default selection screenscreen
1000.
If the type of item prompted is based on a global type this allows
input help (F1) and entry selection help (F4) are shown as defined in
the ABAP dictionary.
PARAMETERS: carrier TYPE sflight-carrid,
fltdate TYPE sflight-fldate.
3/22/2011
2
Event blocks
An ABAP program is a collection of processing blocks.
Event blockscalled by runtime environment when related event
has been triggered through natural program flow of control or
when triggered by a user action when triggered by a user action.
Our initial programsone blockso no need to declare event blocks.
Program event blocks:
LOAD-OF-PROGRAM(called at initial program setup)
START-OF-SELECTION (beginning of main processing)
Example use: PARAMETERS triggered at beginning of main Example use: PARAMETERS triggered at beginning of main
processing. If want to set a default value for field based on
processing (calculation, data retrieval), must do this before
START-OF-SELECTION.
Example
PARAMETERS date LIKE sy-datum DEFAULT sy-datum.
WRITE date.
DATA pastdate LIKE sy-datum.
pastdate = pastdate - 7.
PARAMETERS date LIKE sy-datum DEFAULT pastdate.
WRITE date.
LOAD-OF-PROGRAM.
DATA pastdate LIKE sy-datum.
pastdate = sy-datum - 7.
PARAMETERS date LIKE sy-datum DEFAULT pastdate.
START-OF-SELECTION.
WRITE date.
3/22/2011
3
Selection Screen Input
Selection screen display and control can incorporate additional
elements beyond PARAMETERS to provide additional GUI controls.
Covered previously:
S l ti T t ( h ti i t d ith PARAMETERS) Selection Texts (changes prompting associated with PARAMETERS).
More on Parameters--checkboxes
PARAMETERS can be designated AS CHECKBOX.
PARAMETERS: myvar AS CHECKBOX.
Use DEFAULT 'X' to have it toggled on initially.
PARAMETERS: myvar AS CHECKBOX DEFAULT 'X'.
Test if user selected by seeing if variable set to 'X'.
IF 'X' IF myvar = 'X'.
"code here.
ENDIF.
3/22/2011
4
More on Parameters--checkboxes
PARAMETERS: male AS CHECKBOX, female AS CHECKBOX.
IF male = 'X'.
WRITE / 'You are male!'.
ENDIF.
IF female = 'X'.
WRITE / 'You are female!'.
ENDIF.
More on Parameters--radio buttons
PARAMETERS can be designated as part of a radiobutton group.
PARAMETERS: choice1 RADIOBUTTON GROUP grpa,
choice2 RADIOBUTTON GROUP grpa,
choice3 RADIOBUTTON GROUP grpa choice3 RADIOBUTTON GROUP grpa.
Maximum group name length--4 characters
Use DEFAULT 'X' to have it toggled on initially.
PARAMETERS: choice1 RADIOBUTTON GROUP grpa DEFAULT 'X'.
Test if user selected by seeing if variable set to 'X' or use a CASE
statement.
CASE 'X' CASE 'X'.
WHEN choice1.
WHEN choice2.

ENDCASE.
3/22/2011
5
More on Parameters--radio buttons
PARAMETERS: male RADIOBUTTON GROUP gen,
female RADIOBUTTON GROUP gen.
IF male = 'X'.
WRITE / 'You are male!'.
ENDIF.
IF female = 'X'.
WRITE / 'You are female!'.
ENDIF.
PARAMETERS: male RADIOBUTTON GROUP gen,
female RADIOBUTTON GROUP gen.
CASE 'X'.
WHEN male.
WRITE / 'You are male!'.
WHEN female.
WRITE / 'You are female!'.
ENDCASE.
PARAMETERS: myvar AS CHECKBOX.
PARAMETERS: choice1 RADIOBUTTON GROUP grpa,
choice2 RADIOBUTTON GROUP grpa,
choice3 RADIOBUTTON GROUP grpa.
IF myvar = 'X'.
WRITE / 'You chose the checkbox'.
ELSE ELSE.
WRITE / 'You did not choose the checkbox'.
ENDIF.
CASE 'X'.
WHEN choice1.
WRITE / 'You picked choice1'.
WHEN choice2.
WRITE / 'You picked choice2'.
WHEN choice3.
WRITE / 'You picked choice3'.
WHEN OTHERS.
WRITE / 'You did not pick a choice!'.
ENDCASE.
3/22/2011
6
Selection Screen refinements
To exert further control over selection screen use SELECTION-SCREEN
statement.
Can add 1 or more framed blocks with optional title.
SELECTION SCREEN BEGIN OF BLOCK name WITH FRAME TITLE title SELECTION-SCREEN BEGIN OF BLOCK name WITH FRAME TITLE title.
PARAMETERS: male RADIOBUTTON GROUP gen,
female RADIOBUTTON GROUP gen.
SELECTION-SCREEN END OF BLOCK name.
CASE 'X'.
WHEN male.
WRITE / 'You are male!'.
WHEN female.
WRITE / 'You are female!'.
ENDCASE.
LOAD-OF-PROGRAM.
title = 'Choose a gender'.
Multiple items on a line
To place multiple items on a single output line, place control
definitions within a SELECTION-SCREEN BEGIN OF LINE/ SELECTION-
SCREEN END OF LINE block.
SELECTION SCREEN BEGIN OF BLOCK WITH FRAME SELECTION-SCREEN BEGIN OF BLOCK name WITH FRAME
TITLE title.
SELECTION-SCREEN BEGIN OF LINE.
PARAMETERS: var1 TYPE i,
var2 TYPE i,
var3 TYPE i.
SELECTION-SCREEN END OF LINE.
SELECTION-SCREEN END OF BLOCK name.
LOAD-OF-PROGRAM.
title = 'Enter choices'.
3/22/2011
7
Supplemental Text
COMMENT can be used to place text on the form.
Must use column and length format specifier.
SELECTION-SCREEN BEGIN OF BLOCK name WITH FRAME
TITLE title.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN COMMENT 1(40) comment.
PARAMETERS: var1 TYPE i,
var2 TYPE i,
var3 TYPE i.
SELECTION SCREEN END OF LINE SELECTION-SCREEN END OF LINE.
SELECTION-SCREEN END OF BLOCK name.
LOAD-OF-PROGRAM.
title = 'Enter choices'.
comment = 'Enter your three favorite numbers'.
SELECTION-SCREEN BEGIN OF BLOCK name WITH FRAME TITLE title.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN COMMENT 1(5) comment.
PARAMETERS: male RADIOBUTTON GROUP gen.
SELECTION-SCREEN COMMENT 12(6) comment2.
PARAMETERS: female RADIOBUTTON GROUP gen.
SELECTION-SCREEN END OF LINE. SELECTION SCREEN END OF LINE.
SELECTION-SCREEN END OF BLOCK name.
CASE 'X'.
WHEN male.
WRITE / 'You are male!'.
WHEN female.
WRITE / 'You are female!'.
ENDCASE ENDCASE.
LOAD-OF-PROGRAM.
title = 'Choose a gender'.
comment = 'Male'.
comment2 = 'Female'.
3/22/2011
8
Allowing range of values selection
Allows user to select a range of values.
SELECT-OPTIONS itabname FOR dataobject.
User entry stored in internal table itabname. 4 fields:
Sign either I or E indicating whether values specified are Signeither I or Eindicating whether values specified are
included or excluded from selection
Lowthe lower limit or a single value (if only one specified)
Highthe upper limit
Optiontext such as EQ, NE, GE, GT, LE, LT (if only Low
specified). [Other options not presented here]
Control typically used with database query operations and WHERE Control typically used with database query operations and WHERE
clause particularly adjusted to correspond with this resource.
SELECT fields FROM table WHERE value IN itabname.
(Used as a field limiter if selected, so if not populated all values
returned.)
Allowing range of values selection
DATA str TYPE spfli.
SELECT-OPTIONS userair FOR str-carrid.
SELECT carrid connid cityfrom cityto FROM spfli INTO
CORRESPONDING FIELDS OF str WHERE carrid IN userair.
WRITE: / str-carrid, str-connid, str-cityfrom,
str-cityto.
ENDSELECT.
3/22/2011
9
SELECTION-SCREEN BEGIN OF BLOCK name WITH FRAME TITLE title.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN COMMENT 1(40) comment.
PARAMETERS: var1 TYPE i,
var2 TYPE i.
SELECTION-SCREEN END OF LINE.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN COMMENT 1(40) comment2.
PARAMETERS var3 TYPE i.
SELECTION-SCREEN END OF LINE.
SELECTION-SCREEN END OF BLOCK name.
LOAD-OF-PROGRAM.
title = 'Enter choices'.
comment = 'Enter your three favorite numbers'.
comment2 = 'Put your most favorite here'.
SELECTION-SCREEN BEGIN OF BLOCK name WITH FRAME TITLE title.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN COMMENT 1(40) comment.
PARAMETERS: var1 TYPE i.
SELECTION-SCREEN COMMENT 60(1) comment3.
PARAMETERS: var2 TYPE i.
SELECTION-SCREEN END OF LINE.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN COMMENT 1(40) comment2.
PARAMETERS var3 TYPE i.
SELECTION-SCREEN END OF LINE.
SELECTION SCREEN END OF BLOCK SELECTION-SCREEN END OF BLOCK name.
LOAD-OF-PROGRAM.
title = 'Enter choices'.
comment = 'Enter your three favorite numbers'.
comment2 = 'Put your most favorite here'.
3/22/2011
10
Data Validity Testing
Validation of screen input can be done on the AT SELECTION-SCREEN
event.
Useful if want to require user data entry before main processing.
AT SELECTION SCREEN ON fieldname AT SELECTION-SCREEN ON fieldname.
Triggered if fieldname was submitted.
If an error or warning is issued, the field is highlighted.
AT SELECTION-SCREEN ON RADIOBUTTON GROUP grpnam.
If an error or warning is issued, the group is highlighted.
Data Validity Testing
SELECTION-SCREEN BEGIN OF BLOCK name WITH FRAME TITLE title.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN COMMENT 1(40) comment.
PARAMETERS: var1 TYPE i var2 TYPE i var3 TYPE i PARAMETERS: var1 TYPE i, var2 TYPE i, var3 TYPE i.
SELECTION-SCREEN END OF LINE.
SELECTION-SCREEN END OF BLOCK name.
AT SELECTION-SCREEN ON var2.
IF var2 = 7.
MESSAGE 'Sevens are bad!' TYPE 'W'.
ENDIF.
3/22/2011
11
Let's Practice
Let's Practice
3/22/2011
12
List output events
We now move from input and related events to output and a related
event.
AT LINE-SELECTION EVENT
When outputting a list, the AT LINE-SELECTION event is triggered
when a line is double clicked or the user chooses the choose icon.
SY-LSIND starts out at 0 for the initial list output and is incremented
each time the event fires It is decremented as the user moves each time the event fires. It is decremented as the user moves
BACK.
START-OF-SELECTION.
WRITE: /'hello', 'sy-lsind', sy-lsind.
AT LINE-SELECTION.
When writing in AT LINE-SELECTION, this is called a detail list and
its output appears as a new list.
WRITE: /'Now at selection level', sy-lsind.
3/22/2011
13
Retrieving values from selected line
When list is output, HIDE can be used to designate values that will be
passed on (called a data transport) when line is selected.
The data object to be hidden may or may not be a part of the output
that is displayed that is displayed.
TYPES spfli_table_type TYPE STANDARD TABLE OF spfli.
DATA itable_spfli TYPE spfli_table_type.
DATA str LIKE LINE OF itable_spfli.
DATA str2 TYPE sflight.
SELECT carrid connid airpfrom airpto deptime FROM spfli INTO
CORRESPONDING FIELDS OF TABLE itable_spfli.
LOOP AT itable_spfli INTO str.
WRITE: / str-carrid, str-connid, str-airpfrom, str-airpto,
str-deptime.
HIDE: str-carrid, str-connid.
ENDLOOP.
AT LINE-SELECTION.
IF sy-lsind = 1.
li h f i id id WRITE: 'Flights for connection', str-carrid, str-connid.
SELECT fldate seatsmax seatsocc FROM sflight INTO CORRESPONDING
FIELDS OF str2 WHERE carrid = str-carrid AND connid =
str-connid.
WRITE: / str2-fldate, str2-seatsmax, str2-seatsocc.
ENDSELECT.
ENDIF.
3/22/2011
14
Copyrights
Presentation prepared by and copyright of Dr. Tony
Pittarese, East Tennessee State University, Computer and
Information Sciences Dept. (pittares@etsu.edu)
Podcast lecture related to this presentation available via
Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries,
xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+,
POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF,
Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of
IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
Oracle is a registered trademark of Oracle Corporation.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology.
Java is a registered trademark of Sun Microsystems Inc
ETSU iTunesU.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, and other SAP products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business
Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects S.A. in the
United States and in other countries. Business Objects is an SAP company.
Other products mentioned in this presentation are trademarks of their respective owners.
3/28/2011
1
Spring 2011 Enterprise Programming
INTERMEDIATE ABAP
OBJECTS
Class Inheritance
Inheritance allows grouping of similar classes in
a general-to-specific hierarchy.
The parent class is a general representation
and contains those attributes and methods
common to the 'family.'
The child class(es) is/are a more specific
instance of the parent with added or
redefined attributes and/or methods.
Often described as a "is a" relationship.
Parent class = superclass
Child class = subclass
Parent Class
Child Classes
3/28/2011
2
Class Inheritance Example
document
-doc_number
-date
-doc_type
+get_doc_number
+set_doc_number

+display_doc
po_document
-vendor_id
-company_code
-delivery_date
+get_vendor_id
+set_vendor_id

sales_document
-customer_id
-company_code
-fulfill_by_date
+get_customer_id
+set_customer_id

Class inheritance principles
Common attributes and methods are defined in the superclass.
Items defined in the superclass are inherited in the subclass(es) and
considered to be a part of their definition.
Avoids redundant definition.
Promotes "programming by difference"subclass only defines
those things that are different.
ABAP supports only singular inheritance, so a subclass can have only
one parent superclass.

In comparing the superclass and the subclass, which is the more
specific class?
3/28/2011
3
ABAP Inheritance Syntax
In the child class, add INHERITING FROM parent to the first line of the
class definition.

The inheriting class cannot delete anything from the parent, but it can
redefine method implementations.
When redefining a method's implementation, the interface
(parameter passing) and the visibility (public, private) must
remain unchanged.
In the child class' definition the method is noted as a redefinition.
Since the interface is already defined in the parent, it is not listed
again (as it cannot be changed)
CLASS po_document DEFINITION INHERITING FROM document.
CLASS po_document DEFINITION.
METHODS display_doc REDEFINITION.
ABAP Inheritance Syntax
To call a method of the parent (such as when you want to call the
original method as part of a method's redefinition), use super->
Constructor methods have special rules.
A subclass may use the superclass constructor as it is, or the
subclass may create a new constructor with a new interface.
The subclass constructor does not use REDEFINITION.
If the subclass constructor wishes call the superclass constructor it
may do so as follows:
super->constructor ( params ).
The calling of the superclass constructor must be the first thing
done in the subclass constructor.
Given the above, the constructor is the only method in ABAP objects
that is overloaded. (Two active methods sharing the same name.)
3/28/2011
4
Let's Practice
Let's Practice
3/28/2011
5
Inherited element visibility
A private component (attribute or method) of a superclass cannot be
referenced by the subclass. These elements can only be accessed if
made available by the superclass through public methods.
This is done to ensure security of data.
Attributes and methods can be designated as PROTECTED.
PROTECTED resources are defined in the PROTECTED SECTION of a
class definition.
Protected resources are visible within the class and its children.
Similar to saying something is public to a class and its descendants,
but private to everyone else.
In the definition of an Object, the sections must appear in the order:
PUBLIC SECTION, PROTECTED SECTION, and PRIVATE SECTION.
Static elements
A class shares static attributes with its children in the same fashion as
other attributes.
A class shares static methods with its children, but those methods
cannot be redefined.
3/28/2011
6
Narrowing casts
A data object that is a reference to a superclass can be assigned a
subclass object at runtime using a narrowing cast.
The subclass contains all the methods and attributes of the
superclass so all expected elements are present.
This data object can only access the methods and attributes available
in the subclass through inheritance.
When methods are invoked, if the method has been REDEFINED,
the REDEFINED version is used.
The above is called polymorphism.
Value? Example: Create internal table based on the superclass and
children of various types can be stored. Assumption: only inherited
methods needed.
Example: method defined to take in reference to superclass data
object. Subclass data object can be used.
Widening casts
A data object that is a reference to a subclass can be assigned a
superclass object at runtime using a widening cast.
Typically used when a narrowing cast was previously used and you
wish to restore the object back to its true identity.
After the widening cast, the methods of the subclass will once
again be available.
Done using the syntax MOVE superclass ?TO subclass.
The object moved should have been created as a subclass object or
method calls on the new object will result in an error.

3/28/2011
7
Narrowing, Widening Summary
Document
Reference
P.O.
Document
Reference
Document
Object
P.O.
Document
Object
Document
Reference
=
P.O.
Document
Object
Narrowing Cast
P.O.
Document
Reference
Document
Object
=
Widening Cast
When Document Reference is used to refer
to this object, can only use methods and
attributes defined for Documents. I lose
some abilities. (Have narrower ability.)
When P.O. Document Reference is used to
refer to this object, I can use methods and
attributes defined for P.O. Documents. (Have
wider ability.) However, this is only valid if
the object I'm assigned is actually a P.O
Document formerly cast using a Narrowing
Cast.
Let's Practice
3/28/2011
8
Let's Practice
Class Builder
Just as TYPES creates local data types, so too does CLASS define local
classes. We must use the ABAP Dictionary to define classes that are
reusable across programs.
The Class Builder (SE24) is a special maintenance tool that allows the
creation of global classes within the ABAP Dictionary.
Start the Class Builder and supply the name of the class to be
created (respecting the namespace).
Specify "Usual ABAP Class". Remove "Final" as it means the Class
will not be able to be extended to subclasses.
Use Attributes tab to specify Attributes.
Use Methods tab to specify Methods.
Button for constructor and parameters
Double click to define method behavior.

3/28/2011
9
Copyrights
Microsoft, Windows, Excel, Outlook, and PowerPoint are registered trademarks of Microsoft Corporation.
IBM, DB2, DB2 Universal Database, System i, System i5, System p, System p5, System x, System z, System z10, System z9, z10, z9, iSeries, pSeries,
xSeries, zSeries, eServer, z/VM, z/OS, i5/OS, S/390, OS/390, OS/400, AS/400, S/390 Parallel Enterprise Server, PowerVM, Power Architecture, POWER6+,
POWER6, POWER5+, POWER5, POWER, OpenPower, PowerPC, BatchPipes, BladeCenter, System Storage, GPFS, HACMP, RETAIN, DB2 Connect, RACF,
Redbooks, OS/2, Parallel Sysplex, MVS/ESA, AIX, Intelligent Miner, WebSphere, Netfinity, Tivoli and Informix are trademarks or registered trademarks of
IBM Corporation.
Linux is the registered trademark of Linus Torvalds in the U.S. and other countries.
Oracle is a registered trademark of Oracle Corporation.
HTML, XML, XHTML and W3C are trademarks or registered trademarks of W3C, World Wide Web Consortium, Massachusetts Institute of Technology.
Java is a registered trademark of Sun Microsystems, Inc.
JavaScript is a registered trademark of Sun Microsystems, Inc., used under license for technology invented and implemented by Netscape.
SAP, R/3, SAP NetWeaver, Duet, PartnerEdge, ByDesign, SAP Business ByDesign, and other SAP products and services mentioned herein as well as their
respective logos are trademarks or registered trademarks of SAP AG in Germany and other countries.
Business Objects and the Business Objects logo, BusinessObjects, Crystal Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business
Objects products and services mentioned herein as well as their respective logos are trademarks or registered trademarks of Business Objects S.A. in the
United States and in other countries. Business Objects is an SAP company.
Other products mentioned in this presentation are trademarks of their respective owners.
Presentation prepared by and copyright of Dr. Tony
Pittarese, East Tennessee State University, Computer and
Information Sciences Dept. (pittares@etsu.edu)
Podcast lecture related to this presentation available via
ETSU iTunesU.

You might also like