Vous êtes sur la page 1sur 334

What Is ABAP?

ABAP stands for Advanced Business Application Programming. ABAP is a programming language that was developed by SAP for developing commercial applications in SAP environment. The development process of ABAP went through the following evolutionary stages: In early days ( !"#s$ ABAP stood for %Allgemeiner Berichts&Aufbereitungs Pro'essor( ()eneric *eport )eneration Processor$. That time ABAP was implemented as a macro assembler under *+, and e-clusively used for creating reports. In mid !.#s/ ABAP had become an interpreted language and was powerful enough to be used to create business application programs/ in particular to program dialog&controlled transactions. In early !!#s/ the SAP *+0 system was born and ABAP become ABAP+1/ that ABAP 1)2 (1th )eneration Programming 2anguage$. It now formed the technical and software basis of the entire SAP System. Apart from system core which is written in 3/ all SAP application modules/ *+0 Basis System and the development environment were now created in ABAP+1. At the end of !!#s/ ABAP is e-tended with ob4ect oriented programming constructs and from this point on/ the language was 5nown as ABAP 6b4ects. In the beginning of ,###s ABAP programs were made 7nicode&3ompatible in order to support the internationali'ation of the SAP System. 8ith SAP technology platform under the name %SAP 9et8eaver(/ ABAP become the programming interface of the SAP 9et8eaver Application Server ABAP (AS ABAP$.

What is SAP NetWeaver?


SAP 9et8eaver is SAP:s (Systems Applications and Products in ;ata Processing$ technological platform (3omponents/ Tools and Applications$ which provides a runtime and development environment for all SAP applications. SAP 9et8eaver is the fully interoperable 8eb&based cross&application platform that can be used to develop not only SAP applications but others as well. It allows a developer to integrate information and processes from geographically dispersed locations using diverse technologies/ including <icrosoft:s .9=T/ IB<:s 8ebSphere/ and Sun:s >ava technologies. SAP 9et8eaver is based on Structure 6riented Architecture (S6A$. S6A define methods for systems development and integration where systems provide functionality as interoperable services. The concept of a service/ specifically a 8eb service && is a 5ey part of the S6A. A 8eb Service is defined by the 803 as ?a software system designed to support interoperable machine&to&machine interaction over a networ5?. 2oose coupling (no service is tightly attached to a single system$/ Interoperability and Portability define the ground rules for development/ maintenance/ and usage of the S6A. =nterprise S6A (eS6A$ is the term SAP gives to its own S6A tools and technologies. SAP 9et8eaver platform comprises of the following components/ tools and applications:

Components:
Application Server: Supports platform&independent 8eb services/ business applications/ and standards&based development Business Warehouse: Integrate data from across the enterprise and transform it into information to drive sound decision ma5ing. Business Process Management: Provides tools to help you model/ e-ecute/ and monitor business processes based on a single/ consistent process model. Process Integration: ;elivers S6A&based technology that supports application& to&application (A,A$ and business&to&business (B,B$ integration/ and to accelerate composite application development. Master Data Management: =nsures cross&system data consistency and a single version of master data for supplier/ product/ customer/ or user&defined data ob4ects in heterogeneous environments. SAP NetWeaver Mobile: Provides a mobile runtime environment based on open and fle-ible technology standards and a powerful development environment for building integrated mobile solutions with native or browser&based user interfaces. SAP NetWeaver Portal: 7nifies critical information and applications to give users role&based views that span the enterprise/ enabling you to ta5e full advantage of your information resources. SAP Auto-ID In rastructure: )ives you all the capabilities you need to integrate all automated sensing devices @ including *AI; (*adio AreBuency Identification$ technology electronically captures/ stores/ and transmits data readers and printers/ Bluetooth devices/ embedded systems/ and bar&code devices. I!entit" Management: Celps companies manage users: access to applications securely and efficiently/ while meeting audit and compliance reBuirements. In ormation #i ec"cle Management: =nables companies to decommission redundant SAP system while preserving full auditing and reporting capabilities for stored data.

$ools:
A!aptive Computing Controller: Provides a central point of control for assigning computing resources and optimi'ing their use.

Composition %nvironment: Provides a robust environment for design/ deployment/ and running of composite applications that comply with a service& oriented architecture. Developer Stu!io: 6ffers a convenient user interface and rich functionality for developing >,== applications. &isual Composer: Allows composing model&based business applications in a fle-ible way/ without manual coding. SAP Solution Manager: Application management solution facilitates technical support for distributed systems.

Applications
%nterprise Search: Celps business users navigate critical business information by enabling seamless/ secure access to SAP and non&SAP information and processes. Duet: =nables seamless access to SAP business processes and data via <icrosoft 6ffice. Allo": Simplifies interaction with people/ processes/ and information by providing intuitive access to SAP software and information via the familiar IB< 2otus 9otes. SAP Central Process Sche!uling application b" 'e!(oo!s: Celps companies manage/ monitor/ and e-ecute business&critical processes from a central location by delivering adaptive/ real&time/ event&driven 4ob scheduling and process& automation capabilities across distributed and heterogeneous platforms. %nterprise Mo!eling Applications b" IDS Scheer: ;eliver 8eb&based components that support the process life cycle for business process design/ analysis/ optimi'ation/ and implementation.

Another (a" o !e ining SAP NetWeaver)


SAP 9et8eaver is a set of capabilities that are provided by different SAP products constructed to wor5 with each other to ma5e applications wor5 together/ build new applications on top of e-isting applications and lower the Total 3ost of 6wnership (T36$. T36 is about all the different e-penses involved in owning and running an enterprise application.

The figure above depicts that the core capabilities of SAP 9et8eaver are consists of the following four layers: People Integration Information Integration Process Integration Application Platform

People Integration
People Integration means to bring people together and help them wor5 more efficiently. Information Integration means to bring information from different locations and have it ma5e sense in the conte-t what a user do everyday.

Process Integration
Processes Integration means coordinating the flow of wor5 across departments/ divisions and between companies.

Application Plat orm


Application Platform is called the SAP Application Server (SAP AS$. SAP AS is foundation for the entire SAP software stac5. It is the engine behind the scene of SAP 9et8eaver that drives all SAPEs Applications and Tools. It provides a platform for 9et8eaver components (=nterprise Portal etc.$ and ABAP and >ava applications.

Composite Application *rame(or+


3omposite Application Aramewor5 (SAP 3AA$ is modeling and development environment for creating composite applications. 3omposite applications are applications built out of services provided by other applications.

#i e C"cle Management
The SAP 2ifecycle <anagement (SAP 2<$ offers all the functionality needed for integrated product and asset management li5e Program and pro4ect management and Fuality management.

SAP Application Server


SAP Application Server (SAP AS$ is foundation for the entire SAP software stac5. It is the engine behind the scene of SAP 9et8eaver that drives all SAPEs Applications and Tools. It provides a platform for 9et8eaver components (=nterprise Portal etc$. SAP systems are used for mapping business processes or business applications. These applications should be implemented independent of the hardware environment used (operating system/ database$ to the greatest e-tent possible. Aor this/ the SAP Application Server provides two runtime environments: the ABAP runtime environment (AS ABAP$ and a >ava runtime environment (AS >AHA$. Both application servers wor5 on different data (different database schemas$ and are lin5ed together by allowing mutual access through the >ava 3onnector (>3o$.

Application Server ABAP


The Application Server ABAP provides the ABAP runtime environment that is a virtual machine for ABAP programs independent of the hardware/ operating system and data base system. Aigure below shows a simplified overview of the main AS ABAP components.

AS ABAP can be used by user or by software/ including the remaining components of SAP 9et8eaver. 7ser can access it using user interfaces that are available in the form of "

web browser or SAP )7Is installed on des5top P3s. Software components generally access it through the networ5/ for which two protocols are used: CTTP+CTTPS+S<TP for Internet connections and SAPEs own *emote Aunction 3all (*A3$ protocol for calling ABAP functionality through any e-ternal clients. The components of AS ABAP can be divided according to their tas5s into three layers of a client&server system: Presentation 2ayer Application 2ayer Persistence 2ayer

Presentation #a"er
The components of the presentation layer are responsible for the presentation of data to users and the receiving of user entries. 7ser interfaces for AS ABAP include commercial web browsers and SAPEs SAP )7I. 8hen web browsers are used in application programs/ CT<2 pages prepared in the presentation layer are accessed. Application program access these CT2<2 pages through the Internet 3onnection Aramewor5 (I3A$. The I3A uses standard protocols (CTTP/ CTTPS/ and S<TP$ to operate communications between systems through the Internet. Presentation in a web browser is based on 8eb ;ynpro and Business Server Pages (BSP$. SAP )7I is the graphical user interface that runs on a <icrosoft 8indows/ Apple <acintosh or 79II des5top. The 3ontrol Aramewor5 (3A8$ supports controls (ActiveI and >avaBeans$ that are implemented within the SAP )7I/ depending on the version of SAP )7I currently in use. The presentation in the SAP )7I is based on the classical dynpro technology. Web Dynpro ABAP 8eb ;ynpro for ABAP (8;1A/ 8;A$ is the SAP standard 7I technology for developing 8eb applications in the ABAP environment. It consists of a runtime environment and a graphical development environment with special 8eb ;ynpro tools that are integrated in the ABAP 8or5bench. 8eb ;ynpro is based on <odel Hiew 3ontroller (<H3$. <H3 is an architectural pattern used in software engineering. The pattern isolates business logic from input and presentation/ permitting independent development/ testing and maintenance of each. Business Server Pages Business Server Pages (BSP$ can incorporate server&side scripts written directly in ABAP or >ava Script. It enables direct access to all elements in the application server (such as

function modules/ database tables/ ABAP 6b4ects/ and so on.$. BSP is similar to >ava Server Page (>SP$ as it is coded in CT<2 of AS ABAP Internet applications. BSPs represent the predecessor technology of 8eb ;ynpro ABAP. BSP also supports <H3/ but is not a prereBuisite. Dynpro ;ynamic program (;ynpro$ defines a user interface of an ABAP program in a window of the SAP )7I. =ach dynpro is a component of an ABAP program. The screen of a dynpro can contain a set of predefined screen elements or )7I controls. In addition to screen/ a dynpro also contains a screen processing logic written in a separate programming language that is called dialog modules in ABAP program. 7ser interfaces of new applications should be designed primarily with 8eb ;ynpro ABAP/ even if it is not initially intended to use the system via the Internet. The IC* and C*W provide services between the application program and presentation layer.

Application #a"er
The application layer is the software layer in which application programs are e-ecuted. The application layer contains a 5ernel written primarily in 3+3JJ that servers as a platform for application programs which is independent from hardware/ operating system and database. The 5ernel provides processors (virtual machines$ for the following programming languages: ,S#$ an! S$ IS2T (eItensible Stylesheet 2anguage Transformation$ allows I<2 formats to be converted into any other I<2 format. Simple Transformation (ST$ is an SAP&specific language used to transform ABAP data to I<2 and vice versa. The IS2T and ST processors e-ecute IS2T and ST programs. These programs are edited with Transformation =ditor of the ABAP 8or5bench. ABAP an! ABAP -b.ects ABAP and ABAP 6b4ects (66 enhancement to ABAP$ is the programming interface of AS ABAP for business management applications. The corresponding ABAP processor accounts for the largest part of the AS ABAP 5ernel. ABAP programs are created with the ABAP =ditor/ which can be used either as an independent application or as an add&on to other tools such as 6b4ect 9avigator or 3lass Builder.

/ava Script >avaScript programs are e-ecuted by >avaScript processor. Hariables of the script can be lin5ed to data ob4ects of an ABAP program. 7se of >avaScript on AS ABAP has negligible significance. There is no dedicated editor for >avaScript programs in the ABAP 8or5benchK the CL_JAVA_SCRIPT system class provides an interface to the >avaScript =ngine. -b.ect Services 6b4ect Services provide global services/ which ABAP 6b4ects language elements cannot provide themselves/ to applications written in ABAP 6b4ects. These 6b4ect Services include: A Persistence Service/ A Transaction Service/ and A Fuery Service.

Persistence #a"er
The persistence layer is the software layer in which persistence data is held in a database. =ach AS ABAP accesses a central database on which its entire dataset is stored. This means that not only the application types/ but also all administrative data/ customi'ing settings and ABAP source codes. The central database can be accessed by ABAP programs through the !atabase inter ace of AS ABAP. This interface ma5es AS ABAP independent from the database system that is actually used. The database interface is subdivided into an 6pen SF2 interface and SF2 interface. -pen S0# is a sunset of SF2 reali'ed by ABAP statements and includes the ;ata <anipulation 2anguage (;<2$ portion. The statements of 6pen SF2 access the AS ABAP database through the 6pen SF2 interface/ irrespective of the platform. The 6pen SF2 interface converts the 6pen SF2 statements into manufacturer specific SF2 and passes it onto the ;B<S. 8ith 6pen SF2 you can read (SELECT$ and change (INSERT, UPDATE, MODIFY, DELETE$ data in database tables that are defined in the ABAP ;ictionary. 6nly the statements from 6pen SF2 should be used in application programs. Native S0# interface passes on the manufacturer&specific SF2 statements/ unchanged to the ;B<S. 9ative SF2 refers to statements that can be e-ecuted in ABAP programs between EXEC SQL and ENDEXEC statements.

Communication Components
3ommunication components are position somewhat aside from the three layers: Inter Communication Manager

Internet 3ommunication <anager (I3<$ is a process in ABAP 5ernel that allows it to communicate directly with the Internet via CTTP+CTTPS+S<TP. I3< allows connection to web based presentation components such as 8eb ;ynpro ABAP and BSP. It also enables and AS ABAP to act both as a client and as a server for 8eb Services. ABAP program access the I3< through the classes and interfaces of the Internet 3ommunication Aramewor5 (I3A$. 'emote *unction Call Inter ace *emote Aunction 3all (*A3$ is an invocation of a function that is located in a different system than the one in which the calling program is running. 3alls are possible between different AS ABAPs/ or between an AS ABAP and e-ternal system.

AS ABAP Processes
The SAP runtime system consists of a number of parallel processes that wor5 together. The following graphic illustrates the most important processes of application server ABAP.

AS ABAP Processes In addition to several wor5 processes whose number and type are determined at the startup of AS ABAP/ each ABAP application server contains a dispatcher/ a gateway/ I3< and a message server. Dispatcher The dispatcher is the lin5 between the wor5 processes and the users logged onto the ABAP application server (that is/ the SAP )7Is of the users$. Its tas5 is to receive reBuests from the SAP )7I and direct them to a free wor5 process. In the same way/ it directs screen output bac5 to the appropriate user. If all the wor5 processes are occupied the reBuests are stored in the dispatcher Bueue. Wor+ Processes 8or5 processes are software components that e-ecute an application. =ach wor5 process is lin5ed to a memory area containing the conte-t of the application being run. The conte-t contains the current data for the application program. There are the following types of wor5 process: ,

Dialog: Aulfill all reBuests for the e-ecution of dialog steps triggered by an active user. =very dispatcher reBuires at least two dialog wor5 processes. Update: =-ecute update reBuests. At least one update wor5 process per SAP system and you can have more than one per dispatcher. Background (batch): =-ecute programs that run without interacting with the user. Lou need at least two bac5ground wor5 processes for each SAP system. Lou can configure more than one bac5ground wor5 process for each dispatcher. Enqueue: Administers the loc5 table in the shared memory. The loc5 table contains the logical database loc5s of the ABAP stac5 of the SAP system. 6nly one enBueue wor5 process is needed for each system. Spool: Pass seBuential data flows on to printers. =very SAP system reBuires at least one spool wor5 processK you can also have more than one spool wor5 process per dispatcher.

Internet Communication Manager The Internet 3ommunication <anager (I3<$ enables SAP systems to communicate directly with the Internet. The I3< receives reBuests from the Internet and forwards them to the SAP system for processing. It can also direct CTTP reBuests from an SAP system to a 8eb server and send the response bac5 to the SAP system. Lou can configure a ma-imum of one I3< process per application server. <emory Pipes are memory&based communication ob4ects that are used to transfer data between the I3< and the wor5 processes. Message Server The message server (<S$ handles the communication between the distributed dispatchers within the ABAP stac5 of an SAP system/ thereby enabling scalability of several parallel application servers. The message server is configured only once per SAP system. 1ate(a" The gateway ()8$ enables communication through *A3 interface between SAP systems/ or between SAP systems and e-ternal application systems. There is one per dispatcher.

Memor" -rgani2ation o AS ABAP


AS ABAP is the system in which an ABAP programs runs. Arom software point of view/ the application layer of an AS ABAP is spread across at least one/ but usually several/ application servers. If an AS ABAP has several application servers/ they are usually also installed on several machines/ whose operating systems donEt have to be identical. ThereforeK in application layer there is <essage Server (<S$ that is responsible for communication between the application servers. =ach application server provides a range of services of operating the AS ABAP. The services of an application server are implemented by wor5 processes/ whose number and types are set when the AS ABAP is started. 8or5 processes are software components that can e-ecute an application. There are different types of wor5 processes for different applications: dialog/ enBueue/ bac5ground/ spool and update wor5 processes. 8or5 process is logged on as a user to the database system for the entire runtime of an AS ABAP. ;uring the ASP ABAP runtime/ a database logon canEt be passed on from one wor5 process to another. SAP <emory <anagement is used for memory areas of an application server. Aigure below shows where an ABAP program runs on an application server and what memory areas it can access here.

AS Memor" -rgani2ation The memory areas of an application server that can be accessed in an ABAP program are as follows: Shared <emory SAP <emory ABAP <emory *oll Area

Share! Memor"
=ach application server has its own shared memory. The shared memory is the memory area that is used by all parts of an application server together. The ABAP runtime environment uses the shared memory for programs/ program data and buffering (from database in data dictionary in a table buffer$. ABAP programs can access shared ob4ects and data clusters in the shared memory.

SAP Memor"
8hen a dialog user or an e-ternal client (via *A3 or I3A$ logs on to an AS ABAP/ it is connected to an appropriate application server and opens a user session on this AS. =ach user session is assigned its own memory area/ the SAP <emory/ in which all ABAP programs of a user session have 4oint access to SPA+)PA parameter (7sed to fill the input fields of a called transaction with data from the calling program$. The corresponding statements are SET PARAMETER and GET PARAMETER. These parameters are only suited to saving short character&type fields/ such as the name of the last programs called. The input fields of dynpros can be lin5ed to SPA+)PA parameters and in order to pre&fill them before a dynpros is called.

ABAP Memor"
At least one main session or e-ternal mode is opened for each user session. In dialog processing/ a user session can manage up to G main sessions/ each of which is lin5ed to separate window. If you e-ecute the function 3reate 9ew Session in the SAP )7I/ or enter a transaction code behind +o in the input window of standard toolbar/ you open a new main session in a new window. Arom an ABAP program a new main session can be open via *A3 (CALL FUNCTION STARTING NEW TASK$. =ach main session is assigned a separate memory area/ 5nown as the ABAP <emory/ in which data clusters can be stored. The data in the ABAP memory is retained during a seBuence of program calls within a call seBuence.

A call seBuence is formed if you can return from called program to the calling program. This is always the case when you call an ABAP program with SUBMIT AND RETURN or CALL TRANSACTION. 6nly programs of a call seBuence have common access to data in the ABAP memory/ and this is primarily for data transfer during program calls. 8hen the first program of a call seBuence is terminated/ the corresponding ABAP memory is also released.

'oll Area
8ith each call via SUBMIT or CALL TRANSACTION or LEAVE TRANSACTION of an ABAP program in main session/ an internal session is opened. A memory area called a *oll Area is assigned to the internal session/ in which the data and ob4ects of an ABAP program are stored while it is e-ecuted. This is the actual memory of an ABAP Program. 8ith program calls/ a ma-imum of nine internal sessions can be stac5ed as a call seBuence in a main session. In main session/ only the internal session of the program that is 4ust running e-ists in am active version. All memory content of previous programs is saved on the stac5. Technically each internal session is divided into a Program =-ecution Area (PIA$ and a *oll Area. The PIA is further common memory area of the application server in which the unchangeable data (bytecodes$ of t he programs that are currently running there is stored. 6nly the roll area is individually reserved for an internal session and contains its changeable data. An internal session will e-ist for as long as its first program/ the main program/ is e-ecuted. The additional loaded programs and their data also remain loaded until the end of the internal session. All programs of an internal session have 4oint access to anonymous data ob4ects and instances of classes created with CREATE. 8ithin internal session/ references to ob4ects can be copied from one program to procedures of another program. 6n G1&bit platform/ an internal session can theoretically reBuire up to 1TB of memory. 6n 0,&bit platforms/ the theoretical ma-imum limit is 1)B.

ABAP3 A Practical Intro!uction


Change an! $ransport S"stem 4C$S5
The SAP 9et8eaver repository is the central place where development components in the ABAP 8or5bench are stored. These components include all of the: process models/ data models/ business ob4ect models/ business ob4ects/ and all data and their relationships. The repository also includes the ABAP ;ictionary. The 3TS is the central tool for managing changes to repository ob4ects that you ma5e in the ABAP 8or5bench. The 3TS records all changes in transport+change reBuests. 8hen you have finished your wor5 in ABAP 8or5bench/ or have reached a certain stage/ you can release the reBuest. The change reBuest is then used to copy the changes from this client to other clients or systems. This automatic procedure is 5nown as a transport. Transports of changes by the 3TS allow you to develop in one environment/ test your development wor5 in a test environment/ and then/ if the tests are successful/ use it productively. This ma5es sure that productive operations are not placed at ris5 by faulty settings or program errors. 3TS enable you to define transport layer as an attribute of a pac5age. The transport layer refers to the transport path a pac5age should ta5e in a system landscape. The usual landscape has a least three layers:

The transport layer by itself does not transport anything. Lou need a transport+change reBuest to get something transported. A change reBuest can be created in two ways:

"

. 8hen you create or modify ob4ects in the ABAP 8or5bench/ a window appears as5ing you to assign the ob4ect to an e-isting change reBuest (6wn reBuests$ or to create a new change reBuest (3reate reBuest$. See Pac5age 3reation Topic. ,. Through Transport 6rgani'er (S=#!$. Creating a 'e6uest in the $ransport -rgani2er: . To start application server/ follow the path Start &M Programs &M SAP 9etweaver ".# ABAP Trial Hersion &M 9SP &M Start Application Server.Select 3reate (AG$ to create new transport reBuest.

,. 2og on as a B37S=*.

0. =nter S=#! transaction code in the te-t field of standard toolbar to open the Transport 6rgani'er.

1. Select the 3reate (AG$ function from the toolbar of Transport 6rgani'er to create new transport reBuest.

D. Select 8or5bench reBuest and clic5 continue. G. 3reate *eBuest dialog will appear/ enter short description of the change reBuest. And 3lic5 Save.

". This will open up the ;isplay *eBuest 8indow/ where you can see the change reBuest in hierarchal order. Lou can use it now during ob4ect creations.

,#

Pac+ages
Pac5ages are used to organi'e development ob4ects (programs/ tables/ screens/ BAPIs/ function modules/ types/ and so on$ and handle their connection to the ABAP software logistics (3hange and Transport System$. All ob4ects that can be changed using ABAP 8or5bench (*epository 6b4ects$ are part of pac5age. =very AS ABAP contains a predefined pac5age named NT<P. NT<P pac5age is used for local practice and test programs. =very pac5age starting with N character is considered local and canEt be transported to other SAP system. Pac5ages help developers to modularize/ encapsulate/ and decouple units in the SAP System. Pac5ages may have the following attributes: Nesting: allows to embed pac5ages in other pac5ages. 8ith nesting you can split up larger units of the SAP System and structure them in a hierarchy. &isibilit": is a property of pac5age elements. Arom the outside/ a pac5age loo5s li5e a ?blac5 bo-.? They are always visible to other elements in the same pac5age and always invisible to embedded (sub&$pac5ages within their pac5age. Aor an element to be visible outside the pac5age/ it must be contained in at least one pac5age interface. 7se access: is the right of one pac5age to use the visible elements in the interface of a second pac5age (but not the other way round$.

8hen we create a pac5age/ we specify the following properties: Pac5age: The name of the pac5age to be created. The name should follow the customer namespace conventions. ;escription: To define the pac5age. Application 3omponent: ;etermine the location of the pac5age within the application hierarchy by specifying the corresponding application component. Software 3omponent: The software component describes a set of development ob4ects that can only be delivered in a single unit. Aor customer developments you should enter C6<= as the software component. Transport 2ayer: The transport layer determines if the ob4ects of this pac5age are to be transported to a subseBuent system and/ if so/ to which system. Pac5age Type: Lou can choose between three pac5age types: o Standard pac5age + 9ot a main Pac5age (3an contain *epository ob4ects and other pac5ages$ o <ain pac5age (3an only contain other pac5ages$ o Structure pac5age (3an only contain main pac5ages$

Note: Values like pplication ! So"t#are component is de$eloped b% s%stem administrator #hen s%stem is created&

Creating Package
Pac5age can be created in two ways: a$ In the navigation area of 6b4ect 9avigator (S=.#$/ choose the ob4ect type Pac5age from the ob4ect list and enter the name of the pac5age in the input field below. 3hoose =nter. If the specified pac5age does not already e-ist/ the system branches to a dialog for creating a pac5age. b$ 3all the pac5age builder (S=, or SPA3OA)=$. =nter Pac5age 9ame and push 3reate button.

. =nter the following properties in 3reate Pac5age dialog. a$ Pac5age: PQ<yPac5age b$ ;escription: <y Training and ;emo Programs c$ Application 3omponent: 3A (Press A1 for selection and A for detail help$. d$ Software 3omponent: Come (Press A1 for selection and A for detail help$. e$ Transport 2ayer: P9SP (Aor our demo system you should use the transport layer P9SP$. f$ Pac5age Type: 9ot a main Pac5age (since <ain Pac5age canEt directly contain development ob4ects$.

,,

,. After selecting Save you will be prompted for a transport reBuest.

0. If you have already created transport reBuest/ push 6wn *eBuests button or select the 3reate button to create new one. 1. In new create reBuest dialog enter short description.

Note: 'n a real(#orld de$elopment pro)ect %ou #ill al#a%s use a transport request that is created in the *ransport +rganizer (SE,-) and paste this into the dialog #ith ,0

the header .rompt "or transportable /orkbench 0equest1 i" %ou )ust need a transport request #ithout an% particular properties1 %ou can do it the #a% #e do it here& D. Pressing the Save button opens another dialog window and we are done with transport reBuest.

G. 3lic5ing 3ontinue will bring Pac5age Builder: 3hange Pac5age 8indow. 3hec5 the Pac5age 3hec5 as Server. This ensures that only ob4ects declared in the pac5age interface of the pac5age can be addressed from other transportable pac5ages. 3lic5 Save button on standard toolbar and close the Pac5age Builder.

,1

Creating 8ello Worl! Program in Pac+age


. =nter S=.# in te-t field of standard toolbar to open 6b4ect 9avigator. ,. Select Pac5age from 6b4ect 2ist and type PQ<yPac5age into te-t field below and press return 5ey. Lou will see that our pac5age is now visible in the *epository Browser.

0. *ight&clic5 on the pac5age PQ<yPac5age and choose 3reate @ Program. 1. =nter the name of the program we want to create PQAQC8. ;eselect %8ith T6P I932( (Top Include$ because we do not need a top include and confirm.

D. 9e-t dialog shows the properties of the new program. 6ne of the most important program properties of an ABAP program is its type. Arom the list provided/ we want to select the type ?=-ecutable program? for our simple Cello&8orld program/ and change or add no other properties. In particular/ ensure that the properties ?7nicode chec5s active? (strict static type chec5s/ separation of byte and character string processing$ and ?Ai-ed point arithmetic? (for decimal numbers the decimal separator is ta5en into account in calculations$ should always be chec5ed. 2ogical ;atabases option is no more used in ABAP 6b4ects. Press Save button.

,D

G. 3reate 6b4ect ;irectory =ntry dialog appears/ clic5 save to continue. The 6b4ect ;irectory is a directory of all the *epository 6b4ects that ma5e up the SAP System. 8hen you create an ob4ect/ the corresponding ob4ect directory entry is also created.

". 9e-t dialog prompt for transport reBuest. The transport reBuest our pac5age belongs to is already in the relevant field. Again 3onfirm it.

,G

.. 9e-t the ABAP =ditor is appear/ where you write code. 3lic5 Les if you wanted to chec5 the Buic5 start.

!. To configure the new ABAP =ditor go to 7tilities Settings Aront&=nd =ditor (9ew$.

#. Lou can also double clic5 the program name to open ABAP =ditor.Lou can see the framewor5 predefined by the ABAP 8or5bench. This synta- consists of a few lines of comments/ and also contains an initial statement named *eport.

,"

. To change the program. )o to the change mode by pressing the respective button: Below the report&statement enter:

,. To format the source code. ABAP =ditor uses the Pretty Painter. To configure it go to 7tilities Settings Pretty Painter. 3hec5 Indent and 3onvert 7ppercase +2owercase.

0. 3lic5 the Pretty Painter button in the ABAP =ditor and the format of statements changes.

,.

1. To chec5 the syntactic corrections/ select 3hec5 from the conte-t menu of the program name in ob4ect list. 6r 3hec5 button from standard toolbar. D. The error&free program must be activated. Select Activate function . ;uring The error&free source code is converted to byte code that is stored in the database. After activation program will be visible to every user using System Services *eporting. G. To run the program we press the icon: of program name or by pressing A.. or =-ecute ;irect from conte-t menu

". The e-pected %Cello 8orld( output appears in a special screen.

9ote: ABAP Programs can be e-ecuted by two ways. 7sing the =-ecute function or transaction codes (SA0. and S=0.$. SA0. can be used only to e-ecute or run a program. It is more recommended to use by Aunctional 3onsultants+7sers of the program to reduce the ris5 of mista5enly modification or deletion of the program. S=0. is use to display an ABAP =ditor screen where transaction is not limited only to program e-ecution but also to display or modify the program code. SA0. can be used also by ABAPers to e-ecute the program. Also to call the program from other program the use the S7B<IT R.

,!

statement. 8ith addition A9; *=T7*9 specify the system returns to the caller after the called program is terminated.

SA9: Call

S%9: Call ABAP programs can also be called through transaction codes (transaction maintenance S=!0$. To call transactions from other program use the statement 3A22 T*A9SA3TI69 R. and to abort the calling transaction use 2=AH= T*A9SA3TI69. .. To display the %Cello 8orld% is message bo- change the code to:

0#

As a result a dialog window greets the world. Instead of EIE try =/ I for type message.

-utput (ith $"pe ;I<

-utput (ith $"pe ;%<= message (ill be sho(n in status bar

Dissecting the Hello World Program


ABAP program consists of statements. Statements are composed of to5ens and terminated by Period (.$. To5ens must be separated by at least one space. Possible to5ens include Oeywords/ 6perands/ 6perators and Special 3haracters. In our e-ample *=P6*T is the 5eyword and PAC8P is the operand. ABAP 5eyword determines the category of the statement. (e.g. <odulari'ation/ 3ontrol/ 3all and 6perational Statements$.

=very standalone ABAP program/ that is/ all types of programs e-cept for so&called include programs/ start with an introductory statement. In our first program/ the introductory statement is *=P6*T. The *=P6*T 5eyword e-presses the fact that historically e-ecutable program was once e-clusively used for reporting. After the introductory statement/ every ABAP program follows a fi-ed program structure that divides it into two parts: a$ )lobal ;eclaration part b$ Procedural part )lobal declaration part directly follows the introductory statement. ;eclarative statements can be used for definitions and declarations/ which will be visible and applicable throughout the entire ABAP program. =-amples of ob4ects that can be declared or defined here are data types/ classes/ interfaces/ data ob4ects and screens. Aor larger programs/ these declarations are generally made in a special include program/ the ?top include/? which is supported by the ABAP 8or5bench and inserted at this position. The ;ATA statement declares a data ob4ect msg of type string and initiali'es it to a start value %Cello 8orld%. After the global declaration part comes the procedural also 5nown as implementation part/ in which the actual processing logic of the ABAP program is implemented. The implementation part is divided into individual procedural units that are referred to as Processing Bloc5s. =very ABAP statement that is not part of global declaration part always belongs to e-actly one processing bloc5. Statements within processing bloc5 are processed seBuentially. The arrangement of processing bloc5s in the implementation part is not significant for program e-ecution. The order in which processing bloc5s are e-ecuted is controlled by calls (from other processing bloc5$ or by the ABAP runtime environment. =ach time a program is e-ecuted/ at least one processing bloc5 is called by the runtime environment as a point of entry/ which/ in turn/ can call additional processing bloc5s of same or other program. 8hen first processing bloc5 of a program is called/ the entire program is loaded into the memory. 8hen the last processing bloc5 is terminated/ control is returned to the calling program or runtime environment. Processing bloc5s canEt be nested. To 5eep the program readable/ select a semantically relevant program structure and ma5e the structure visible using comment lines. The following types of processing bloc5s are available. Procedures (methods/ subroutines and function modules with their own local data area$ ;ialog modules (processing bloc5s without local data$ =vent bloc5s (handle events of processes in the ABAP runtime environment$

0,

STA*T&6A&S=2=3TI69 statement introduces a processing bloc5 which plays the same role in e-ecutable programs as the main method in >ava program. That is/ when program is e-ecuted/ the implementation of the bloc5 is automatically called. The 8*IT= statement outputs a list and it is driven by the classic SAP ;ynpro technology which should not be used to applications with state&of&the&art user interface. Lou should use ;ynpro&based 7Is only in test&programs if you want to output (or input$ some values in a Buic5 and dirty way. Lou can compare the write&statement to the output to the console in >ava. 3omment lines are introduced by an asteris5 S in the first position. To mar5 only the final portion of a line as a comment/ you can use the character %.

-b.ect -riente! &ersion o >8ello Worl!? Program


. Select 3reate 3lass 2ibrary 3lass from the conte-t menu of PQ<yPac5age in the *epository Browser. It will pop up the 3reate 3lass dialog.

,. Set the following fields in 3reate 3lass dialog. 9ame: PQ32QC8 3lass Type: 7sual ABAP 3lass Brief ;escription: <y hello world class Instantiation: Public Ainal: 3hec5 (<eans that this class canEt be inherited$

00

0. Press Save button and you will be presented with 3reate 6b4ect ;irectory =ntry dialog/ clic5 save to continue.

1. 9e-t dialog prompt for transport reBuest. The transport reBuest our pac5age belongs to is already in the relevant field. Again 3onfirm it.

D. In the 3lass Builder/ select the Attributes tab to define attribute for a class. An attribute is a data ob4ect declared within the class. =nter the following values in respective columns. Attribute: msg 2evel: Instance Attribute Hisibility: Private Typing: Type Associated Type: string

01

G. 9e-t to define the method/ clic5 on <ethods tab. To define constructor push 3onstructor (AD$ button in class builder. To declare method/ enter the following in respective columns write after the 369ST*73T6*. <ethod: printQhello 2evel: Instance Hisibility: Public ;escription: This method will print hello world message

". To implement the methods clic5 the Source 3ode function

.. Type the following statement in constructor. <a5e sure that the cconstructor is selected in the list. To switch between the class builder and editor select previous button and ne-t button .

!. 9e-t type the following statement in printQhello method.

#. This concludes the definition of class in class library so chec5 and activate the class. The dialog displays pending inactive ob4ects. 3lic5 3ontinue to activate.

0D

. To consume this class/ letEs create the program of type Subroutine pool. Note: Subroutine pool is a t%pe o" B . program1 #here local classes are created and their public methods are connected to transaction codes& ,. *ight&clic5 on the pac5age PQ<yPac5age and choose 3reate @ Program. 0. =nter the name of the program we want to create PQ66QC8. ;eselect %8ith T6P I932% (Top Include$ because we do not need a top include and confirm. 1. 9e-t dialog shows the properties of the new program. Arom the type list select the type ?Subroutine Pool? change or add no other properties. In particular/ ensure that the properties ?7nicode chec5s active? and ?Ai-ed point arithmetic? should always be chec5ed. Press Save button.

0G

D. 3reate 6b4ect ;irectory =ntry dialog appears/ clic5 save to continue. G. 9e-t dialog prompt for transport reBuest. The transport reBuest our pac5age belongs to is already in the relevant field. Again 3onfirm it. ". This will open the ABAP =ditor/ enter the following listing.

0"

.. 9ow if you activate and =-ecute (A.$ the program. It wonEt wor5/ because subroutine pool has no pre&defined starting point li5e STA*T&6A&S=2=3TI69 for e-ecutable programs. To solve this problem we have to define the transaction code. 9ote: Transaction li5e the name %report% for e-ecutable program/ is historical in nature and the reason for this conte-t is e-plained by the fact that a classical ABAP application program generally e-ecuted a business transaction on the database table. Aor us the transaction means the e-ecution of an ABAP program via %Transaction 3ode%. It is a twenty&character name which is assigned to a screen or a method of an ABAP program and is used for program e-ecution. !. Select 3reate other( $ Transaction from the conte-t menu of our pac5age in the repository browser and fill the dialog window that appears. Transaction 3ode: PQC8 Short Te-t: Cello 8orld Start 6b4ect: <ethod of a class and Select 3ontinue.

0.

,#. 6n ne-t screen maintain 66 transaction. 66 Transaction <odel: 7nchec5 (to fill the input fields$ 3lass 9ame: 'QclQclient <ethod: main 2ocal in Program: 3hec5 2ocal in Program: PQ66QC8

, . 3lic5 Save on standard toolbar. ,,. 3reate 6b4ect ;irectory =ntry dialog appears/ clic5 save to continue.

0!

,0. 9e-t dialog prompt for transport reBuest. The transport reBuest our pac5age belongs to is already in the relevant field. Again 3onfirm it. ,1. To run/ enter the ToPQC8 in the input field of the standard toolbar. +o runs the program in new window/ in contrast to +n.

Dissecting the OO Hello World Program


The declaration part contains the declaration of local class 'QclQclient. The public section show defines the public visibility of the static method main which is defined with 32ASS&<=TC6; statement. The implementation part of local class must implement between 32ASS...... I<P2=<=9TATI69 and =9;32ASS. Between <=TC6; ... and =9;<=TC6; we provide the implementation for method. The main method is a user for our global class. The *=A T6 means that ob4 is a reference variable which is pointing to 'QclQclient reference type or class. The 3*=AT= 6B>=3T creates the ob4 ob4ect. The selector &M is used for accessing an instance public component.

1#

ABAP Program $"pes


7nli5e >ava where programs are simply containers for classes/ there are different ABAP programs types that play different roles on the application server ABAP. The program type defines the basic technical attributes of a program/ that is/ which processing bloc5s a program may contain how the program is handled and e-ecuted by the ABAP runtime environment/ and whether it can wor5 with its own screens (Also 5nown as dynpros$ are the most general type of user dialog in SAP applications before 9et8eaver. Lou do not define them in ABAP programs/ but instead in the Screen Painter.$. 8hen you run an ABAP application program/ you must call at least the first processing bloc5 from outside the program/ that is/ from the runtime environment. This processing bloc5 can then either call further processing bloc5s or return control to the runtime environment. 8hen you start an ABAP program/ the runtime environment starts a processor (dependent on the program type$/ which calls the first ABAP processing bloc5. The program can be started either by the user or by the system (for e-ample/ in bac5ground processing$/ or through an e-ternal interface/ for e-ample/ for *emote Aunction 3alls (*A3$. There are seven program types from which you can choose: e-ecutable program/ module pool/ function group/ class pool/ interface pool/ subroutine pool/ and include program.

Class Pools @ 1lobal Class


3lass pool is a container for e-actly one global class and more than one data types and local ob4ect types (local classes and interfaces$. All the reusable code is programmed here. A class pool is loaded into memory by using the global class/ for e-ample/ a public method of global class can be called from another ABAP program or it can be lin5ed with a transaction code. They are declared with the CLASS-POOL statement but as it is created with 3lass Builder (S=,1$ of ABAP 8or5bench/ which means it is generally not displayed as a single continues source code.

Inter ace Pools @ 1lobal Inter ace


Interface pool is a container for e-actly one global interface. The global interface can be implemented in any global or local classes. They are introduced with the INTERFACEPOOL statement. Interface pool is created in 3lass Builder (S=,1$ of the ABAP 8or5bench.

*unction 1roups @ *unction Pools


Aunction group contains a procedures (Aunction <odules$ processing bloc5. Aunction groups and their function modules are the procedural predecessors of global classes with public methods. Aunction groups (li5e e-e programs and module pools$ can contain 1

dynpros as components/ which is not possible in class pools. If you reBuire wor5ing with dynpros in ABAP 6b4ects then function groups is the first choice. Aunction groups are also reBuired for *A3s. Lou can call function groups from methods but no more functional coding should be created in function modulesK instead you should branch from there into methods. Aunction pools are introduced with the FUNCTION-POOL statement and maintained with Aunction Builder (S=0"$ of ABAP 8or5bench.

Subroutine Pools
Subroutines pool contains a subroutine processing bloc5s that can be called by other programs. The use of subroutine is obsolete in ABAP 6b4ects. Cowever/ you can create local classes in subroutine pools and connect their public methods to a transaction code. A subroutine pool that contains a class with a main method that is connected to a transaction code is very similar to >ava program. Subroutine pools are created using the ABAP =ditor (S=0.$ of ABAP 8or5bench and are introduced with the PROGRAM statement.

%Aecutable Programs
=-ecutable programs can contain all processing bloc5s supported in ABAP/ with the e-ception of function modules/ and as many local classes as reBuired. =-ecutable programs are often referred to as reports/ and why running an e-ecutable program is often called reporting. Analogously/ the source code of an e-ecutable program starts with the REPORT statement. 6nly e-ecutable programs can be called using their name. In ABAP 6b4ects/ e-ecutable should only be used if direct e-ecution using the name is important. Aor technical point of view/ e-ecutable programs are currently only reBuired for bac5ground processing. Today you should only handle the STA*T&6A&S=2=3TI69 event of the reporting (e-e program$ process and 4ump from the corresponding processing bloc5 directly to a method of a local class. It is maintained directly in the ABAP =ditor (S=0.$ of ABAP 8or5bench. =-ecutable programs are only started with the SUBMIT statement. Although 9et8eaver AS ABAP offers several ways to call e-ecutable programs by entering their name on the screen/ the system still e-ecutes the SUBMIT statement in the bac5ground.

Mo!ule Pools
<odule pool acts as a container for dialog modules called by the dynpros flow logic. <odule pools were originally designed for the dialog programming with dynpros. 8ith the e-ception of reporting event bloc5s and function modules/ module pools can contain all processing bloc5s supported in ABAP and as many local classes as reBuired. <odule pools are no longer play a role in ABAP 6b4ects. Instead/ function groups should be used as carriers of dynpros. <odule pools are introduced with the PROGRAM statement. It is maintained directly in the ABAP =ditor (S=0.$ of ABAP 8or5bench.

1,

$"pe 1roups
Type groups only contain declaration part for global data types and constants which can be made visible in any ABAP program. Type groups are predecessor technology for general type definitions in the ABAP ;ictionary and in global classes or interfaces. 9o more type groups should be created in ABAP 6b4ects. Instead/ types and constants can be published by global classes and interfaces. Type groups are introduced with the TYPEPOOLS statement. It is maintained with ABAP ;ictionary (S= $ tool of the ABAP 8or5bench.

Inclu!e Programs
Include programs have no introductory program statement and/ unli5e all other program types/ they do not represent independent compilation units with their own memory space. Include programs provide a library function for ABAP source code and can be embedded at any location in other ABAP programs using the INCLUDE statement. ;uring syntachec5 the INCLUDE statement is replaced by the source code of the include programs. Include programs have no technical relationship to processing bloc5s. Cowever/ it is preferable to separate logical program units/ such as the declaration part for global data/ and similar or individual processing bloc5s into independent include programs. They are automatically generated by ABAP 8or5bench when you create programs such as class pools or function pools. Lou can create your own include programs directly with the ABAP =ditor (S=0.$ tool of ABAP 8or5bench. Include programs ma5e large program much easier to handle/ as it can be transported individually/ which allows/ individual methods or function modules to be processed independently of their class pool or their function group. The %T6P include( is designed for the global declaration part of an ABAP program. The naming convention is that the name of top includes ends with %T6P(. 8hen you organi'e program using include program/ all statements of global declaration part should be included by the top include. It can be created automatically when you create an ABAP program in the ABAP 8or5bench by simply selecting the corresponding chec5bo-. Include programs should never be sued for multiple usage of source code in several compilation units. Instead/ you can use global classes or interfaces. The reason for this that the inclusion of an include program in several programs dramatically restricts both their maintainability. Aurther more/ an include program that is included in several programs is loaded several times into the program memory of the application server/ if the programs are used in parallel. 8e recommend the declaration part of a local class or processing bloc5 (method$. The names of include programs should correspond to those that are proposed by the ABAP 8or5bench. The following matri- shows all ABAP program types and their supported features.

10

'ecommen!e! Program $"pes (ith ABAP -b.ects


7se class and interface pools for reusable code in global classes and interfaces. Subroutine pools can serve as >ava&li5e programs in which you can call e-actly one main method from outside. The same applies for e-e programs as for subroutine/ though you can call them using SUBMIT statement/ which is technically suitable for bac5ground processes. 7se function groups only where technically necessary/ that is/ as containers for dynpros and for *A3&enabled function modules. 9ew module pools or type groups should no longer be created for programming with ABAP 6b4ects.

11

ABAP Program Processing Bloc+s


An ABAP program is embedded in a runtime environment provided by Application Server ABAP. The runtime contains processors that e-ecute the ABAP programs. The e-ecution of ABAP program is synonymous with a process in ABAP runtime environment/ which controls the program by calling the processing bloc5s. Cowever most of the concept of processors are primarily connected to procedural+event oriented ABAP programming and has lost significance for modern ABAP 6b4ects. The following types of processing bloc5s are available. Procedures ;ialog <odules =vent Bloc5s

Proce!ures
Procedure processing bloc5s have a local data area and can have a parameter interface. Procedure can be in the form of <ethod/ Aunction <odules or Subroutines.

Methods
<ethod is a component of a class. 66 ABAP program is built from methods that are organi'ed in classes. <ethod processing bloc5s can only be defined in class pools program type. METHOD statement and concluded with the ENDMETHOD statement. Lou call methods from ABAP programs using the CALL METHOD statement.

unction Modules
These are predecessors of methods for e-ternal procedure calls in the procedural programming model. It is also called e-ternal procedure. Aunction modules can only be created in function groups or function pools program type. Since many functions (dynpros and *A3$ of an ABAP are still offered in function modules/ they can continue to be called from methods. Aunction modules are introduced with the FUNCTION statement and concluded with the ENDFUNCTION statement. Lou call function modules from ABAP programs using the CALL FUNCTION statement.

Subroutines
These are predecessors of methods for internal procedure calls in the procedural programming model. It is also called internal procedures. Subroutines are replaced entirely by methods and should no longer be used. Instead you can create local classes for internal modulari'ation in all program types that can contain operational code.

1D

Subroutines are introduced with the FORM statement and concluded with the ENDFORM statement. Lou call subroutines from ABAP programs using the PERFORM statement.

Dialog Mo!ules
;ialog <odules are processing bloc5s without a local data area and without a parameter interface. They can only wor5 with global data from the declaration part of their ABAP program/ which prevents data encapsulation. They can be used in ABAP programs that support their own dynpros (e-ecutable programs/ function groups/ module pools$. ;ialog modules processing bloc5s should contain little or no operational code other than method calls. ;ialog modules are rarely needed nowadays. ;ialog modules are introduced with the MODULE statement and concluded with the ENDMODULE statement. ;ialog modules called from the screen flow logic (screen command MODULE$.

%vent Mo!ules
=ven <odules are processing bloc5s without a local data area and without a parameter interface. They can only wor5 with global data from the declaration part of their ABAP program/ which prevents data encapsulation. 3lassical ABAP programs and e-ecutable programs particularly are event&oriented. =vent bloc5s are called through events which are triggered by user actions on selection screens and lists or by the ABAP runtime environment. ABAP 6b4ects has an e-plicit event concept where events are triggered by a statement in methods and are handled by special methods (event handlers$. The events bloc5s can be divided into:

Program Constructor !vent Block


;irectly after an e-ecutable program/ a module pool/ a function group or a subroutine pool has been loaded/ a special processing bloc5 can be e-ecuted e-actly once. This bloc5 can be used for global data initiali'ation. Therefore it resembles class constructor. This processing bloc5 is defined as an event bloc5 using the event 5eyword LOAD-OFPROGRAM.

Selection Screen !vent Block


It is triggered by the screen selection processor of ABAP runtime environment during selection screen processing. Selection screens are special dynpros.

"ist !vent Block


It is triggered by the list processor of the ABAP runtime environment during classical list processing. In ABAP 6b4ects the creation and processing of classical lists is obsolete in most cases.

1G

#eporting !vent Block


It is triggered by the reporting processor of the ABAP runtime environment if an e-ecutable program is e-ecuted. In ABAP 6b4ects you should only implement the START-OF-SELECTION.

1"

%lements o ABAP #anguage


Statements
=ach ABAP program is composed of one or more statements. =ach statement contains one or more words separated by at least one space. The first word of a statement is the 5eyword. A statement can include one or more additions/ and always ends with a period.

The first 5eyword of statement determines the category of the statements. The different statement categories are as follows:

Declarative Statements
These statements define data types or declare data ob4ects which are used by the other statements in a program or routine. The collected declarative statements in a program or subroutine ma5e up its declaration part. =-amples of declarative 5eywords: TYPES, DATA, TABLES.

Modulari$ation Statements
These statements define the processing bloc5s in an ABAP program. =-amples of modulari'ation 5eywords: START-OF-SELECTION, MODULE ... ENDMODULE.

Control Statements
Lou use these statements to control the flow of an ABAP program within a processing bloc5 according to certain conditions. =-amples of control 5eywords: IF, WHILE, CASE.

Call Statements
Lou use these statements to call processing bloc5s that you have already defined using modulari'ation statements. The bloc5s you call can either be in the same ABAP program or in a different program. =-amples of call 5eywords: PERFORM, CALL, SET USER-COMMAND, SUBMIT, LEAVE TO.

1.

Operational Statements
These 5eywords process the data that you have defined using declarative statements. =-amples of operational 5eywords: WRITE, MOVE, ADD.

Database Statements
These statements use the database interface to access the tables in the central database system. There are two 5inds of database statement in ABAP: 6pen SF2 and 9ative SF2. -pen S0#: 6pen SF2 is a subset of the standard SF2!, language. It contains only ;ata <anipulation 2anguage (;<2$ statements/ such as S=2=3T/ I9S=*T/ and ;=2=T=. It does not contain any ;ata ;efinition 2anguage (;;2$ statements (such as 3*=AT= TAB2= or 3*=AT= I9;=I$. Aunctions of this type are contained in the ABAP ;ictionary. ABAP programs that use only 6pen SF2 statements to access the database are fully portable. The database interface converts the 6P=9 SF2 commands into commands of the relevant database. Native S0#: 9ative SF2 statements are passed directly from the database interface to the database without first being converted. It allows you to ta5e advantage of all of your databaseEs characteristics in your programs. In particular/ it allows you to use ;;2 operations. The ABAP ;ictionary uses 9ative SF2 for tas5s such as creating database tables. In ordinary ABAP programs/ it is not worth using ;;2 statements/ since you cannot then ta5e advantage of the central administration functions of the ABAP ;ictionary. ABAP programs that use 9ative SF2 statements are database&specific.

Chaine! Statements
The ABAP programming language allows you to concatenate consecutive statements with an identical first part into a chain statement. To concatenate a seBuence of separate statements/ write the identical part only once and place a colon (:$ after it. After the colon/ write the remaining parts of the individual statements/ separating them with commas. =nsure that you place a period (.$ after the last part to inform the system where the chain ends. Statement seBuence: WRITE H !!"#. WRITE $" $% #. WRITE &"'!( ") ABAP#. 3hain statement: WRITE* H !!"#, $" $% #, 1!

&"'!( ") ABAP#. In a chain statement/ the first part (before the colon$ is not limited to the 5eyword of the statements. Statement seBuence: SUM SUM SUM SUM + + + + SUM SUM SUM SUM , , , , -. .. /. 0.

3hain statement: SUM + SUM , * -, ., /, 0.

D#

Data -b.ects an! Data $"pes Data -b.ects


;ata ob4ect is a named memory that is structured according to a particular data type. ;ata ob4ects are instances of data types. =ach ABAP data ob4ect has a set of attributes (field length/ number of decimal places$ which it acBuires from its data type. ;ata ob4ects reside in repository. ;ata ob4ects can be created by using declarative statements (DATA statement$ or CREATE DATA statement. ;ata ob4ects that have been created using declarative statements are assigned name and can be accessed through this name. ;ata ob4ects created using CREATE DATA are not assigned a name (anonymous data ob4ects$ and can be addressed only via reference variables/ similar to class instances. DATA (1$1_"23 TYPE (1$1_$45 6LENGTH ! 78 6DECIMALS ( 98 VALUE :1!8 6READ-ONLY8. The statement defines a (1$1_"23 data ob4ect of type (1$1_$45 . LENGTH must be used for incomplete types (p/c/n and -$ discussed later. The DECIMALS is used to define the number of decimal places for pac5ed number type (p$. The VALUE addition defines the initial value for data ob4ect (1$1_"23. READ-ONLY addition can be used to declare an attribute in the public visibility section of a class (discussed in class section$ in such away that its contents can not be changed from out side the class. CREATE DATA (1$1_"23_' ) TYPE (1$1_$45 6LENGTH ! 78 6DECIMALS ( 98. ;ata ob4ects have three levels of visibility (a5a 3onte-t of ;ata 6b4ect$: global/ local/ and class. The visibility of a data ob4ect indicates from where in the program the data ob4ect is accessible. 1lobal Data -b.ects: can be accessed from anywhere within the program. They are declared in the declaration part of a program. The life cycle of global data ob4ect is bound to the life cycle of its program in the internal session. In ABAP 6b4ects/ avoid using program global data/ instead use global classes. #ocal Data -b.ects: are accessible only from inside the methods or other procedures (function modules/ subroutines$ in which they are defined. The life cycle of local data ob4ect spans over the body of method or procedure. Class #evel Data -b.ects: ;ata declarations in the declaration part of classes either create instance attributes or static attributes. Instance attributes can b addressed in all instance methods/ while static attributes can be addressed in all methods via their names.

The life cycle of an instance attribute depends on the lifecycle of an ob4ect/ while the life cycle of a static attribute depends on the life cycle of an internal session. ;ata ob4ects can be of the form: 2iterals/ Hariables/ 3onstants or Te-t Symbol.

"iterals
2iterals are not created by declarative statements. Instead/ they e-ist in the program source code. 2i5e all data ob4ects/ they have attributes (field length/ number of decimal places/ data type$/ but no name. They are therefore referred to as unnamed data ob4ects. 2iterals can be numeric or character. Aor e-ampleK ,0DG/ or %Cello 8orld(.

%ariables
Hariables are named data an ob4ect that you can declare statically (compile time$ using declarative statements or dynamically while a program is running. They allow you to store changeable data under a particular name within the memory area of a program. Lou declare variables using the DATA, CLASS-DATA, STATICS, PARAMETERS, SELECT-OPTIONS/ and RANGES statements.

Constants
3onstants are data ob4ects whose contents cannot be changed. Lou declare constants using the CONSTANTS statement. Lou cannot define constants for XSTRINGS/ references/ internal tables/ or structures containing internal tables. CONSTANT (1$1_"23 TYPE (1$1_$45 VALUE :1! ; <IS INITIAL=.

IS INITIAL is use to set a constant (1$1_"23 to its type specific initial value.

&e't Symbols
Te-t symbols are pointers to te-ts in the te-t pool of the ABAP program. The te-t pool contains the te-t elements of the program/ several te-t pools can be defined in different languages for a program. 8hen the program starts/ the corresponding data ob4ects are generated from the te-ts stored in the te-t pool. They can be addressed using the name of the te-t symbol. Te-t Symbols are maintained with Te-t =lement <aintenance (S=0,$ of the ABAP 8or5bench. Te-t Symbols are lin5ed to the translation/ i.e. you can use te-t symbols in places where you want to display te-ts from the program on the user interface/ without to bother about the logon language of specific user.

D,

Data $"pes
;ata types specify the attributes of data ob4ects. ;ata type determines how the data is stored in the memory/ and tells the ABAP statement how to handle it. ;ata types do not occupy memory. The TYPE 5eyword defines the data type for data ob4ect as: DATA $>$ TYPE 9 LENGTH -. VALUE H !!" W"'!(#. Cere t-t data ob4ect is an instance of data type c with initial value %Cello 8orld(. In ABAP we have the following data types.

!lementary Data &ypes


These are data types of fi-ed or variable length that are not made up of other types. There are eight fi-ed length and two variable length elementary data types. The difference between variable length data types and fi-ed length data types is that the length and the memory space reBuired by data ob4ects of variable length data types can change dynamically during runtime. Lou can also define your own elementary data types in ABAP using the TYPES statement. Lou base these on the predefined data types. This determines all of the technical attributes of the new data type. There are total # built&in elementary data types: *iAe! #ength %lementar" Data $"pes The %2ength( column indicates the minimum and ma-imum number of bytes or characters that a data ob4ect can occupy. The interval is specified in length column for 5/ 9/ 7 and > data types means that these data types are incomplete or generic and it is reBuired to use the LENGTH addition to specify their length/ otherwise you cannot use them to declare data types and data ob4ects. The other types ?/ )/ (/ and $ are not generic and complete/ you donEt need to specify LENGTH when declare a data ob4ect or data type. In fact/ specifying length in this is forbidden. ;ata ob4ects that are declared using one of these eight data types are referred to as static data ob4ects because the utili'ed memory space is statically (during declaration$.

D0

Data $"pe

#ength

Stan!ar! #ength

Initial &alue

Meaning

Numeric Data $"pes i f p 1 bytes . bytes & G bytes & GDD0D characters & GDD0D characters . characters G characters # # # Integer Aloating point Pac5ed number Te-t Aield (Alpha numeric$ 9umeric Te-t Aield (9umeric characters$ ;ate Aield (Aormat: LLLL<<;;$ Time Aield (Aormat: CC<<SS$$ Ce-adecimal field

.bytes

Character Data $"pes c n d t character character UR.E :# R #: U########: :######:

8eAa!ecimal 4B"te5 Data $"pe &GDD0D bytes byte -:## R##:

&ariable #ength %lementar" Data $"pes #ength Stan!ar! #ength Initial &alue Meaning

Data $"pe

Character Data $"pes string -string 3haracter Strings Byte Strings

Comple' Data &ypes


3omple- data types are made up of other data types. 3omple- ;ata Types allow you to manage and wor5 with semantically related datasets under a common name. There is nor built&in comple- data types. A comple- data type must be constructed from e-isting types. 3omple- data types can be structured types or table types.

D1

#e(erence Data &ypes


*eference types describe data ob4ects (reference variables$ that contain references to other ob4ects. There are types of data references (references to data ob4ects$ and ob4ect references (references to instances of classes$.

DD

De ining Data $"pes


There are two ways to define data types in ABAP: Bound ;ata Type Independent ;ata Type

Bound Data &ype


The data statement DATA creates a bound data type. That is a type defined only for that particular data ob4ect and canEt be used for other data ob4ects. DATA @AB TYPE 9 LENGTH .C VALUE H !!"#. The above statement declares @AB data ob4ect of type 9 with length of ,# characters. 9ow these properties i.e. type and length is 4ust associated or bound with data ob4ect @AB. If we try the following declarative statement. DATA $>$ TYPE @AB VALUE W !9"@ #. Lou will get an error saying that type @AB is un5nown. This shows that the properties li5e type and length is bound to @AB and you canEt use the TYPE addition to @AB to define data ob4ects of type @AB. The LIKE 5eyword is used to solve the above problem. Aor e-ample the following line is e-ecuted without any errors. DATA $>$ LIKE @AB VALUE W !9"@ #. The above line says that $>$ is a data ob4ect having same properties as that of @AB. LIKE refers to predefined data ob4ects. But the problem with this method is we are creating data ob4ects even for the purpose of defining data types i.e. LIKE similar to TYPE also allocates memory space. As a result/ this would consume a lot of memory. Aor this reason ABAP provides an independent data types.

)ndependent Data &ypes


Independent data types act as a template for data ob4ects/ similar to classes that can be used for template for ob4ects. The TYPES 5eyword is used to define an independent data types. The TYPES 5eyword creates data type and does not allocate memory space. The synta- of TYPES is almost identical to the DATA statement but without data ob4ect specific additions li5e length and value etc.

DG

The TYPES statement for an independent character&li5e data type te-t of length ,# would be as follows: TYPES $ >$ TYPE 9 LENGTH .C. To declare data ob4ects of type te-t: DATA $>$- TYPE $ >$ VALUE W !9"@ #. DATA $>$. TYPE $ >$ VALUE $" ABAP#. This means/ that t-t and t-t, are of type te-t which in turn of type c and having length of ,#. 8ith so many different ways to declare data types/ the Buestion arises as to when you should use which optionV It is good programming style to create a self&defined data type only as an independent type. 7se LIKE addition whenever your declaration is directly li5ed to a data ob4ect. =-amples of this include au-iliary variables in procedures that must have the same type as interface parameters or their components. This 5eeps your program valid even if the data type of the data ob4ects changes. In all other cases/ you should use the TYPE addition to directly reference appropriate independent data types.

D"

%lementar" Data $"pes 7sage


*umeric Data &ypes
Data $"pe i: i is a complete type/ used for integers/ having si'e of 1&bytes. 6ften used for inde- or count variables. The default value is #. DATA 9"D7$ TYPE ? VALUE C. Data $"pe : f is a data type for binary floating point numbers. f is a complete type. It is having .&bytes of si'e. It is consists of three components: the J+& sign/ a G&digit mantissa and the e-ponent. <antissa contains the digits of the number/ while the e-ponent specifies the position of the decimal point. The default value is #. DATA ' AD!$ TYPE ). Data $"pe p: p is incomplete type. It is pac5ed numbers in the Binary 3oded ;ecimals (B3;$ format with fi-ed number of decimal places. The number of decimal places is defined during declaration of data type or data ob4ect using the DECIMALS addition after TYPE. The default value is #. The type p is useful for monetary amounts/ dimensions or weights etc. DATA 7D@2 ' TYPE 5 DECIMALS . VALUE ./. 8ith SAP 9et8eaver ,##" new data type decfloat G and decfloat01 are introduced to replace the f and p data types. Data $"pe !ec loatBC: decfloat G is complete type. It is decimal floating point number with G decimal places. It is having .&bytes of si'e. The default value is #. DATA 7" TYPE ( 9)!"1$-E VALUE -.. Data $"pe !ec loat9D: decfloat01 is complete type. It is decimal floating point numbers of this type are represented internally with 01 decimal places. It is having G&bytes of si'e. The default value is #. DATA 7" TYPE ( 9)!"1$/0 VALUE ./.

Character Data &ypes


Data $"pe c: c is a data type that can be used for any character string of fi-ed length. c is incomplete data type for this purpose you must specify the length property for this data type.

D.

DATA $>$ _!?7 TYPE 9 LENGTH F.. $>$_!?7 + ABAP 5'"B'1@@?7B ?A )D7GH. Data $"pe n: Type n is a special case of type c for numeric characters/ but not a numeric data type. n is also incomplete data type. ;ata ob4ects of this type can only contain numbers/ but these numbers can not be directly used to carry out calculations. Typical use areas can be PIP codes/ Phone 9umbers/ P.6 Bonumbers etc. DATA 5"A$1!_9"( TYPE 7 LENGTH I. 5"A$1!_9"( + .ICCC#. Data $"pe !: d is data type for date information in the format/ YYYYMMDD. d is a complete type. If data ob4ect of type d is used in the position of operands where a numerical value is e-pected/ the date is regarded as a number that corresponds to the number of days that have been passed since CCC-C-C-. 6ther operations utili'e the character nature. DATA $"(14 TYPE (. $"(14 + A4-(1$D@. $"(14 + $"(14 , .. The A4-(1$D@ system field provides the system date/ after the calculation/ it assign the date of day after tomorrow. Data $"pe t: t is a data type for time information in the format/ HHMMSS. It is complete data type. . If data ob4ect of type d is used in the position of operands where a numerical value is e-pected/ the time is regarded as a number that corresponds to the number of seconds that have been passed since midnight CCCCCC. 6ther operations utili'e the character nature. DATA 7"& TYPE $. 7"& + A4-DJ ?$. 7"& + 7"& , /ECC. The A4-DJ ?$ system field provides the current time/ and then one hour is added to the now data ob4ect. Data $"pe A: - is a data type used for storing byte strings of fi-ed length. It is incomplete data type. Type - data ob4ects can generally be used for byte&li5e content where the fi-ed length is important. DATA % > TYPE > LENGTH /. % > + F/0IEAB#.

D!

Data $"pe string: Type string is a data type that can be used for any characters strings of variable length. The LENGTH addition is not allowed with string data typeK however you can use the VALUE addition to initiali'e a string data ob4ect. DATA $>$_A$' TYPE A$'?7B.

Data $"pe Astring: -string is a data type that can be used for any byte string of variable length. The LENGTH and VALUE and addition is not allowed with -string data type. DATA $>$_>A$' TYPE >A$'?7B.

G#

CompleA Data $"pes


3omple- data types can be structured types or table types.

Structured Data &ype


Structured data type is consists of a seBuence of other data types. The data ob4ect of a structured data type is called structure. The units that ma5e up a structured type are called structure components (fields$. The components of the structure can be elementary data types/ a structure/ an internal table or a reference data type. Structures are used especially to define the data at the interface of module pools and screens and to define the types of function module parameters. There are Alat/ nested and deep structures. A flat structure only references elementary types. A nested structure references at least one further structure/ but not a table type. A deep structure references at least one table type. The BEGIN OF and END OF statements define the beginning and end of a structure as a bound or independent type: DATA* BEGIN OF A$'D9$D' _71@ , A$'D9$_9"@5- TYPE;LIKE K, A$'D9$_9"@5. TYPE;LIKE K, KKK KKK A$'D9$_9"@57 TYPE;LIKE K END OF A$'D9$D' _71@ .

TYPES* BEGIN OF A$'D9$D' _71@ , A$'D9$_9"@5- TYPE K, A$'D9$_9"@5. TYPE K, KKK KKK A$'D9$_9"@57 TYPEK END OF A$'D9$D' _71@ . The addition of BEGIN OF and END OF statements define the beginning and end of a structure called A$'D9$D' _71@ . The colon and the commas indicate that we are dealing with several DATA and TYPES statements. All the statements that lie in&between G

declare the components of the structure. A component that is structured itself is referred to as a substructure. A structure that contains substructures is called nested structure. The component of a structure can be accessed with structure component (&$. Aor nested structures/ you must concatenate the structure names to access internal components.

G,

The program produces the following out put.

Aor the street/ we created a separate structured type A$' $_A$'D9$ with components 71@ and 7". Aor the address/ we declare a structure 1((' AA_A$'D9$ as a data ob4ect (everything we discussed for DATA also holds true for CLASS-DATA/ for declaration of static attributes.$ and we declare the A$' $ component with type A$' $_A$'D9$. The substructure 9?$4_A$'D9$ consists of two components J?59"( and 71@ . Lou can integrate the components of a structure into another structure using the INCLUDE statement as: DATA BEGIN OF A$'D9$_-, KK INCLUDE STRUCTURE A$'D9$_. AS 71@

G0

6RENAMING WITH SUFFIX AD))?>8. KK DATA END OF A$'D9$_-. TYPES BEGIN OF A$'D9$_-, KK INCLUDE TYPE A$'D9$_. AS 71@ 6RENAMING WITH SUFFIX AD))?>8. KK TYPES END OF A$'D9$_-. The INCLUDE statement is not an addition to the TYPES or DATA statements. Instead/ it interrupts the chained statement that must be restarted afterwards. The components of A$'D9$_. will be transferred as components into the A$'D9$_structure. They can either be addressed commonly under the name 71@ / or individually by their component names. The RENAMING addition can be used to avoid naming conflicts.

G1

The program produces the following out put.

All the components are allocated at the same level. 9aming conflicts between the name components are avoided by the use of different endings. This type of structure definition avoids comple- nested structures with long name chains.

&able &ypes
Table types represent the second comple- data type. The data ob4ects of table types are internal tables. Internal tables are dynamic data ob4ects li5e stringsK internal tables are internally managed by references. An internal table consists of a dynamic seBuence of lines of the same data type (it can be thin5 of an arrays in >ava or 3W.9et$. The table type

GD

describes the line type/ the table category and a table 5ey. The following synta- can be used to declare the internal tables. DATA $12_71@ TYPE;LIKE STANDARD;SORTED;HASHED TABLE OF (1$1_$45 ;(1$1_"23 9$ WITH 6NON-8UNIQUE KEY 9"!-K9"!7. TYPE STANDARD;SORTED;HASHED TABLE OF (1$1_$45 WITH 6NON-8UNIQUE KEY 9"!-K9"!7.

TYPES

$12_71@

The 5eywords STANDARD/ SORTED and HASHED define the table category. S$ANDA'D $able: is managed internally by a table inde-. Access is possible via table inde- or table 5ey. 8ith a 5ey access/ the response time is directly dependent on the number of table entries. The 5ey of a standard table is always non&uniBue. This table category is suited best whenever the individual entries can be accessed using the inde-. S-'$%D $able: is managed internally by means of a table inde-/ too. They are always sorted by the table 5ey and can be accessed via the table inde- or the table 5ey. 8ith a 5ey access/ the response time is logarithmically dependent on the number of table entries/ because the table is accessed via a binary search. The 5ey of sorted tables can be uniBue or non&uniBue. This table category is suited whenever the table must already be sorted when it is filled. 8AS8%D $able: is managed internally by a hash algorithm. Cashed tables can be accessed only via the table 5ey. The response time is constant/ independent of the number of table entries. The 5ey of hashed tables is always uniBue. This table category is suited whenever the 5ey accesses represent the central operation on the table entries. The (1$1_$45 and (1$1_"23 9$ represent the line type. The internal table can contain any number of lines of the specified line type. Thus/ line type is fi-ed during declaration/ but not the number of lines. Lou can use any line type/ elementary types/ reference types/ structures and even other internal tables. The table 5ey is reBuired for the identification of table rows. An internal table has a uniBue or non&uniBue table 5ey that can be defined by listing its components. =-ample below demonstrates the usage of internal table.

GG

After e-ecuting the loop will display five message bo-es as:

G"

=-ample above declares a standard table 1''14 whose line type is elementary data type i and whose 5ey consists of the DEFAULT KEY. DEFAULT KEY is build from all columns of the internal table that have a character&type type (9/ (/ $/ 7/ >/ A$'?7B/ >A$'?7B$. The APPEND statement appends a new line to the end of the inde-ed internal table. The A4-?7( > is a system field (System fields are filled according to the conte-t by system runtime$ gets the particular record number. It acts li5e 2oop Iteration 3ounter.

'e erence Data $"pes


*eference types can contain a reference to other data ob4ects or to instances of classes. Those data ob4ects are referred to as reference variables. ;epending on the type of ob4ect that is referenced/ we spea5 of data reference variables or ob4ect reference variables that can either contain data references or ob4ect references. The following synta- can be used to declare the reference data types. DATA ' )_:1'?12! TYPE ;LIKE REF TO (1$1_$45 ;(1$1_"23 9$. G.

TYPES ' )_:1'?12!

TYPE REF TO (1$1_$45 .

DATA "23_' ) TYPE REF TO 9!1AA;?7$ ')19 . TYPES "23_' ) TYPE REF TO 9!1AA;?7$ ')19 . The first two statements create the reference variable for data reference. 9e-t two statements create an ob4ect reference for class or interface. All of the data ob4ects that you define in the declaration part of a program using statements such as DATA are created statically/ and already e-ist when you start the program. To create a data ob4ect dynamically during a program/ you need a reference variable and the following statement: CREATE DATA ' )_:1'?12! TYPE ;LIKE (1$1_$45 ;(1$1_"23 9$. CREATE DATA ' )_:1'?12! TYPE (1$1_$45 .

The statements create a reference variable in the internal session of the current ABAP program. After the statement/ the data reference in the data reference variable points to the ob4ect. The ob4ect component selector (-L$ can be used to access the components of the reference variable. The dereferencing operator (-LM$ can be used to access the entire data ob4ects that is referenced. The following statements allow you to place a data reference to an e-isting data ob4ect in a reference variable: GET REFERENCE OF (1$1_"23 9$ INTO ' )_:1'?12! . =-ample below demonstrates the usage of reference variable and ob4ect references.

G!

The program produces the following results.

The declaration section introduces the "23_' ) is an ob4ect reference to 9!A class/ while (1$1_' )- and (1$1_' ). are reference variables to "23_' ) and ? respectively. CREATE OBJECT statement allocates the reference "23_' ) which enable us to access its attribute :1'. The GET REFERENCE OF statement gets the reference of "23_' ) and places it into the (1$1_' )- reference variable.

"#

CREATE DATA statement creates a data ob4ect (1$1_' ). dynamically. 6n ne-t line through dereferencing operator (-LM$ we access the :1' attribute of "23_' ) ((1$1_' )- is pointing to "23_' )$ and assign to (1$1_' ).. After e-ecution it is clear that both "23_' ) and (1$1_' ). are pointing to same memory location.

1eneric Data $"pes


The generic data types allow the dynamic programming. By generic we mean that the data type is determined during runtime. Table below lists the predefined generic types in the first column/ while the second column describes the types they comprise. Lou can assign a data ob4ect with a type from the second column to a formal parameter r field symbol (Aield symbols are placeholders or symbolic names for other data ob4ects. Aield symbols are similar to dereferenced pointers in 3$ that is typed with a generic type from the first column. 1eneric $"pe any/ data cli5e cseBuence -seBuence any table sorted table hashed table inde- table standard table/ table numeric c/ n/ p/ simple $"pes Comprise! All data types c/ d/ n/ t/ string/ and flat structures containing character li5e components c and string (te-t li5e types$ - and -string (byte li5e types$ All table types Sorted tables Cashed tables Standard and Sorted tables Standard tables i (b/s$/ p / f (numeric types$ 3orresponding built&in types with generic lengths and decimal places c/ d/ f/ i (b/s$/ n/ p/ t/ string/ -/ -string/ and flat structures containing character li5e components

If table type is defined using the TLP=S statement or if it is defined in the ABAP ;ictionary without specifying a 5ey/ this table type is also generic type.

*lat an! Deep Data $"pes


All data types in which the content of their data ob4ects represents actual wor5ing data are referred to as flat data types. Thus all elementary data types of fi-ed length are flat data types. All data types in which content of their data ob4ects are references that point to wor5ing data in different locations of the memory are referred to as deep data types. Thus reference types and dynamic data ob4ects (strings and internal tables$ are deep data types. "

In assignment between deep data ob4ectsK for assignments between reference variables/ reference semantics applies i.e. only the references are copied/ but not the referenced ob4ects. Aor assignment between dynamic data ob4ects (strings and internal tables$/ value semantics applies i.e. the referenced ob4ect is copied and a new reference is created. The memory reBuirement for deep data ob4ects is combination of a constant reBuirement for the reference (. bytes$ and a dynamic reBuirement for actual ob4ects.

",

ABAP Dictionar"
ABAP ;ictionary is a central global storage for data definitions (metadata$ of user defined types (data elements i.e. elementary types/ structures/ table$/ inde-es/ views and domains that can be accessed by all repository ob4ects/ provided this is permitted by the pac5age chec5. The ABAP ;ictionary describes the logical structure of the table and views used in application development and shows how they are mapped to the underlying relational database in tables or views. The ABAP ;ictionary also provides a number of services that support program development. Aor e-ample/ setting and releasing loc5s/ defining an input help (A1 help$ and attaching a field help (A help$ to a screen field are supported. ;ata types of the ABAP ;ictionary play the same role as the global types that are declared using the TYPES statement in classes and interfaces. ;ata types of the ABAP ;ictionary enable a type&specific transfer of values between dynpros and ABAP programs. 8hen defining tables/ first a structured type is created in the ABAP ;ictionary/ based on this structured type a physical database table is generated in the database. To use data from database tables/ you must declare data ob4ects in an ABAP program. ABAP ;ictionary contains many more built&in types than the ABAP programming language/ and these types also have different names. The difference between the data types is based on the fact that the built&in data types of the ABAP ;ictionary must be compatible with the e-ternal data types of the database tables supported by the AS ABAP. If an ABAP program/ you reference a data type from the ABAP ;ictionaryK the elementary components of that data type are converted into the built&in data types of the ABAP programming language. Table below provides an overview of all built&in data types of the ABAP ;ictionary and their counterparts in ABAP programs. Dictionar" $"pe A33P Description Posting Period: The length is set to G places for this data type. The format is LLLL<<. In input and output/ a point is inserted between the year and month/ so the template of this data type has the form UQQQQ.QQE. 3haracter string: Aields of type 3CA* may have a ma-imum length of only ,DD in tables. If longer character fields are to be used in tables/ you must choose data type 23C*. There are no restrictions on the length of such fields in structures. 3lient: 3lient fields always have three places. 3urrency 5ey: Aields of this type are referenced by fields of type 37**. The length is set to D places for this data type. ABAP $"pe n

3CA* 329T 37OL

c c c

"0

37** ;ATS ;=3 A2TP I9T

I9T,

I9T1 2A9)

23CA*

2*A8

97<3 P*=3 F7A9

3urrency field: =Buivalent to an amount field ;=3. A field of this type must refer to a field of type 37OL (reference field$. The ma-imum length for this data type is 0 places. ;ate: The length is set to . places for this data type. The output template can be defined with the user profile. 3ounter or amount field: with decimal point/ sign/ and commas separating thousands. A ;=3 field has a ma-imum length of 0 places. Aloating point number: The length (including decimal places$ is set to G places for this data type. &byte integer: between # and ,DD. The length is set to 0 places for this data type. ,&byte integer: between &0,"G" and 0,"G". Aields of this type should only be used for length fields. 8ith I9S=*T or 7P;AT= on the long field/ the database interface enters the length which was actually used in the length field. The length is set to D places for this data type. 1&byte integer: between &, 1"1.0G1" bis , 1"1.0G1". The length is set to # places for this data type. 2anguage 5ey: This data type always has length . The language 5ey is displayed at the user interface with , places/ but is only stored with place in the database. 3haracter string of any length: but has to be declared with a minimum of ,DG characters. If there is an I9S=*T or 7P;AT= in ABAP programs/ this length field must be filled with the length actually reBuired. If the length field is not filled correctly/ this may lead to a data loss in the 23C* fieldX Aields of this type cannot be used in the 8C=*= condition of a S=2=3T statement. 2ong byte string: of any length/ but has to be declared with a minimum length of ,DG. If there is an I9S=*T or 7P;AT= in ABAP programs/ this length field must be filled with the length actually reBuired. If the length field is not filled correctly/ this may lead to a data loss in the 2*A8 fieldX Aields of this type cannot be used in the 8C=*= condition of a S=2=3T statement. 9umeric te-t: 2ong character field in which only numbers can be entered. The length of this field is limited to a ma-imum of ,DD places. Precession: Accuracy of a F7A9 field. The length is set to , places for this data type. Fuantity. =Buivalent to an amount field ;=3. A field of this type must always refer to units field with 79IT format (reference field$. The ma-imum length for this data type is 0 places.

p d p f b

i c

n s p

"1

Byte string: Aields of type *A8 may have only a *A8 ma-imum length of ,DD in tables. If longer raw fields are reBuired in tables/ you should select data type 2*A8. Hariable byte string: In the ;ictionary a length can be specified for this type (at least ,DG characters$. As default *A8ST*I9) for the output length 0, characters are proposed. Lou cannot attach search helps to components of this type. Hariable character string: In the ;ictionary a length can be specified for this type (at least ,DG characters$. As ST*I9) default for the output length 0, characters are proposed. Lou cannot attach search helps to components of this type. Short character string: In the ;ictionary the number of characters can be specified for this type ( &,DD$. String SST*I9) fields of this type can be used in inde-es and in the 8C=*= condition of a S=2=3T statement. Lou cannot use them in table 5eys. Time: The length is set to G places for this data type. The TI<S format is hhmmss. The template for input and output has the form UQQ.QQ.QQE. 7nit: Aields of this type are referenced by fields of type 79IT F7A9. The length of this data type is set to , or 0 places.

-string

string

string

t c

Lou can not directly reference the built&in data types of the ABAP ;ictionary in an ABAP program. Instead you must reference types of the ABAP ;ictionary that are created on the basis of those data types. 9ote the type b and s canEt be directly specified in ABAPK however they are internally assigned when dictionary types INT- and INT. are referenced. Type 2 and A behave li5e type ?/ but value ranges are more limited i.e. # to ,DD.

"D

The ABAP ;ictionary Tool can be used to define ABAP ;ictionary types. It can be called either by selecting 3reate ;ictionary 6b4ect RR. from the conte-t menu of pac5age in 6b4ect 9avigator or by entering transaction code S= .

Creating !lementary Data &ype


An elementary type is defined by the built&in data type/ length and possibly the number of decimal places. These type attributes can either be defined directly in the data element or copied from a domain. . To define elementary data typeK select 3reate ;ictionary 6b4ect ;ata =lement from the conte-t menu of pac5age.

"G

,. =nter the name for data element.

0. This will open the ;ictionary: <aintain ;ata =lement windowK select Predefined Type on ;ata Type tab. Select NUMC from data type and enter length of ..

1. 6n the Aield 2abel tab you can maintain te-t information for the data element. The field labels are used to display a ;ynpro screen field. Oeywords of different lengths (Short/ <edium and 2ong$ for identifying screen fields. Ceading is used as a column header when you output the contents of fields as a list in the ;ata Browser. The Aurther 3haracteristics tab maintains help (A $ and input help (A1$. 3lic5 Save button.

D. The 3reate 6b4ect ;irectory =ntry dialog will pop up save it. 9e-t confirm the Prompt for transportable 8or5bench reBuest dialog. G. 3onfirm the <aintain field label. ""

". 9ow you can see that new entry with the name ;ictionary 6b4ects is added to the tree under the N_MYPACKAGE.

.. To activate choose the Activate function from toolbar. !. The following code shows the usage of our newly created ABAP ;ictionary type N_DIC_TYPE.

".

#. 6n e-ecuting the above code/ it produces the following output.

Creating Domains
A domain defines a value range. A domain is assigned to a data element. All table fields or structure components that use this data element then have the value range defined by the domain. The relationship between the field or component and the domain is thus defined by the data element of the field or component. Aields or components that refer to the same domain (with the assigned data elements$ are also changed when the domain is changed. This ensures that the value ranges of these fields or components are consistent. . =nter S= to open the ABAP ;ictionary: Initial Screen. ,. Select ob4ect type ;omain/ enter the name of ;omain N_DOM and choose create button.

"!

0. The maintenance screen for domains appears. =nter an e-planatory short te-t in the field Short te-t. 1. 6n the ;ata type tab page/ choose the data type/ number of places (valid positions without editing characters such as comma or period$ and number of decimal places (only needed for data types DEC/ FLTP/ QUAN and CURR$. 9ote that some data types have a fi-ed length. Aor e-ample/ the data type CLNT (client$ always has 0 places. If you enter an invalid number of places for such a data type/ the system corrects this automatically after issuing a warning.

D. If only certain input values are valid for the domain/ you can enter them in the Halue range tab page as fi-ed values. If fi-ed values are defined for a domain/ these are used in the input chec5 in screen templates. Lou can define fi-ed value intervals either by entering upper and lower limits or by specifying single values. It is only possible to define fi-ed values for domains of data types CHAR/ NUMC/ DEC/ INT-/ INT. and INT0.

.#

G. Save the domain. 3onfirm the 3reate 6b4ect ;irectory =ntry and Transportable 8or5bench reBuest. ". The ;omain entry is now visible in 6b4ect 9avigator tree. Activate it.

.. 9e-t to create the elementary type based to our newly created domain N_DOM. Select ;ata Type/ enter the name of data type N_DOMAIN_TYPE and choose create button.

!. Select ;ata element on ne-t dialog and confirm.

#. 6n ;ictionary: <aintain ;ata =lement window/ enter the short te-t and domain PQ;6< and save it.

.,

. 3onfirm the 3reate 6b4ect ;irectory =ntry/ <aintain field label and Transportable 8or5bench reBuest. ,. The data element entry is now visible in 6b4ect 9avigator tree. Activate it.

0. The following code shows the usage of our newly created ABAP ;ictionary type N_DOM_TYPE_USAGE

.0

1. 6n e-ecuting the above code/ it produces the following output.

Creating Structures
A structure (structured type$ comprises components (fields$. A component can refer to an elementary type/ another structure/ a table type or a view. . Select 3reate ;ictionary 6b4ect Structure from the conte-t menu of pac5age/ and enter structure name JA$'D9$_$45 . ,. In <aintain Structure window enter the short description for JA$'D9$_$45 .

0. Provide the name in column 3omponent/ enter the name of the type whose attributes should be used in the component/ you can enter any type here.

.1

If you want to add components by entering the data type and length directly choose this will enable the ;ata Type/ 2ength ;ecimal Places columns and Short ;escription. By choosing you can switch to the screen for entering references to e-isting types/ this will enable the *Type and 3omponent Type columns. If you enter a class/ interface or generic reference (ANY/ DATA or OBJECT$ in the 3omponent Type column the *Type field is automatically set. If you enter a reference type already defined in the ;ictionary as a reference type/ a blue arrow appears in the ;ata Type column. If ;ata Type is QUAN or CURR then in 3urrency + Fuantity tab page/ you must specify the reference tableK this reference table must contain a field with the format for the currency 5ey (CUKY$ data type or unit of measure (UNIT$ data type.

6n =ntry help+chec5 tab/ choose / if you want to assign a search help to a structure field that points to a data element. 1. Then press SAH=/ 3C=3O and A3TIHAT=. D. The following code shows the usage of our newly created JA$'D9$_$45 .

.D

G. 6n e-ecuting the above code/ it produces the following output.

Inserting an Inclu!e To include the components of e-isting structures into new structure at highest hierarchy level/ you can select =ditIncludeInsert when creating the structure. This function provides the same option as the INCLUDE statement in ABAP programs in order to create structures with a single hierarchy level from other structures. Structures that are defined in this way are particularly interesting as templates for database tables. In the e-ample below a predefined structure SYST whose elements are the data types of the system fields is included in the JA$'D9$_$45 .

.G

. Place the cursor under the line in which you want to insert the ?79!D( choose =ditIncludeInsert.

and

,. A dialog bo- appears/ enter the structure name SYST/ the optional group name (with group name/ you can access the fields in the include together in ABAP program$ or a three&place suffi- (suffi- can be used to avoid name collisions between fields of the include and fields already in the table$. Press continue button.

0. A line with .INCLUDE in the 3omponent column and the name of the structure is inserted into 3omponent type column.

1. 3lic5 to =-pend Include

button to see the fields of SYST structure.

."

..

-perations in ABAP
Cere we will loo5 into the basic operations that we can carry out on data ob4ects.

Assignment -peration
Assignment operation determines how to move the data into the data ob4ects. The MOVE statement and assignment operator (+$ can be used to perform the assignment operation on the data ob4ects. To assign the value of a data ob4ect A"D'9 to a variable ( A$?71$?"7/ use the following statement: MOVE source TO destination. 6r the eBuivalent statement ( A$?71$?"7 + A"D'9 . In addition to the general type of assignment using M": (+$/ ABAP provides several special types of assignments. or the assignment operator

Assigning Structures by Components+ To assign individual components of a structure to the components of another structure. 6ne alternative method is to use several MOVE statements but ABAP provides a special statement for this: MOVE-CORRESPONDING source_struct TO destination_struct. This statement identifies all components that have the same name in both structures and assigns them individually according to the respective assignment rules without affecting other components. 9ested structures are completely dissolved in this process. 8hen it is e-ecuted/ it is bro5en down into a set of MOVE statements/ one for each pair of fields with identical names/ as follows: MOVE source_struct-<ci> TO destination_struct-<ci>. The following e-ample shows that the components of a structure are assigned to the components of two other structures that have the same names.

.!

!#

The above program produces the following output.

ormatted Assignment+ The internal representation of data in data ob4ects is usually not suited for a direct output of the values to the user. In particular/ this holds true for numeric data in data ob4ects of numeric data types whose code can not be used for a direct presentation. Prior to displaying the contents of those data ob4ects/ they must be converted into character&li5e data that can be output so that the user understands them. ABAP provides WRITE TO assignment statement that e-plicitly carries out this. WRITE source TO destination )"'@1$_"5$?"7A. This statement formats the content of an elementary data ob4ect A"D'9 and assigns it to a flat character @li5e data ob4ect/ ( A$?71$?"7. If no )"'@1$_"5$?"7A additions are specified/ formatting is carried out according to type&dependent predefined rules that can also depend on user&specific values or regional settings. Aollowing table illustrate the different formatting options.

*or All Data $"pes -ption 2=AT&>7STIAI=; 3=9T=*=; *I)CT&>7STIAI=; 96&P=*6 *or Numeric *iel!s 96&SI)9 ;=3I<A2S YdM =IP69=9T YeM *679; YrM 37**=93L YcM *or Date *iel!s ;;+<<+LL <<+;;+LL ;;+<<+LLLL <<+;;+LLLL ;;<<LL <<;;LL LL<<;;

*unction 6utput is left&4ustified. 6utput is centered. 6utput is right&4ustified. If a field contains only 'eros/ these are replaced by blan5s. Aor type 3 and 9 fields/ leading 'eros are replaced automatically. The leading sign is not displayed on the screen. YdM defines the number of digits after the decimal point. In type A fields/ the e-ponent is defined in YeM. Type P fields are multiplied by #SS(&r$ and then rounded. Aormat according to currency YcM in table T37*I. Separators as defined in userEs master record. Separators as defined in userEs master record. Separators as defined in userEs master record. Separators as defined in userEs master record. 9o separators. 9o separators. 9o separators.

2astly/ data types in ABAP ;ictionary can be lin5ed with specific function modules (3onversion *outines or 3onversion =-its$. 3onversion routines are used for formatting content for output and for converting input into internal formats. A conversion routine can be assigned to a domain in the ABAP ;ictionary. These routines are automatically e-ecuted when you use the WRITE TO statement. The following code demonstrates the use of WRITE TO statement.

!,

The above code produces the following output.

!0

The CLEAR statement reset variables to their type&specific initial value. CLEAR (1$1_"23. That is depending on the elementary data type/ the content of data ob4ect is reset to initial value discussed in data types section. The structure components are initiali'ed in accordance with their data type. All lines of an internal table are deleted while the reference variable points to null reference. The three cases determine the e-ecution of the assignment operation: Compatibility+ The A"D'9 and ( A$?71$?"7 data ob4ects are compatible. This means their data types match in all technical properties. ;uring copy process the content of A"D'9 is transferred byte by byte into the target field ( A$?71$?"7. The technical properties of an elementary data types are length and number of decimal places. In structured types/ the technical properties are defined by the composition of substructures and elementary data types. The technical properties of table types are the table category/ line type and table 5ey. Convertibility ,&ype Conversion-+ The A"D'9 and ( A$?71$?"7 data ob4ects are not compatible but convertible. This means that a conversion rule between the data types is defined in ABAP. In this case/ the content of A"D'9 is first converted according to the conversion rule before it is transferred into the target field ( A$?71$?"7. But it must be noted that a conversion reBuires a substantial amount of e-tra computing time. )ncompatibility and )nconvertibility+ If A"D'9 and ( A$?71$?"7 data ob4ects are neither compatible nor convertible/ no assignment is possible. If this is detected during the synta- chec5/ a synta- error occursK otherwise/ an e-ception will be raised.

$"pe Conversions
In ABAP/ the rules for type conversions are designed in such a way that the largest possible number of data types can be converted into each other without any error. The basic rule says that the content of a source field must represent a reasonable value for the data type of the target variable must always be fulfilled. It is pointless to allow conversions between data types ( and $ or between elementary fields and internal tables. Aollowing are the conversion rules for different data types: !lementary Data &ypes There are # built&in elementary types. ABAP contains conversion rules between all those types with the e-ception of types ( and $/ between which conversion doesnEt ma5e sense.

!1

&e't.&ype to &e't.&ype+ ;uring the conversion between te-t&type data ob4ects of data type 9 and A$'?7B/ the characters are transferred as left&aligned. If necessary/ target fields of type 9 are filled with space characters on the right&hand side/ or the right&hand side is truncated. Aor target fields of the A$'?7B type/ the transferred characters determine the length. Cere you should note that closing spaces are transferred for source fields of the A$'?7B type/ not for those of type 9. &e't.&ype to *umeric+ ;uring the conversion of te-t&type data ob4ects to numeric data ob4ects of data types ?/ 5/ and )/ the content of the source field must represent a number in an appropriate notation (mathematical/ commercial or scientific$. The value of the number is converted into the internal representation of the target field. &e't.&ype to Byte."ike+ ;uring the conversion of te-t&type data ob4ects to byte& li5e data ob4ects of data type > and A$'?7B/ the content of the source field must contain values in he-adecimal notation. =ach character of the source field determines the contents of a half&byte of the target field. *umeric to *umeric+ ;uring the conversion between numeric data ob4ects/ the value of the source field is converted into the internal representation of the target field. If necessary the value can be rounded. *umeric to &e't.&ype+ ;uring the conversion of numeric data ob4ects to te-t& type data ob4ects/ the value of the source field is represented in the target field as a character string/ either in commercial or in scientific notation/ depending on the data type. In a commercial notion/ the plus+minus sign is placed after the number/ while the scientific notation consists of a mantissa and an e-ponent. If the target field is not long enough/ the value is either rounded or truncated. *umeric to Byte."ike+ ;uring conversion of numeric to byte&li5e data ob4ects/ the value of the source field is first converted to ?. Then/ its internal representation is transferred without further conversion. Byte."ike to Byte."ike+ ;uring the conversion between byte&li5e data ob4ects/ the bytes are transferred as left&aligned. If necessary/ target fields of type > are filled with he-adecimal # on the right&hand side/ or the right&hand side is truncated. Aor target fields of the >A$'?7B type/ the transferred bytes determine the length. Byte."ike to &e't.&ype+ ;uring the conversion of byte&li5e data ob4ects to te-t& type data ob4ects/ the values of the bytes of the source field are represented in he-adecimal notation in the target field. Byte."ike to *umeric+ ;uring the conversion of byte&li5e data ob4ects to numeric data ob4ects/ the final four bytes of the source field are interpreted as an internal representation of a data ob4ect of type iK this number is converted into the data types of the target fields.

The following e-ample demonstrates the elementary data types conversion.

!D

!G

8hen a plain number is entered/ every conversion wor5ed as:

8hen a character is entered the conversion is failed and an e-ception is caught.

!"

Structured Data &ypes There are no conversion rules for structures that contain internal tables or strings (deep structures$. The conversion rules between flat incompatible structures state the following: Alat structures whose 7nicode Aragment Hiews (7AH$ are identical can be assigned without prior conversion. Alat structures of different lengths whose initial sections have the same 7AH across the length of the shorter structure can be assigned without conversion in the length of shorter structure. Surplus components are either truncated or they are filled with type&specific initial values.

*ote+ U2V splits a structure into "ragments& "ragment is a grouping o" structure components o" the same or similar data t%pes& 'n nested structures1 the elementar% components on the lo#est nesting depth are taken into account #hen "orming "ragments in nested structures&
BEGIN OF struc, a(2) TYPE C, b(4) TYPE N, c TYPE D, d TYPE T,

!.

e TYPE f(2) TYPE g(4) TYPE h( ) TYPE !( ) TYPE END OF struc"

F, X, X, C, C,

2ragment 3: a1 b1 c1 d 2ragment 4: lignment gap bet#een d and e 2ragment 5: e 2ragment 6: "1 g 2ragment 7: lignment gap bet#een g and h 2ragment 8: h1 i lignment gaps are b%tes that are inserted in "ront o" components so that the required alignment can be attained& *he s%stem normall% aligns "ields and structures automaticall% #hen %ou declare them& 9omponents #ith alignment requirements must begin at address that can be di$ided b% a speci"ic number& 2or e:ample1 the address o" a t%pe ! "ield must be di$isible b% 6 and the address o" a t%pe f "ield b% ;& The conversion rules between flat structures and elementary fields state the following: If the structure is purely character&li5e/ it is treated li5e a data ob4ect of type 9 during the conversion. If the structure is not completely character&li5e/ the elementary field must be of type c/ and the structure must begin with a character&li5e fragment that is at least as long as the elementary field. The assignment occurs e-clusively between this fragment and the elementary field.

The following e-ample demonstrates the structured type conversion.

!!

The above code produces the following output.

This e-ample defines two different structures/ A$'D9$_- and A$'D9$_.. In each one/ the first three components have the same data type. After assignment of A$'D9$_- to A$'D9$_./ only the result for the first three components is as if they had been ##

transferred component by component. All the remaining positions of A$'D9$_- are omitted. )nternal &ables Internal tables can only be converted into other internal tables. Lou cannot convert them into structures or elementary fields. Internal tables are convertible if their line types are convertible. The convertibility of internal tables does not depend on the number of lines. The conversion rules between internal tables state the following: Internal tables which have internal tables as their line type are convertible if the internal tables which define the line types are convertible. Internal tables which have line types that are structures with internal tables as components are convertible according to the conversion rules for structures if the structures are compatible.

#e(erence &ypes 3lass and Interface variables are pointers to ob4ects. The conversion rules between reference types state the following: If the two class references are incompatible/ the class of the target field must be the predefined empty class OBJECT. 8hen you assign a class reference to an interface reference/ the class of the source field must implement the interface of the target field. If two interface references are incompatible/ the interface of the target field must contain the interface of the source field as a component. 8hen you assign an interface reference to a class reference/ the class of the source field must be the predefined empty class OBJECT.

Arithmetic -perations
In arithmetic operations/ numeric operands are lin5ed to each other via arithmetic operators. The numeric operands can be numeric data ob4ects or built&in functions. 9umeric data ob4ects are data ob4ects of type ?/ )/ 5/ ( 9)!"1$-E and ( 9)!"1$/0 or byte&li5e (>$ and character&li5e (9/ (/ $/ 7$ data ob4ects whose contents can be interpreted as numeric on the basis of conversion rules. Built&in functions are predefined functions with a numeric return value. Built&in functions are further divided into numeric/ floating point and description functions. 9umeric functions accept arguments of any type of numeric data i.e numeric functions are overloaded. Aloating point functions accept only arguments of floating point data and returns floating point value. The description functions return properties of their argument #

for e-ample/ 9%1'! 7 determines the length of characters in terms of bytes/ A$'! 7 defines the number of characters of data ob4ect and !?7 A determine the number of lines in an internal table. The following table summari'es the numeric and floating point built in functions. *unction Numeric *unctions 12AO > P A?B7O > P 9 ?!O > P )!""'O > P $'D79O > P )'19O > P *loating Point *unctions 19"AO > P/ 1A?7O > P/ 1$17O > P / 9"AO > P/ A?7O > P/ $17O >P 9"A%O > P/ A?7%O > P/ $17%O > P >5O > P !"BO > P !"B-CO > P AQ'$O > P Meaning @ 'esult *eturns an absolute value of an argument. *eturns the J+& sign of an argument. *eturns the smallest integer value not smaller than the argument. *eturns the largest integer value not larger than the argument. *eturns the integer part of an argument. *eturns the fraction part of an argument.

Trigonometric functions. Cyperbolic functions. =-ponential function with base e (eZ,." .,. .,.D$. 9atural logarithm with base e. 2ogarithm with base #. SBuare root (only possible for positive numbers$.

The following table provides the list of arithmetic operators. ABAP also provides a self &e-planatory statement for four basic arithmetic operations but we wonEt elaborate on these statements any further. -perator , M S DIV MOD MM Meaning Addition Subtraction <ultiplication ;ivision Integer division *emainder =-ponent 5 5 5 5 5 5 5 + + + + + + + 7sage 7 @ @ @ @ @ @ , @. R 7. M 7. S 7. DIV 7. MOD 7. MM 7. Statement ADD 7 TO SUBTRACT MULTIPLY DIVIDE @ @. 7 FROM @. @ BY 7. BY 7. &&& &&& &&&

The following e-ample shows the usage of arithmetic operators and built&in functions.

#,

#0

The above code produces the following output.

#ogical -perations
A logical operation returns true or false. ABAP does not contain a Boolean data type to accept these values. The missing Boolean data type is replaced with data ob4ects of type 9 and length . If the data ob4ect contains an % X(/ it is interpreted as %true(. The %false( value/ on the other hand/ is represented by a space character. In ma4ority of logical operations/ the contents of two operands are compared with each other by using a relational operator. ABAP provides generic relational operators for all data types/ logical lin5ing and negating operators and specific relational operators for certain data types. The following table summari'es these operators.

#1

-perator

Meaning

7sage

Statement EQ NE LT LE GT GE ------&&& &&& &&& &&& &&& &&& &&& &&& &&& &&& &&&

1eneric 'elation -perators + =Bual to TL 9ot eBual to T 2ess than T+ 2ess than or eBual to L )reater than L+ )reater than or eBual to #ogical #in+ing an! Negating -perators O 9 T 7 P AND O 7 3ombine two logical AND L ) P e-pression O 9 T 7 P OR O 7 L 3ombine two logical OR ) P e-pression 9egate the result of NOT NOT O 9 T 7 P logical e-pression String Comparison -perators CO UBD U CO UABCD U 3ontains 6nly CN UABC-.U CN UABCD U 3ontains 9ot only CA UAB9( U CA UB( U 3ontains Any NA UABAB U NA UAB U contains 9ot Any CS UAB9( U CS U2C U 3ontains String NS UAB9( U NS U9 U contains 9o String CP UAB9( U CP UMV2MU 3ontains Pattern NP UAB9( U NP UM2MU contains 9o Pattern

Bit Se6uences Comparison -perators (,nd operand must have type I$ O 1# O T>L bits are 6ne N (# N T>L bits are Pero M 1# M T>L bits are <i-ed

9umeric fields (?/ )/ 5$ are compared with each other with regard to their numeric values. 3haracter&li5e fields (9/ A$'?7B/ (/ $/ 7$ are generally compared with each other from left to right. 6perands of type 9 and string are compared le-icographically and by differentiating between uppercase and lowercase letters. 6perands of type 7 are compared on the basis of the represented numeric values. If operands have type ( or $ and contain a valid date or time/ the later date or time is greater than the earlier one. Byte& li5e fields (>/ >A$'?7B$ are compared on the basis of their byte values. The previous type conversion rules also apply to operands of logical operators with little modifications. If one operand is date field type ( or a time field of type $ and the other

#D

operand is a numeric field/ the system converts date or time field into the numeric type. If the other operand is character&li5e/ the date and time fields are also regarded as being character&li5e. If one of the operands has data type 7 and the other has data type 9/ A$'?7B/ > or >A$'?7B/ the contents of both operands are converted to data type 5. If one of the operands is a te-t field of type 9 and the other operand is a te-t string of type A$'?7B/ the te-t field is converted into a A$'?7B/ the same rule applies to > and >A$'?7B. If one of the operands has a byte&li5e type and the other operand has a character&li5e type 9 or A$'?7B/ the content of an operand type > is converted to 9/ while the content of an operand of type >A$'?7B is converted to A$'?7B. It is recommended that you use compatible operands. Two reference variables are eBual when they point to the same ob4ect. Two compatible structures are identical if all their components are identical. Incompatible structures can be compared with each other if their 7nicode fragment views are identical in the length of the shorter structure. Structures can be compared with elementary fields if they contain only character&li5e and flat and its length matches at least the length of the elementary field/ which/ in turn/ must be of type 9. A prereBuisite for comparing internal tables is that its line type can be compared. If two internal tables contain the same number of lines/ they are compared with each other line by line and component by component. Note: B . processes logical e:pressions "rom the le"t to right& 't the s%stem detects that one o" the partial e:pressions is "ul"illed or not "ul"illed no other comparisons checks are carried out "or this partial e:pression& *here"ore1 to increase the processing speed b% arranging logical e:pressions in such a #a% that comparisons that o"ten return a <="alse= are placed at the beginning o" an #ND sequence&

#ogical %Apressions (ith Pre!icates


ABAP provides the following predicates for logical e-pressions. /*O&0 B!&W!!*+ chec5 whether the value of a field lies within a particular range. Aor e-ampleK 7D@2 ' BETWEEN / AND F. )S /*O&0 )*)&)A"+ chec5 whether the value of a field is initial. Aor e-ampleK )!1B IS INITIAL. )S /*O&0 BO1*D+ chec5 whether a reference variable points to an ob4ect. Aor e-ampleK ' ) IS BOUND. )S /*O&0 ASS)2*!D+ chec5/ whether a memory area is assigned to a field symbol T)AL. Aield symbols are placeholders for e-isting data ob4ects. Aor e-ampleK T)AL IS NOT ASSIGNED.

#G

)S /*O&0 S1PP")!D+ chec5 whether an actual parameter is bound to a formal parameter of a procedure. This predicate can only be used in function modules and methods. Aor e-ampleK 5- IS SUPPLIED. /*O&0 )* selection3tbl+ =valuates the conditions in a selection table. A selection table is an internal table with standard table type/ standard which represents a logical condition. The row type of a selection table is a structure that consists of four components: A?B7/ "5$?"7/ !"& / and %?B%. The following statement is used to declare a selection table in the program that is lin5ed to the ) column of a database table/ or to an internal ) field in the program. SELECT-OPTIONS A !_$12 FOR ). I for inclusive and E for exclusive. A !_$12-A?B7 + I#. Selection operator, EQ, NE, GT, E, T, !" and A !_$12-"5$?"7 + EQ#. sa#e as t$e colu#n t%pe of t$e data&ase ta&le, t$e selection criterion is lin(ed. Specif% t$e for a ran)e selection. A !_$12-!"& + /. sa#e as t$e colu#n t%pe of t$e data&ase ta&le, t$e selection criterion is lin(ed. Specif% t$e for a ran)e selection. A !_$12-%?B% + F.

N" to '$ic$ lo'er li#it to '$ic$ upper li#it

#"

Control Structures
3ontrol structures decompose a processing bloc5 (method etc.$ into statement bloc5s and control the program flow within the processing bloc5. ABAP provides Selection or Branching control structures and looping control structures. The concept of ABAP control structures is similar to those of other programming languages.

Selection @ Branching Control Structures


ABAP has two types of selection structures i.e. IF control structure and CASE control structure.

I* Control Structure
The IF control structure is used to e-ecute only one statement bloc5 on the basis of logical e-pression. Aollowing is the general synta- of IF control structure. IF !"B_ >5-. A$1$ @ 7$_2!"9W6ELSEIF !"B_ >5.8. A$1$ @ 7$_2!"9W. ..................... ..................... 6ELSE8. A$1$ @ 7$_2!"9W7 ENDIF. The logical e-pressions !"B_ >5 are chec5ed from top to bottom/ starting with the IF statement. The statement bloc5 that is located after the first true logical e-pression is e-ecuted. If none of the logical e-pressions is true/ the statement bloc5 after the ELSE statement is e-ecuted. If the ELSE statement is not specified/ it may result in no statement bloc5 being e-ecuted. Cowever/ it is recommended to always close the IF control structure with an ELSE statement. 2isting below shows an e-ample of IF control structure.

#.

#!

The above code produces the following output.

CAS% Selection Structure


The CASE selection structure is a multi&way branch control statement. Aollowing is the general synta- of CASE control structure. CASE (1$1_"23. WHEN "5 '17(- 6OR "5 '17(.8 6OR "5 '17(/ KK88. A$1$ @ 7$_2!"9WWHEN "5 '71(0 6OR "5 '17(I8 6OR "5 '17(E KK88.

A$1$ @ 7$_2!"9W. ..................... ..................... WHEN OTHERS. A$1$ @ 7$_2!"9W7 ENDCASE. The system chec5s from top to bottom/ starting with the first WHEN statement/ whether the contents of the operand "5 '17( agree with the contents of one of the operands/ "5 '17(-/ "5 '17(./ K/ and processes the statement bloc5 following the first agreement. If no agreement is found/ the statement bloc5 after WHEN OTHERS statement is e-ecuted. If the WHEN OTHERS statement is not specified/ it may result in no statement bloc5 being e-ecuted. Cowever/ it is recommended to always close the CASE control structure with WHEN OTHERS statement. 2isting below shows an e-ample of CASE control structure.

The above code produces the following output.

#oops @ Iterative Control Structures


2oops enable to e-ecute a statement bloc5 several times. ABAP provides DO/ WHILE/ LOOP AT and SELECT loop.

D- #oop
DO loop e-ecutes the bloc5 of statements several times unconditionally/ Aollowing is the synta- of DO loop. DO 67 TIMES8. A$1$ @ 7$_2!"9W ENDDO. If no additions are specified/ the statement bloc5 is repeated until it reaches a termination statement such as EXIT or STOP. The system field SY-INDEX contains the number of loop passes/ including the current loop pass. In nested loop you can access the inde- of an outer loop from within the inner loop by using the au-iliary variable. The TIMES addition restricts the number of loop passes to 7. 7 can be literal or a variable. If 7 is # or negative/ the system does not process the loop. If you do not use the TIMES option/ you must ensure that the loop contains at least one EXIT or STOP statement to avoid endless loops. 3ode below shows an e-ample of DO loop.

The above listing produces the following output.

W8I#% #oop
WHILE loop allows a bloc5 of code to be e-ecuted while a specified condition is true. Aollowing is the synta- of WHILE loop. WHILE !"B_ >5. A$1$ @ 7$_2!"9W ENDWHILE. The statement bloc5 in the loop is repeatedly e-ecuted as long as the logical e-pression !"B_ >5 is true/ or until the loop is left using a statement such as EXIT. Cere as well/ A4-?7( > is set to the current loop inde- in each pass. 3ode below shows an e-ample of WHILE loop.

The above listing produces the following output.

#--P A$ #oop
LOOP AT is special type of loop which can be used to read lines from internal table seBuentially. Aollowing is the synta- of LOOP AT loop.

LOOP AT ?7$ '71!_$12 ' AD!$ 69"7(?$?"7A8. A$1$ @ 7$_2!"9W ENDLOOP. The statement bloc5 between LOOP and ENDLOOP is e-ecuted once for each line. The output ' AD!$ determines when and where the line contents are read. To restrict the number of lines use the 9"7(?$?"7A addition. The loop continues to run until all the table lines that meet condition have been read or/ or until the loop is left using a statement such as EXIT. The LOOP statement sets system field A4-$12?> to table inde- of the current table line for standard tables and sorted tables and to # for hashed tables/ after every loop pass while the A4-AD2'9 remains unchanged. There are four alternatives to influence the output ' AD!$ as: ... <INTO &1= ; <ASSIGNING T)AL= ; <REFERENCE INTO (' )= ; <TRANSPORTING NO FIELDS= ... If you specify INTO &1 (8or5 area$/ the contents of the line are transported to data ob4ect &1. The data type of the data ob4ect must be compatible with the line type of the internal table. If you specify ASSIGNING T)AL (Aield Symbol$/ no values will be transported. Instead/ the field symbol is bound to the table line in memory after the assignment. In turn/ the table line can be evaluated or modified using T)AL. If you specify REFERENC INTO (' )/ no values will be transported either. Instead/ the data reference variable (' ) points to the table line the memory after the statement. The table line can be evaluated or modified using (' )-LK If you specify TRNASPORTING NO FIELDS/ you only fill the corresponding system fields. This addition is only possible/ if the addition WHERE is used simultaneously in the 9"7(?$?"7A.

Note: 2ield s%mbol (fs) is placeholder or s%mbolic name "or other "ields& *he% do not ph%sicall% reser$e space "or a "ield1 but point to its contents& "ield s%mbol can point to an% data ob)ect& *he data ob)ect to #hich a "ield s%mbol points is assigned to it a"ter it has been declared in the program& >ou must assign a "ield to each "ield s%mbol be"ore %ou can address the latter in programs& 2ield s%mbols are similar to dere"erenced pointers in 9& To limit the rows in the output the 9"7(?$?"7A given below can be used: ... 6FROM ?7( >-8 6TO ?7( >.8 6WHERE !"B_ >58. If FROM ?7( >- is specified/ lines starting from table inde- ?7( >- will be accepted. Aor ?7( >- data ob4ect of type ? is e-pected. If value of ?7( >- is "

smaller or eBual to #/ then it will be set to . If the value is larger than the number of table rows/ the loop is not passed through. FROM ?7( >- is only possible with standard and sorted tables. If TO ?7( >. is specified/ lines after table inde- ?7( >. will be accepted. Aor ?7( >. data ob4ect of type ? is e-pected. If value of ?7( >. is smaller or eBual to #/ then the loop will not be passed. If the value is larger than the number of table rows/ the value will be set to the number of rows. If inde-, is smaller than inde- then the loop is not passed as well. TO ?7( >. is only possible with standard and sorted tables. If WHERE !"B_ >5 is specified/ lines fulfilling the !"B_ >5 will be accepted. Airst operand of any comparison will be component of an internal table. WHERE !"B_ >5 is possible with all table types.

3ode below shows an e-ample of LOOP AT loop.

The above listing produces the following output.

S%#%C$ #oop
The SELECT loop reads several entries of a database table in succession. Aollowing is the synta- of SELECT loop. SELECT ' AD!$ FROM (2$12;(2:? & INTO 6CORRESPONDING FIELDS OF8 &"'W_1' 1;O("23-,("23.,...P8; INTO;APPENDING 6CORRESPONDING FIELDS OF8 TABLE ?$12 WHERE 9"7(?$?"7A8. A$1$ @ 7$_2!"9W ENDSELECT. The ' AD!$ defines whether the resulting set consists of multiple rows (table&li5e structure$ or a single row (flat structure$. It specifies the columns to be read and defines their names in the resulting set. The 9"7(?$?"7A addition restricts the number of lines.

,#

Aor every loop pass/ the SELECT statement assigns a row to the data ob4ects specified in INTO addition. If the last row was assigned or if the result set is empty/ then SELECT branches to ENDSELECT. 8e can end the loop using the statement such as EXIT. The SELECT statement sets A4-AD2'9 to # for every pass by value to an ABAP data ob4ect and to 1 if the result set is empty. After every value that is transferred to an ABAP data ob4ect/ the SELECT statement sets A4-(297$ to the number of rows that were transferred. If the result set is empty/ A4-(297$ is set to #. The following listing shows an e-ample of SELECT loop.

,,

After selecting %9ew Lor5( on the selection screen/ the following out put is produced.

,0

*iel! S"mbols
Aield symbols are placeholders or symbolic names for other fields. They do not physically reserve space for a field/ but point to its contents. A field symbol can point to any data ob4ect. The data ob4ect to which a field symbol points is assigned to ( ASSIGN$ it after it has been declared in the program. After its declaration/ a field symbol is initial & that is/ it does not reference a memory area. After successful assignment/ there is no difference in ABAP whether you reference the field symbol or the field itself. Aield symbols are similar to dereferenced pointers in 3 (M5$'$. Aield symbols can also be compared to a data reference variable that is dereferenced with -LM. All operations programmed with field symbols are applied to the field assigned to it. 8e can declare field symbol as: FIELD-SYMBOLS TFSL 6TYPE $45 ;LIKE ("238. The FIELD-SYMBOLS statement is used to declare the field symbols. Aor field symbols/ the angle brac5ets are part of the synta-. They identify field symbols in the program code. The TYPE addition allows you to specify the type of a field symbol. If you do not specify any additions/ the field symbol TFSL can have data ob4ects of any type assigned to it. 8hen you assign a data ob4ect/ the field symbol inherits its technical attributes. The data type of the assigned data ob4ect becomes the actual data type of the field symbol. Aield symbols allow wor5ing generically with data ob4ects/ that is/ we can program operations without 5nowing the data ob4ects with which the program will actually wor5 at runtime. Secondly/ we can use field symbols for the casting of data ob4ects. The following listing demonstrates the field symbols.

,1

The above code produces the following code.

,D

Static Assignment an! Sub iel! A!!ressing


If the name of the data ob4ect that is being assigned to the field symbol is already 5nown when the program is created it is referred as static assignment. ;uring static assignment not only we can assign entire data ob4ects to a field symbol/ but also we can assign subfields of byte or character type data ob4ects which we specify using the offset and length specifications. The synta- is: ASSIGN ("236,"))A $86O! 7B$%P8 TO T)AL. 2isting below demonstrate the use of subfield addressing.

After e-ecuting the above code the following out put is produced.

,G

D"namic Assignment
If the name of the data ob4ect that we want to assign to a field symbol is not 5nown until runtime/ we can use the following variant of the ASSIGN statement: ASSIGN O71@ P TO T)AL. As a result of using the above statement/ the data ob4ect whose name is contained in the name field in brac5ets is assigned to the field symbol T)AL. After dynamic assignment/ we must always chec5 A4-AD2'9 before we access the field symbol. If the assignment is successful/ A4-AD2'9 is set to #/ if no data ob4ect with the right name is found there is no assignment to the field symbol and A4-AD2'9 is set to the value 1. In the e-ample in listing below in @1?7 method we dynamically access the attribute 1$$' of the class !9!_9!A. Cere both the name of the class and the name of the attribute are given in the character type fields 1$$'_71@ and 9!A_71@ .

,"

The above code produces the following output.

Component Assignment

$o !"namicall" a!!ress the components o structure= use the ollo(ing variant o ASSIGN statement)

,.

ASSI1N C-MP-N%N$ comp -* S$'7C$7'% struct $- E sF) I 9"@5 is a !ata ob.ect o the t"pe 9 or A$'?7B= its content is interprete! as the name o the component) I the 9"@5 has a !i erent t"pe an! i the content is a number= this speci ies the number o the component) In the eAample belo( the iel! s"mbol T)-L points to the structure A$'D9$= T).L points to the iel! 9"@5) In the DO loop the components o A$'D9$ are speci ie! b" their numbers an! assigne! one b" one to T)/L) A ter the loop the component 9"!/ o A$'D9$ is speci ie! b" its name an! assigne! to T)/L) Note= eApressions such as T)-L-9"!- are s"ntacticall" incorrect)

,!

$he above co!e pro!uces the ollo(ing output)

0#

Increment Assignment

It is possible (ithin a structure to incrementall" access sub iel!s o the structure) *ollo(ing is the s"ntaA or increment assignment) ASSI1N !ob. INC'%M%N$ inc $- E sF G'AN1% rangeH) A memor" area is assigne! to the iel! s"mbol that is eAactl" as long as the !ata ob.ect ("23 an! is o set ?79 times this length o ("23) With RANGE= (e can speci " the area (ithin (hich an assignment is possible) 8ere= '17B is a !ata ob.ect that comprises the subareas) Without speci "ing RANGE= (e can onl" access the memor" area (ithin ("23 itsel ) $he eAample in listing belo( sho(s ho( (ithin a character-t"pe structure $>$= starting rom the t(o-character component 9"@5-= sub iel!s o the component 9"@5. are accesse! that are .ust as long)

The above code produces the following output.

0,

Casting $"pe in Assignment


8hen we assign data ob4ects to field symbols/ a cast can be performed on any data types. This means that the assigned memory area can be handled assuming a particular type. The addition CASTING allows to assign data ob4ects to field symbols whose type is not compatible with the typing of the field symbol. 8ithout e-plicit casting with the addition CASTING/ the field symbol always ta5es over the type of the specified data ob4ect/ which must then be compatible with the typing of the field symbol. If the field symbol is typed either fully or with one of the built&in generic ABAP types 9/ 7/ 5 or > (Implicit Type Specification$/ the following form of the ASSIGN statement can be used: ASSIGN ("23 TO T)AL CASTING. The assigned memory area is cast to the type of the field symbol. The listing given below the content of the character&type system field A4-(1$D@ is interpreted as a structure.

00

The above coding produces the following output.

If the field symbol is typed generically/ rather than completely (=-plicit Type Specification$/ we can use the following form of ASSIGN statement. ASSIGN ) TO T)AL CASTING TYPE $45;O7 @1 P ; LIKE ("23 ; TYPE HANDLE %17(! '. Behind TYPE/ we can specify a name of a data ob4ect enclosed in round brac5etsK this then specifies the data type dynamically. The TYPE HANDLE addition specify a reference to a type ob4ect of the *un Time Type Services (*TTS$/ which allows an entirely dynamic casting/ because such a type ob4ect can be created through the definition of a new data type. The specified data type must be compatible with the generic typing of the field symbol. It can preserve or speciali'e the generic typing but it can not overwrite an already 5nown technical property of the field symbol. The e-plicit type specification is forbidden for a fully typed field symbol. 2isting below shows an e-ample in which the numerical content of a te-t field is interpreted once as a date and once as a number value. The interpretation occurs when the field symbol is assigned to an integer field/ where the data type of the field symbol determines the conversion rule.

01

The above coding produces the following output.

0D

Note: /e can use the $fs% I& #&&IGNED to check #hether a data ob)ect is assigned to a "ield s%mbol& *he e:pression #ill be true i" the "ield s%mbol $fs% points to a data ob)ect& /hile #e can us the 'N#&&IGN $fs% statement to ensure that no more data ob)ects are assigned to a "ield s%mbol& +n the other hand1 the C(E#) $fs% statement doesn?t mean that the "ield s%mbol #ill be initialized1 but rather the memor% area that #as assigned to the "ield s%mbol&

0G

Internal $ables
The data ob4ects of table types are internal tables. Internal tables allow storing a variable amount of data of a fi-ed structure in the memory and enable to efficiently use this data. In ABAP/ internal tables fulfill the function of arrays. 8e can use internal tables whenever we want to process a dataset with a fi-ed structure within a program. A particularly important use for internal tables is for storing and formatting data from a database table within a program. 8e can use internal tables to perform table calculations on subsets of database tables. Aor e-ample/ you can read a certain part of a database table into an internal table. Arom the internal table/ you can then calculate totals or generate a ran5ed list. 2i5e all elements in the ABAP type concept/ internal tables can e-ist both as data types and as data ob4ects. Internal tables are implicitly managed by the runtime environment. ABAP contains a set of special/ highly optimi'ed statements that we can use when wor5ing with internal tables. The following synta- can be used to declare the internal tables. DATA $12_71@ TYPE;LIKE STANDARD;SORTED;HASHED TABLE OF (1$1_$45 ;(1$1_"23 9$ WITH 6NON-8UNIQUE KEY 9"!-K 9"!7 6INITIAL SINE 78. TYPES $12_71@ TYPE STANDARD;SORTED;HASHED TABLE OF (1$1_$45 WITH 6NON-8UNIQUE KEY 9"!-K9"!7 6INITIAL SINE 78. Internal tables are stored in individual bloc5s in the memory. The [ INITIAL SINE 78 addition enables to specify initially reBuired number of table lines 7. It is recommended that specify initial memory reBuirement only when the number of entries in table is already 5nown. This can be particularly important for internal tables that are themselves components of tables and contain only a few lines. Internal tables contain three essential attributes: *ow+2ine Type/ Table 3ategory and Table Oey.

'o(@#ine $"pe
The line type of an internal table can be any data type. The data type of an internal table is normally a structure. =ach component of the structure is a column in the internal table. Cowever/ the line type may also be elementary or another internal table.

$able Categor"

0"

The table category determines the way an internal table is internally managed and the way in which it is accessed within the ABAP program. It doesnEt affect an access to entire table/ as it occurs for instance in assignment and comparisons. There are three categories of internal tables.

STANDARD $able: is managed internally by a table inde-. Access is possible via table inde- or table 5ey. 8ith a 5ey access/ the response time is directly dependent on the number of table entries. The 5ey of a standard table is always non&uniBue. This table category is suited best whenever the individual entries can be accessed using the inde-. A table inde- numbers the lines from to the e-isting number of lines. The system field A4-$12?> is always filled with the inde- of the line that is addressed. SORTED $able: is managed internally by means of a table inde-/ too. They are always sorted by the table 5ey and can be accessed via the table inde- or the table 5ey. 8ith a 5ey access/ the response time is logarithmically dependent on the number of table entries/ because the table is accessed via a binary search. The 5ey of sorted tables can be uniBue or non&uniBue. This table category is suited whenever the table must already be sorted when it is filled. The system field A4$12?> is always filled with the inde- of the line that is addressed. HASHED $able: is managed internally by a hash algorithm. Cashed tables can be accessed only via the table 5ey. The response time is constant/ independent of the number of table entries. The 5ey of hashed tables is always uniBue. This table category is suited whenever the 5ey accesses represent the central operation on the table entries.

8hich table category to use depends upon the type of operations you want to perform on the table and how often you want to access the table in your programV Standard tables are the most appropriate type if you are going to address the individual table entries using the inde-. Inde- access is the Buic5est possible access. Lou should fill a standard table by appending lines (APPEND statement$/ and read/ modify and delete entries by specifying the inde- (INDEX option with the relevant ABAP command$. The access time for a standard table increases in a linear relationship with the number of table entries. If you need 5ey access/ standard tables are particularly useful if you can fill and process the table in separate steps. Aor e-ample/ you could fill the table by appending entries/ and then sort it. If you use the binary search option with 5ey access/ the response time is logarithmically proportional to the number of table entries. 8e should avoid using large standard tables of more than ## lines because of the linear search process. Sorted tables are useful if both a fast 5ey access and an inde- access are necessary and if the lines should already be sorted during the filling of the table. Lou fill sorted tables using the INSERT statement. =ntries are inserted according to the sort seBuence defined through the table 5ey. Any illegal entries are recogni'ed as soon as you try to add them to the table. The response time for 5ey access is logarithmically proportional to the number of table entries/ since the system 0.

always uses a binary search. Sorted tables are particularly useful for partially seBuential processing in a LOOP if you specify the beginning of the table 5ey in the WHERE condition. Cashed tables are the most appropriate type for any table where the main operation is 5ey access. Lou cannot access a hashed table using its inde-. The response time for 5ey access remains constant/ regardless of the number of table entries. 2i5e database tables/ hashed tables always have a uniBue 5ey. Cashed tables are useful if you want to construct and use an internal table which resembles a database table or for processing large amounts of data.

$able Ie"
The table 5ey identifies table rows. There are two 5inds of 5ey for internal tables & the standard 5ey or default 5ey and a user&defined 5ey. The 5ey should be UNIQUE or NONUNIQUE. Aor all table categories/ we can specify one of the following 5ey definitions during the declaration: If a table has a structured line type/ its default 5ey consists of all of its non& numerical (?/)/5$ columns+components that are not references or themselves internal tables. If a table has an elementary line type/ the default 5ey is the entire line (pseudo& component $12! _!?7 / the entire line of the internal table is interpreted as the only component.$. If a table has an internal table line type/ the default 5ey is empty.

The user&defined 5ey can contain any columns+components of the internal table that are not references or themselves internal tables. Internal tables with a user&defined 5ey are called 5ey tables. 8hen you define the 5ey/ the seBuence of the 5ey fields is significant. Lou should remember this/ for e-ample/ if you intend to sort the table according to the 5ey.

Wor+ing (ith Internal $ables


8hen wor5ing with internal tables/ we must distinguish between the access to single lines and the access to the entire table.

Processing Single #ines


8hen wor5ing with single table lines/ we must distinguish between the operators that are possible for all table types/ and those that are only possible with inde- tables. Indetables (standard and sorted tables$ have an internal inde-/ ma5ing linear access possible. Cashed tables have no linear inde-. 3onseBuently/ only 5ey access is possible. The operations that are permitted for all table types do not use inde-es.

0!

The statements used to access lines of any type of table differ from those used to access inde- tables mainly through the TABLE addition following the corresponding 5eyword. Aor e-ample/ you would use MODIFY to change lines in inde- tables/ but MODIFY TABLE to change lines in any type of table. There are three ways to access a single table entry: Access 7sing a 8or5 Area/ Access 7sing Aield Symbols and Access via ;ata *eferences. Access 7sing a Wor+ Area: 8hen we access individual table entries using a wor5 area/ we are not wor5ing directly with the data in the table. Instead/ we wor5 with another data ob4ect as a wor5 area. The wor5 area is an interface to the entries in the internal table/ and must be convertible into the line type of the internal table. 8hen we read data from a table record/ the data you are reading overwrites the current contents of the wor5 area. Lou can then use this data in the program. 8hen you write data to the internal table/ this must first be placed in the wor5 area. The system then transfers it from the wor5 area to the appropriate table entry. Access 7sing *iel! S"mbols: 8hen we access an internal table using a field symbol / we do not need to copy the data into a wor5 area. 8e can assign a line of an internal table to a field symbol. Ideally/ the field symbol will have the same type as the line type of the internal table. 6nce you have assigned the entry to the field symbol/ wor5ing with the field symbol has e-actly the same effect as accessing the corresponding line directly. Access via Data 'e erences: 8hen we access an internal table using a data reference/ we do not need to copy the data into a wor5 area. 8e can assign a line of an internal table to a data reference. Ideally/ the data reference will have the same type as the line type of the internal table. 6nce we have assigned the entry to the field symbol/ wor5ing with the dereferenced data reference has e-actly the same effect as accessing the corresponding line directly. Inserting 'o(s To fill an internal table with lines/ we must us the INSERT statement as: INSERT <&1;INITIAL LINE;LINES OF $12_71@ 6FROM ?(>-8 6TO ?(>.8= INTO <TABLE ?$12_71@ ; ?$12_71@ 6?7( > ?(>8= 6ASSIGNING T)AL 6CASTING8 ; REFERENCE INTO (' )8. The &1 represents the wor5 area/ a new line is generated and filled with the contents of &1. &1 must be compatible with the line type of the internal table when you insert the lines or wor5 area using the table 5ey. The INITIAL LINE statement represents a new line in which each component contains the type&specific initial value. The LINES OF $12_71@ 6)'"@ ?( >-8 6TO ?(>.8 specify the internal table from where the lines are inserted one after another according to the same rules as for the insertion of a wor5 area. The line types of both ?$12_71@ and $12_71@ must be compatible. If

1#

$12_71@ is an inde- table/ you can specify FROM ?(>- and TO ?(>. to restrict the lines to be inserted. The addition TABLE specifies the position at which the line is inserted/ which is specified using the table 5ey. If we use the addition INDEX/ the table inde- is used for the specification. The INDEX option can only be used for inde- tables. Aor standard tables/ each new line is appended as the last line in the internal table regardless of the table 5ey and the table inde- of the following lines is increased by one. Aor sorted tables/ each new line is inserted into the sort order of the internal table according to its 5ey values. If the internal table does not have a uniBue 5ey/ duplicate entries are inserted before the e-isting line. Aor hashed tables/ each new line is inserted into the internal table by the hash administration according to its 5ey values.

The additions ASSIGNING T)AL 6CASTING8 ; REFERENCE INTO (' ) can only be used when inserting single lines. If they are inserted successfully/ the inserted line is assigned to a field symbol T)AL or a reference is set to the inserted line in the reference variable. 6n successful e-ecution the system field A4-AD2'9 is set to # or to 1 on failure. =-ample below demonstrates the use of the INSERT statement.
*E"+*T ,_it&_insert.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. "declare line types .-T-4 int T5"E i, dref T5"E *E/ T+ i. "declare internal tables .-T-4 int_ta& I6E ST-N.-*. T-1 E +/ int, ref_ta& I6E 3-S3E. T-1 E +/ dref 7IT3 0NIQ0E 6E5 ta&le_line. .+ 8 TI2ES. "insert table index in standard table "and set the reference of inserted line "into dref reference variable INSE*T s%-index INT+ int_ta& IN.E9 : *E/E*EN!E INT+ dref.

"now insert the references to lines "in hashed table using the table key INSE*T dref INT+ T-1 E ref_ta&. EN..+. "print out the contents of standard table 7*ITE ;!ontnets of Standard Ta&le;. "output blank line S6I". ++" -T int_ta& INT+ int. 7*ITE4 int, space. EN. ++". S6I" <. "print out the contents of hashed table "using derefernce operator 7*ITE ;!ontnets of 3as$ed Ta&le;. S6I". ++" -T ref_ta& INT+ dref. 7*ITE4 dref->=, space. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

The above coding produces the following output.

In the following e-ample a structure is used as a line type.


*E"+*T ,_it&_insertA<.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS.

1,

! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line, id T5"E na#e T5"E a)e T5"E 'ei)$t T5"E EN. +/ line. .-T- ita& i, c ENGT3 :A, i, p .E!I2- S <,

I6E S+*TE. T-1 E +/ line 7IT3 0NIQ0E 6E5 id. line-na#e > ;-s)$ar;. line-'ei)$t > ;BA.AA;.

line-id > :. line-a)e > <A.

INSE*T line INT+ T-1 E ita&. line-id > <. line-a)e > :B. line-na#e > ;Sali#;. line-'ei)$t > ;CD.<E;.

INSE*T line INT+ T-1 E ita&. line-id > E. line-a)e > :8. line-na#e > ;-F#al;. line-'ei)$t > ;B<.AA;.

INSE*T line INT+ T-1 E ita&. line-id > G. line-a)e > :A. line-na#e > ;S$u#ila;. line-'ei)$t > ;EG.AA;.

INSE*T line INT+ T-1 E ita&. line-id > 8. line-a)e > :D. line-na#e > ;3a#ad;. line-'ei)$t > ;DC.AA;.

INSE*T line INT+ T-1 E ita&. 7*ITE4 ; ; ; I.;, ;Na#e;, -)e;, 7ei)$t;.

S6I" :. ++" -T ita& INT+ line. 7*ITE4 H line-id, line-na#e, line-a)e, line-'ei)$t. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

10

The above listing produces the following output.

The e-ample below creates two internal tables with the same line type but different table types. =ach is filled with three lines. Then/ ?$12 is sorted into sorted table 3$12.
*E"+*T ,_it&_insertAE.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ ro', col: T5"E c col< T5"E c EN. +/ ro'. .-T- ita& .-T- Fta& ENGT3 :A, ENGT3 :A,

I6E ST-N.-*. T-1 E +/ ro'. I6E S+*TE. T-1 E +/ ro' 7IT3 N+N-0NIQ0E 6E5 col: col<.

ro'-col: > ;-s)$ar;. ro'-col< > ;2S-IT;. INSE*T ro' INT+ T-1 E ita&. ro'-col: > ;Salee#;. ro'-col< > ;1!S;. INSE*T ro' INT+ T-1 E ita&. ro'-col: > ;-F#al;. ro'-col< > ;/-;. INSE*T ro' INT+ T-1 E ita&. INSE*T INES +/ ita& INT+ T-1 E Fta&.

7*ITE4 ;Ta&le Index;, ; !ol:;, ; !ol<;. 7*ITE4 H ;---------------------------------;. ++" -T Fta& INT+ ro'. 7*ITE4 H s%-ta&ix, ; ;,

11

ro'-col:, ro'-col<. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

The above listing produces the following output.

Inserting Aggregate! 'o(s The COLLECT statement is specifically used for totaling numeric values that belong to uniBue 5eys. 8hen the line is inserted/ the system chec5s whether there is already a table entry that matches the 5ey. If there is no corresponding entry already in the table/ the COLLECT statement has the same effect as inserting the new line. If an entry with the same 5ey already e-ists/ the COLLECT statement does not append a new line/ but adds the contents of the numeric fields in the wor5 area to the contents of the numeric fields in the e-isting entry. Aollowing is the synta- of the COLLECT statement. COLLECT &1 INTO ?$12 6ASSIGNING T)AL 6CASTING8 ; REFERENCE INTO (' )8. The statement inserts the contents of a wor5 area &1 either as single row into an internal table ?$12 or adds the values of its numeric components to the corresponding values of e-isting rows with the same 5ey. The &1 must be compatible with the row type of ?$12 and all components that are not part of the table 5ey must have a numeric data type ( ?/ 5/ )$. The COLLECT statement is primarily used for hashed tables. In contrast/ its use for standard tables is error&prone and obsolete. The e-ample below demonstrates COLLECT statement.
*E"+*T ,_it&_collectA:.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS.

1D

! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line, col: T5"E c ENGT3 E, col< T5"E n ENGT3 <, colE T5"E i, EN. +/ line. .-T- ita& I6E S+*TE. T-1 E +/ line 7IT3 N+N-0NIQ0E 6E5 col: col<.

line-col: > ;a&c;. line-col< > ;:<;. line-colE > E. !+ E!T line INT+ ita&. 7*ITE4 ;s%-ta&ix4 ;, s%-ta&ix. line-col: > ;def;. line-col< > ;EG;. line-colE > 8. !+ E!T line INT+ ita&. 7*ITE4 H ;s%-ta&ix4 ;, s%-ta&ix. line-col: > ;a&c;. line-col< > ;:<;. line-colE > C. !+ E!T line INT+ ita&. 7*ITE4 H ;s%-ta&ix4 ;, s%-ta&ix. 7*ITE H ;------------------------------;. ++" -T ita& INT+ line. 7*ITE4 H line-col:, line-col<, line-colE. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

The e-ample fills a sorted table. The first two COLLECT statements wor5 li5e normal insertion statements. In the third COLLECT statement/ the first line of ?$12 is modified. The following diagram shows the three steps:

1G

In the e-ample below compressed insertion of data from the database table A)!?B%$ into the internal table A 1$A_$12. The rows in which the 5ey components 91''?( and 9"77?( are identical are compressed by adding the number of occupied seats to numeric component A 1$A"99.
*E"+*T ,_it&_collectA<.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ seats, carrid T5"E sfli)$t-carrid, connid T5"E sfli)$t-connid, seatsocc T5"E sfli)$t-seatsocc, EN. +/ seats. .-T- seats_ta& I6E 3-S3E. T-1 E +/ seats 7IT3 0NIQ0E 6E5 carrid connid.

SE E!T carrid connid seatsocc /*+2 sfli)$t INT+ seats. !+ E!T seats INT+ seats_ta&. EN.SE E!T. 7*ITE4 ;-irline !ode;, ; /li)t !onnection No.;, ; +ccupied Seats in Econo#% !lass;. S6I". ++" -T seats_ta& INT+ seats.

1"

7*ITE4 H seats-carrid, ; seats-connid, ; seats-seatsocc. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

;, ;,

The above code produces the following output.

Appen!ing 'o(s The APPEND statement appends one or more rows to an internal inde- table (standard and sorted tables$ as last row(s$. Aollowing is the synta- of APPEND statement. APPEND <&1;INITIAL LINE;LINES OF $12_71@ ?(>.8= 6FROM ?(>-8 6TO

1.

TO ?$12 6SORTED BY 9"@58 6ASSIGNING T)AL 6CASTING8;REFERENCE INTO (' )8. The SORTED BY addition is used to sort the table in a specified way. It is allowed only if you specify a wor5area &1 and if you use a standard table/ where &1 must be compatible to the row type of the table. This statement provides a convenient way to fill standard tables with lines. In standard tables/ rows are appended directly and without chec5ing the content of the internal table while in sorted tables/ rows are appended only if they correspond to the sort seBuence and do not create duplicate entries with uniBue table 5ey. 6therwise/ an untreatable e-ception is triggered. 9o rows can be appended in hashed tables. The APPEND statement sets A4-$12?> to the table inde- of the last appended row.
*E"+*T ,_it&_appendA:.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line:, col: T5"E c ENGT3 E, col< T5"E n ENGT3 <, colE T5"E i, EN. +/ line:. .-T- ta&: I6E T-1 E +/ line:.

.-T-4 1EGIN +/ line<, field: T5"E c ENGT3 :, field< I6E ta&:, EN. +/ line<. .-T- ta&< I6E T-1 E +/ line<.

line:-col: > ;a&c;. line:-col< > ;:;. line:-colE > :A. -""EN. line: T+ ta&:. line:-col: > ;def;. line:-col< > ;<;. line:-colE > ::. -""EN. line: T+ ta&:. line<-field: > ;-1!;. line<-field< > ta&:. -""EN. line< T+ ta&<. "Deletes all rows of the internal table, the memory space "required for the table is freed up to the initial memory "size INI I!" #I$% *E/*ES3 ta&:. line:-col: > ;)$i;. line:-col< > ;E;. line:-colE > :<.

1!

-""EN. line: T+ ta&:. line:-col: > ;F(l;. line:-col< > ;G;. line:-colE > :E. -""EN. line: T+ ta&:. line<-field: > ;.E/;. line<-field< > ta&:. -""EN. line< T+ ta&<. "note the use of nested loop ++" -T ta&< INT+ line<. 7*ITE4 H ;ta&<-field: > ;, line<-field:. 7*ITE H ;ta&<-field< > ;. ++" -T line<-field< INT+ line:. 7*ITE4 EN. ++". S6I". EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @. H ; ;, line:-col:, line:-col<, line:-colE.

The e-ample above creates two internal tables $12- and $12.. $12. has a deep structure because the second component of !?7 . has the data type of internal table $12-. !?7 - is filled and appended to $12-. Then/ !?7 . is filled and appended to $12.. After clearing $12- with the REFRESH statement/ the same procedure is repeated. Aollowing is the output of the above e-ample.

D#

This e-ample below creates two internal tables of the same type/ ?$12 and 3$12. In the DO loop/ ?$12 is filled with a list of sBuare numbers/ and 3$12 with a list of cube numbers. Then/ the last two lines of 3$12 are appended to ?$12.
*E"+*T ,_it&_appendA<.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line, col: T5"E c ENGT3 :, col< T5"E i, EN. +/ line. .-T-4 ita& Fta& .+ E TI2ES. line-col: > s%-index. line-col< > s%-index == <. -""EN. line T+ ita&. line-col: > s%-index. line-col< > s%-index == E. -""EN. line T+ Fta&. EN..+. -""EN. INES +/ Fta& /*+2 < T+ E T+ ita&. SIrH!u&e;. I6E T-1 E +/ line, I6E ita&.

7*ITE4 ;Index;, ;

++" -T ita& INT+ line. 7*ITE4 H line-col:, line-col<. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

The above listing produces the following output.

The program below inserts three lines into the internal table ?$12 using the APPEND statement and the SORTED BY addition. The line with the smallest value for the field COL. is deleted from the table/ since the number of lines that can be appended is fi-ed to , through the INITIAL SINE addition.
*E"+*T ,_it&_appendAE.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line, col: T5"E i, col< T5"E i, colE T5"E i, EN. +/ line. .-T- ita& I6E T-1 E +/ line INITISIJE <.

line-col: > ::. line-col< > <<. line-colE > 88. -""EN. line T+ ita& S+*TE. 15 col<. line-col: > :<. line-col< > <E. line-colE > 8D. -""EN. line T+ ita& S+*TE. 15 col<. line-col: > :E. line-col< > <G. line-colE > 8C. -""EN. line T+ ita& S+*TE. 15 col<. 7*ITE4 ; ; S6I". ++" -T ita& INT+ line. !ol:;, ; !olE;. !ol<;,

D,

7*ITE4 H line-col:, line-col<, line-colE. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output of the above program.

'ea!ing 'o(s To read the contents of individual rows from an internal table/ we can use the READ TABLE statement. The synta- for READ statement is as follows: READ TABLE ?$12 <FROM &1;WITH TABLE KEY 9"@5-+("23- K 9"@57+("237=; <WITH KEY 9"@5-+("23- K 9"@57+("237 6BINARY SEARCH8=; <INDEX ?(>= INTO <&16COMPARING 9"@5- K 9"@57;TRANSPORTING 9"@5- K 9"@578;ASSIGNING T)AL 6CASTING8;REFERENCE INTO (' )=; <TRANSPORTING NO FIELDS=. The values of the search 5ey can be specified either implicitly in a wor5 area &1 after FROM/ or by e-plicitly listing the components of the table ke% after TABLE KEY. The wor5 area &1 must be a data ob4ect that is compatible with the line type of the internal table. The ("23 data ob4ect in TABLE KEY must be compatible with the line type of the internal table. Cere the standard table is searched using linear search/ sorted table is searched using binary search and hashed tables are searched based on hash algorithm. If we donEt use the TABLE addition before KEY/ we can use any component 9"@5 of the internal table as search 5eys ("ree ke%$. If the addition BINARY SEARCH is specified/ the search is binary instead of linear for standard table. It can be specified for sorted tables/

D0

but has no effect on sorted tables. The addition BINARY SEARCH is not permitted for hashed tables. In standard tables and sorted tables/ the table inde- of the row to be read can be specified e-plicitly in ?(>. Aor ?(>/ a data ob4ect of type ? is e-pected. If the value of ?(> is smaller than or eBual to #/ or greater than the number of rows in the table/ no line is read and A4-AD2'9 is set to 1. The content of the found line is assigned to the wor5 area &1. The addition COMPARING compares the specified components 9"@5- K 9"@57 in a found line before they are transported with the corresponding components of the wor5 area. If the addition TRANSPORTING is specified/ only the specified components 9"@5- K 9"@57 in the found line are assigned to the corresponding components of the wor5 area. COMPARING must be specified before TRANSPORTING. 8hen the addition TRANSPORTING NO FIELDS is used/ the statement READ TABLE only chec5s whether the line that is being searched for e-ists/ and fills the system field A4-AD2'9 and A4-$12?>. The system can then no longer access the content of the found fields. The program below fills a sorted table with a list of sBuare numbers. The READ statement reads the line of the table in which the 5ey field 9"!- has the same value as in the wor5 area and copies it into the wor5 area. 6nly the contents of 9"!. are copied into the wor5 area LINE. SY-SUBRC is 'ero/ and SY-TABIX is 0/ because ?$12 is an inde- table.
*E"+*T ,_it&_readA:. ! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line, col: T5"E i, col< T5"E i, EN. +/ line. .-T- ita& I6E S+*TE. T-1 E +/ line 7IT3 0NIQ0E 6E5 col:.

.+ G TI2ES. line-col: > s%-index. line-col< > s%-index == <. INSE*T line INT+ T-1 E ita&. EN..+. "sets the line components to initail values

D1

! E-* line. 7*ITE4 ; line-col:;, ; line-col<;. 7*ITE H;---------------------------;. ++" -T ita& INT+ line. 7*ITE4 H line-col:, line-col<. EN. ++". S6I". ! E-* line. *E-. T-1 E ita& 7IT3 T-1 E 6E5 col: > E INT+ line T*-NS"+*TING col<. 7*ITE ;Kalue read 'it$ (e% > E;. S6I". 7*ITE4 ; line-col:;, ; line-col<;. 7*ITE H;---------------------------;. 7*ITE4 H line-col:, line-col<. EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

The above program produces the following output.

The e-ample below reads the first ten lines of the internal table A)!?B%$_$12 using the inde-.
*E"+*T ,_it&_readA<.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain.

DD

EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. "sflight is a flight details table in "abap dictionary .-T- sfli)$t_ta& T5"E S+*TE. T-1 E +/ sfli)$t 7IT3 N+N-0NIQ0E 6E5 seatsocc. "declare line work area, that will hold "one row at a time .-T- sfli)$t_'a I6E INE +/ sfli)$t_ta&. SE E!T = /*+2 sfli)$t INT+ T-1 E sfli)$t_ta& 73E*E carrid > ; 3; -N. connid > ;GAA;. 7*ITE4 ;-irlineI.;, ; !on No;, ; /li)$t .ate;, ; T%pe;, ; !urrenc%;,; /are;. 7*ITE4 H ;-------------------------------------------------------------------------------;. .+ :A TI2ES. *E-. T-1 E sfli)$t_ta& IN.E9 s%-index INT+ sfli)$t_'a. I/ s%-su&rc <> A. E9IT. E SE. 7*ITE4 H sfli)$t_'a-carrid, ; sfli)$t_'a-connid, ; ;, sfli)$t_'a-fldate, ; ;, sfli)$t_'a-planet%pe, ; ;, sfli)$t_'a-currenc%, sfli)$t_'a-price. EN.I/. EN..+. EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

;,

Aollowing is the output.

DG

In the third e-ample the READ statement uses a WHILE loop to read all lines of the table A)!?B%$_$12 one after the other using the table inde- in the wor5 area A)!?B%$_&1. 7sing the COMPARING addition/ all flights are selected in which no seats have yet been boo5ed.
*E"+*T ,_it&_readAE.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T- sfli)$t_ta& T5"E S+*TE. T-1 E +/ sfli)$t 7IT3 0NIQ0E 6E5 carrid connid fldate. .-T- sfli)$t_'a I6E INE +/ sfli)$t_ta&. .-T- su&rc T5"E s%-su&rc. SE E!T = /*+2 sfli)$t INT+ T-1 E sfli)$t_ta& 73E*E carrid > ; 3;. su&rc > s%-su&rc. 7*ITE4 ;-irlineI.;, ; !on No;, ; /li)$t .ate;, ; +ccupied Seats;. 7*ITE4 H ;-------------------------------------------------------;. 73I E su&rc > A. sfli)$t_'a-seatsocc > A.

D"

*E-. T-1 E sfli)$t_ta& IN.E9 s%-index INT+ sfli)$t_'a !+2"-*ING seatsocc T*-NS"+*TING carrid connid fldate seatsocc. !-SE s%-su&rc. 73EN A. "&'"'( addition change the background color of "output of the current )(I % statement 7*ITE4 H sfli)$t_'a-carrid, ; ;, sfli)$t_'a-connid, ; ;, sfli)$t_'a-fldate, ; ;, sfli)$t_'a-seatsocc !+ +* > D. su&rc > s%-su&rc. 73EN <. 7*ITE4 H sfli)$t_'a-carrid, ; ;, sfli)$t_'a-connid, ; ;, sfli)$t_'a-fldate, ; ;, sfli)$t_'a-seatsocc !+ +* > 8. su&rc > A. 73EN G +* B. E9IT. EN.!-SE. EN.73I E. EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the screen shot of the output.

D.

The program below fills a hashed table with a list of sBuare numbers. The READ statement reads the line of the table in which the 5ey field 9"!- has the value , and assigns it to the field symbol TFSL. The program then assigns the value ## to component 9"!. of TFSL. This also changes the corresponding table field.
*E"+*T ,_it&_readAG.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain.

D!

.-T-4 1EGIN +/ line, col: T5"E i, col< T5"E i, EN. +/ line. .-T- ita& I6E 3-S3E. T-1 E +/ line 7IT3 0NIQ0E 6E5 col:. I6E INE +/ ita&.

/IE .-S521+ S <fs>

.+ G TI2ES. line-col: > s%-index. line-col< > s%-index == <. INSE*T line INT+ T-1 E ita&. EN..+. 7*ITE4 ; line-col:;, ; line-col<;. 7*ITE H;------------------------;. ++" -T ita& INT+ line. 7*ITE4 H line-col:, line-col<. EN. ++". *E-. T-1 E ita& 7IT3 T-1 E 6E5 col: > < -SSIGNING <fs>. <fs>-col< > :AA. S6I". ++" -T ita& INT+ line. I/ line-col< > :AA. 7*ITE4 H line-col: !+ +* 8, line-col< !+ +* 8. E SE. 7*ITE4 H line-col:, line-col<. EN.I/. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output of the above e-ample.

G#

The following program chec5s whether a particular line e-ists in the internal table A)!?B%$_91''/ and assign the table inde- of the found line in A4-$12?> to ?(>.
*E"+*T ,_it&_readA8.

"*arameters are components of a selection screen that "are assigned a global elementary data ob+ect in program "and an input field on the selection screen, ! special "screen that can be defined without the use of the #creen "*ainter by using the statement like *!(!-% %(# "-*-2ETE*S p_carrid T5"E scarr-carrid. ! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T- scarr_ta& T5"E S+*TE. T-1 E +/ scarr 7IT3 0NIQ0E 6E5 carrid. .-T- idx T5"E i. "scarr table stores airline details SE E!T = /*+2 scarr INT+ T-1 E scarr_ta&. *E-. T-1 E scarr_ta& 7IT3 T-1 E 6E5 carrid > p_carrid T*-NS"+*TING N+ /IE .S. I/ s%-su&rc > A. idx > s%-ta&ix. EN.I/. 7*ITE4 ;Kalue find at ;, idx. EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is produce after e-ecution.

1se o( "OOP A& "oop The LOOP AT loop can be used to read rows from internal table seBuentially. The row that has been read is available in the statement bloc5 of the loop. The seBuence in which the table lines are read depends on the table category. Standard tables and sorted tables are read based on their ascending table inde-. The lines of hashed tables are read either in the seBuence in which they were inserted into the table or in the sort seBuence if they were sorted with the SORT statement. In inde- tables A4-$12?> is filled with the inde- of the current line in each loop pass. 6nce the loop has been completely processed/ A4-$12?> is assigned that value that it had prior to entering the loop. 8e insert lines behind the current lineK these new lines will be processed in the processed in the subseBuent loop passes. An endless loop can result. If we delete a line after the current line/ it will not be processed in a subseBuent loop pass. If we insert lines in front of the current line/ the internal loop counter is increased by one with each inserted line. If we delete a line before or at the current line/ the internal loop counter will be decreased accordingly. The A4-$12?> is affected in the subseBuent loop pass. 9ote/ statements such as CLEAR/ FREE/ REFRESH and SORT and all types of assignments to internal table are not allowed in classes. 3ontrol level processing is allowed within a LOOP AT over an internal table. This means that you can divide seBuences of entries into groups based on the contents of certain fields. Internal tables are divided into groups according to the seBuence of the fields in the line structure. The first column defines the highest control level and so on. The control level hierarchy must be 5nown when you create the internal table. The control levels are formed by sorting the internal table in the seBuence of its structure/ that is/ by the first field first/ then by the second field/ and so on. Tables in which the table 5ey occurs at the start of the table are particularly suitable for control level processing. The statements AT and ENDAT define statement bloc5s that are e-ecuted at control brea5s. 3ontrol brea5 is the change from one control level to another in the control level processing. The additions AT statements determine the control brea5 at which their statement bloc5s are e-ecuted. 8ithin these statement bloc5s/ the statement SUM can be specified to add together the numeric components of the control level. Statements in the LOOP-ENDLOOP control structure that are not e-ecuted within an AT-ENDAT control structure are e-ecuted in each pass of the loop. LOOP AT ?$12 INTO <&1;ASSIGNING;REFERENCE INTO (' ); TRANSPORTING NO FIELDS=. AT FIRST. ...... ENDAT. G,

AT NEW 9"@5-. ...... ENDAT. AT NEW 9"@5.. ...... ENDAT.


........................ TA?7B! _!?7 5'"9 AA?7BL

........................ AT END OF 9"@5.. ...... ENDAT. AT END OF 9"@5-. ......ENDAT.

AT LAST. ...... ENDAT. ENDLOOP. The innermost hierarchy level TA?7B! !?7 5'"9 AA?7BL processes the table lines that do not correspond to a control level change. Lou do not have to use all control level statements. But you must place the used ones in the above seBuence. Lou should not use control level statements in loops where the line selection is restricted by WHERE or FROM and TO. 9either should the table be modified during the loop. FIRST is used to define the control level by the first line of the internal table. The control brea5 ta5es place when this line is read. NEW defines the control levels by the beginning of a group of lines with the same content in the content 9"@5? and in the components to the left of 9"@5?. END OF defines the control levels by the end of a group of lines with the same content in the content 9"@5? and in the components to the left of 9"@5?. In both NEW and END OF the control brea5s ta5e place when the content of the component 9"@5? or another component to the left of 9"@5? changes. If a control level field 9"@5? is not 5nown until runtime/ you can specify it dynamically as O9"@5?P. LAST is used to define the control level by the last line of the internal table. The control brea5 ta5es place when the last line is read. Note: "ter (OOP1 a restricting condition can onl% be speci"ied i" this selects a consecuti$e line block o" the internal table& +ther#ise1 the beha$ior o" control le$el processing is unde"ined& If a wor5 area does not contain the current line in the AT ... ENDAT statement bloc5. All character fields to the right of the current group 5ey are filled with asteris5s (S$. All other fields to the right of the current group 5ey contain their initial value. In the program below in the LOOP - ENDLOOP bloc5/ the wor5 area LINE is output for each loop pass. The first field of the table 5ey/ 9"!-/ is used for control level processing. The total for all numeric fields is always calculated when the contents of 9"!- change and when the system is in the last loop pass.
*E"+*T ,_it&_loop.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N.

G0

! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line, col: T5"E c ENGT3 :, col< T5"E i, colE T5"E i, EN. +/ line. .-T- ita& I6E 3-S3E. T-1 E +/ line 7IT3 0NIQ0E 6E5 col: col<.

line-col: > ;-;. .+ E TI2ES. line-col< > s%-index. line-colE > s%-index = <. INSE*T line INT+ T-1 E ita&. EN..+. line-col: > ;1;. .+ E TI2ES. line-col< > s%-index. line-colE > s%-index = G. INSE*T line INT+ T-1 E ita&. EN..+. S+*T ita& 15 col: -S!EN.ING. 7*ITE4 ;!+ :;, ; !+ <;, ; "print horizontal line 0 INE. !+ E;.

++" -T ita& INT+ line. 7*ITE4 H line-col:, line-col<, line-colE. "&ontrol breaks when the contents .!, /0 "of col1 change -T EN. +/ col:. "sum up all numeric fields individually "for ! and / S02. 0 INE. 7*ITE4 H line-col: !+ +* D, line-col< !+ +* D, line-colE !+ +* D. 0 INE. S6I" <. EN.-T. "control breaks when last line is reached -T -ST. "sum up all numeric fields S02. 0 INE.

G1

7*ITE4 H line-col: !+ +* D, line-col< !+ +* D, line-colE !+ +* D. 0 INE. EN.-T. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output of the above program.

In this e-ample/ the sorted internal table ?$12 is filled with data from the database table A2""W using the 6pen SF2 statement SELECT. The seBuence of the columns in the internal table defines the control level hierarchy. Since the table 5ey is the entire line/ the sort seBuence and the control level hierarchy are the same. The seBuence of the ATENDAT bloc5s within the LOOP and ENDLOOP statements is important.
*E"+*T ,_it&_loopA<.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. "sbook is the flight booking table

GD

.-T-4 1EGIN +/ line, carrid T5"E connid T5"E fldate T5"E custt%pe T5"E class T5"E &oo(id T5"E EN. +/ line. .-T- ita&

s&oo(-carrid, s&oo(-connid, s&oo(-fldate, s&oo(-custt%pe, s&oo(-class, s&oo(-&oo(id,

I6E S+*TE. T-1 E +/ line 7IT3 0NIQ0E 6E5 ta&le_line.

SE E!T carrid connid fldate custt%pe class &oo(id /*+2 s&oo( INT+ !+**ES"+N.ING /IE .S +/ T-1 E ita& 73E*E custt%pe > ;1;. ++" -T ita& INT+ line. "control breaks when 1st line is read -T /I*ST. 7*ITE H ; ist of 1oo(in)s;. 7*ITE H ;----------------;. EN.-T. "control breaks when the contents of the "component carrid or another component to "the left of carrid changes, -T NE7 carrid. 7*ITE4 H ;-irline !ode4;, line-carrid. EN.-T. -T NE7 connid. 7*ITE4 H ;/li)$t !onn I.4;, line-connid. EN.-T. -T NE7 fldate. 7*ITE4 H ;/li)$t .ate4;, line-fldate. EN.-T. -T NE7 custt%pe. 7*ITE4 H ;!usto#er T%pe4;, line-custt%pe. EN.-T. 7*ITE4 H ;1oo(in) I.4;, line-&oo(id, ;/li)$t !lass4;, line-class. "control breaks when the contents of "component class changes -T EN. +/ class. 0 INE. EN.-T. EN. ++". EN.2ET3+.. EN.! -SS.

GG

ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output of the above e-ample.

Mo!i "ing 'o(s To change the contents of a single line or several lines we can us the following statement: MODIFY <TABLE ?$12;?$12 INDEX ?(> FROM &1 6TRANSPORTING 9"@5- 9"@5. ...8 ASSIGNING T)AL 6CASTING8;REFERENCE INTO (' )=; <?$12 FROM &1 TRANSPORTING comp comp, ... WHERE !"B_ >5=. The system searches for the relevant lines as follows: In standard table linear search is used/ in sorted table binary search is applied/ while in hashed table the entry is found using the hash algorithm of the internal table. The wor5 area T&1L/ which must be compatible with the line type of the internal table/ plays a double role in this statement. 9ot only it is used to find the line that you want to change/ but it also contains the new contents. The system searches the internal table for the line whose table 5ey corresponds to the 5ey fields in T&1L. The following e-ample uses the TABLE addition. G"

*E"+*T

,_it&_#odif%A:.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T- scarr_ta& T5"E S+*TE. T-1 E +/ scarr 7IT3 0NIQ0E 6E5 carrid. .-T-4 scarr_'a airline_code T5"E scarr, T5"E c ENGT3 E.

SE E!T = /*+2 scarr INT+ T-1 E scarr_ta&. airline_code > ;--;. *E-. T-1 E scarr_ta& INT+ scarr_'a 7IT3 T-1 E 6E5 carrid > airline_code. 7*ITE4 ;-irline I. ;, ; Na#e;, ; !urrenc%;. 0 INE. 7*ITE H ;1E/+*E 2+.I/I!-TI+N.;. 7*ITE H ;------------------;. 7*ITE4 H scarr_'a-carrid, ; ;, scarr_'a-carrna#e, scarr_'a-currcode. S6I". 7*ITE ;-/TE* 2+.I/I!-TI+N.;. 7*ITE H ;------------------;. "change the contents of an internal table "based on the values in workarea and the "currcode field is only assigned to the "corresponding component of the work area scarr_'a-currcode > ;E0*;. 2+.I/5 T-1 E scarr_ta& /*+2 scarr_'a T*-NS"+*TING currcode. "read again that specific line *E-. T-1 E scarr_ta& INT+ scarr_'a 7IT3 T-1 E 6E5 carrid > airline_code. 7*ITE4 H scarr_'a-carrid, ; ;, scarr_'a-carrna#e, scarr_'a-currcode. EN.2ET3+.. EN.! -SS.

G.

ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

The following e-ample changes the currency to =7*6 using the inde- access.
*E"+*T ,_it&_#odif%A<.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T- scarr_ta& T5"E S+*TE. T-1 E +/ scarr 7IT3 0NIQ0E 6E5 carrid. .-T-4 scarr_'a idx airline_code T5"E scarr, T5"E s%-ta&ix, T5"E c ENGT3 E.

SE E!T = /*+2 scarr INT+ T-1 E scarr_ta&. airline_code > ;--;. *E-. T-1 E scarr_ta& INT+ scarr_'a 7IT3 T-1 E 6E5 carrid > airline_code. 7*ITE4 ;-irline I. ;, ; Na#e;, ; !urrenc%;. 0 INE. 7*ITE H ;1E/+*E 2+.I/I!-TI+N.;. 7*ITE H ;------------------;. 7*ITE4 H scarr_'a-carrid, ; ;, scarr_'a-carrna#e, scarr_'a-currcode. S6I". 7*ITE ;-/TE* 2+.I/I!-TI+N.;. 7*ITE H ;------------------;. idx > s%-ta&ix. scarr_'a-currcode > ;E0*;. 2+.I/5 scarr_ta& IN.E9 idx /*+2 scarr_'a T*-NS"+*TING currcode. *E-. T-1 E scarr_ta& INT+ scarr_'a 7IT3 T-1 E 6E5 carrid > airline_code. 7*ITE4 H scarr_'a-carrid, ; ;, scarr_'a-carrna#e, scarr_'a-currcode.

G!

EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output of the above two e-amples.

Deleting 'o(s To delete a line(s$ of an internal table we can use the DELETE statement. The syntafollows as: DELETE <<TABLE ?$12 FROM &1;WITH TABLE KEY 9"@5-+("23- K 9"@57+("237=;?$12 6INDEX ?(>8==; <?$12 6FROM ?(>-8 6TO ?(>.8 6WHERE !"B_ >58=; <ADJACENT DUPLICATES FROM ?$12 6COMPARING 9"@5- K;ALL FIELDS8=. 8ith variant TABLE we have to specify the line by using the table 5ey. In standard and sorted table we can specify the line to be deleted by its table inde- ?(>. ?(> e-pects a data ob4ect of the type ?. 8ithin a LOOP/ we can omit the INDEX addition. In this case/ the current table line of the LOOP&pass is deleted. To delete several lines at once/ we have to specify at least one of the additions FROM/ TO/ or WHERE. If we specify FROM/ all the table rows from the table inde- ?(>- onwards are included. 8hen addition TO is added only the table rows up to table inde- ?(>. are included. If ?(>. is less than ?(>-/ no rows are deleted. 8e can specify any logical e-pression !"B_ >5 after WHERE/ for which the first operand of each individual comparison is a component of the internal table. 8ith additions ADJACENT DUPLICATES/ the statement DELETE deletes all lines in certain groups of lines/ e-cept for the first line of the group. These are groups of lines that follow one another and have the same content in certain components. If the addition COMPARING is not specified/ the groups are determined by the content of the 5ey fields. If the addition COMPARING is specified/ the groups are determined either by the content

"#

of the specified components 9"@5- 9"@5. ... or the content of all components ALL FIELDS. The following program fills the hashed table with data. The DELETE statement deletes the line where the 5ey field column ?( has the contents of 0#".
*E"+*T ,_it&_deleteA:.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line, id T5"E i, na#e T5"E c ENGT3 <A, EN. +/ line. .-T- ita& I6E 3-S3E. T-1 E +/ line 7IT3 0NIQ0E 6E5 id.

line-id > :AA. line-na#e > ;-s)$ar;. INSE*T line INT+ T-1 E ita&. line-id > <AA. line-na#e > ;Safdar;. INSE*T line INT+ T-1 E ita&. line-id > EA8. line-na#e > ;Jees$an;. INSE*T line INT+ T-1 E ita&. line-id > EAC. line-na#e > ;Safdar;. INSE*T line INT+ T-1 E ita&. 7*ITE4 ; I.;, ; Na#e;. 0 INE. 7*ITE ;1efore .elete;. 7*ITE H ;-------------;. ++" -T ita& INT+ line. 7*ITE4 H line-id, line-na#e. EN. ++". .E ETE T-1 E ita& 7IT3 T-1 E 6E5 id > EAC. S6I". 7*ITE H ;-fter .elete;. 7*ITE H ;------------;. ++" -T ita& INT+ INE. 7*ITE4 H INE-I., INE-na#e. EN. ++". EN.2ET3+.. EN.! -SS.

"

ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output of above program.

The ne-t program fills a hashed table with a list of sBuare numbers. The DELETE statement deletes the lines of the table where the content of field 9"!. is greater than and the content of field 9"!- is less than 1.
*E"+*T ,_it&_deleteA<.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line, col: T5"E i, col< T5"E i, EN. +/ line. .-T- ita& I6E 3-S3E. T-1 E +/ line 7IT3 0NIQ0E 6E5 col:.

.+ G TI2ES. line-col: > s%-index. line-col< > s%-index == <. INSE*T line INT+ T-1 E ita&. EN..+. 7*ITE4 ; ; 0 INE. No.;, SIuare;.

",

7*ITE ;1efore .elete;. 7*ITE H ;-------------;. ++" -T ita& INT+ line. 7*ITE4 H line-col:, line-col<. EN. ++". .E ETE ita& 73E*E ? col< > : @ -N. ? col: < G @. 7*ITE H ;-fter .elete;. 7*ITE H ;-------------;. ++" -T ita& INT+ line. 7*ITE4 H line-col:, line-col<. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

The above program produces the following output.

The e-ample below creates and fills a standard table. Cere/ the first DELETE statement deletes the second line from ?$12 because the second line has the same contents as the first line. The second DELETE statement deletes the second line from the remaining table because the contents of the field 9"!- is the same as in the first line. The third DELETE statement deletes the third and fourth line from the remaining table because the contents of the default 5ey field 9"!. are the same as on the second line. Although the contents of the default 5ey are the same for the first and the fifth line/ the fifth line is not deleted because it is not ad4acent to the first line.
*E"+*T ,_it&_deleteAE.

! -SS exa#ple .E/INITI+N. "static methods "01 I! SE!TI+N. ! -SS-2ET3+.S4 #ain,

"0

#a(e_list. "static attributes "*IK-TE SE!TI+N. ! -SS-.-T-4 1EGIN +/ line, col: T5"E i, col< T5"E c, EN. +/ line. ! -SS-.-T- pos T5"E i. ! -SS-.-T- ita& I6E ST-N.-*. T-1 E +/ line 7IT3 N+N-0NIQ0E 6E5 col<. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #a(e_list. S6I" T+ INE :. ++" -T ita& INT+ line. "! position the output according to pos 7*ITE4 -T Hpos line-col:, line-col<. EN. ++". EN.2ET3+.. 2ET3+. #ain. line-col: line-col: line-col: line-col: line-col: line-col: line-col: pos > A. !2ET3+. #a(e_list. /IE .S. > > > > > > > :. :. :. <. E. G. 8. line-col< line-col< line-col< line-col< line-col< line-col< line-col< > > > > > > > ;-;. ;-;. ;1;. ;1;. ;1;. ;1;. ;-;. -""EN. -""EN. -""EN. -""EN. -""EN. -""EN. -""EN. line line line line line line line T+ T+ T+ T+ T+ T+ T+ ita&. ita&. ita&. ita&. ita&. ita&. ita&.

.E ETE -.L-!ENT .0" I!-TES /*+2 ita& !+2"-*ING pos > :8. !2ET3+. #a(e_list.

.E ETE -.L-!ENT .0" I!-TES /*+2 ita& !+2"-*ING col:. pos > EA. !2ET3+. #a(e_list. .E ETE -.L-!ENT .0" I!-TES /*+2 ita&. pos > G8. !2ET3+. #a(e_list. EN.2ET3+.. EN.! -SS.

"1

ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output of above coding.

Processing %ntire Internal $ables


8hen we access the entire internal table/ we address the body of the table as a single data ob4ect. The following operations on the body of an internal table are relevant: Initiali2ation 8e can initiali'e internal tables with the CLEAR/ REFRESH and FREE statements. The CLEAR statement deletes all the rows and all the memory reBuired/ e-cept the initial memory reBuirement is released. CLEAR ?$12. Aor table with header line we must place two brac5ets (6 8$ after the table name as: CLEAR ?$1268. The REFRESH statement sets an internal table to its initial value/ meaning that it deletes all rows of the internal table. The memory space reBuired for the table is freed up to the initial memory si'e INITIAL SINE. If the internal table has no header line/ REFRESH acts li5e CLEAR. Therefore/ you should always use CLEAR instead of REFRESH. REFRESH ?$12. FREE has the same effect as the REFRESH statement/ though the entire memory area occupied by the table rows is released/ and the initial memory area remains unoccupied. FREE ?$12. In the program/ an internal table ?$12 is filled and then initiali'ed with REFRESH. The IF statement uses the e-pression ?$12 IS INITIAL to find out whether ?$12 is empty. If so/ the memory is released.

"D

*E"+*T

,_it&_initA:.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line, col:, col<, EN. +/ line. .-T- ita& I6E T-1 E +/ line.

line-col: > ;-;. line-col< > ;1;. -""EN. line T+ ita&. *E/*ES3 ita&. I/ ita& IS INITI- . 7*ITE ;IT-1 is e#pt%;. /*EE ita&. EN.I/. EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output.

Assignment 2i5e other data ob4ects/ we can use internal tables as operands in a MOVE statement. MOVE ?$12- TO ?$12.. 6r the eBuivalent statement. ?$12. + ?$12-.

"G

Both operands must either be compatible or convertible. These statements assign the entire contents of table ?$12- to table ?$12./ including the data in any nested internal tables. The original contents of the target table are overwritten. 8hen using internal tables with header lines/ the header line and the body of the table have the same name. If we want to address the body of the table in an assignment/ we must place two brac5ets ( 6 8$ after the table name. But it must be noted that tables with header line is not supported in 66 conte-t. The e-ample creates two standard tables ?$12- and ?$12. with the line type of the structure !?7 . ?$12- has a header line. After filling ?$12- line by line using the APPEND statement/ its entire contents are assigned to ?$12.. 9ote the brac5ets in the statement.
*E"+*T ,_it&_as)nA:.

ST-*T-+/-SE E!TI+N. .-T-4 1EGIN +/ line, col:?:@ T5"E c, col<?:@ T5"E c, EN. +/ line. .-T-4 ita&: ita&< I6E T-1 E +/ line 7IT3 3E-.E* I6E T-1 E +/ line. INE,

line-col: > ;-;. line-col< > ;1;. -""EN. line T+ ita&:. ita&< > ita&:MN. 7*ITe4 ;!ol:;, ; 0 INE. !ol<;.

++" -T ita&< INT+ line. 7*ITE4 H line-col:, ; ;, line-col<. EN. ++".

Aollowing is the output of the above code.

""

In the following e-ample )$12 is a sorted table with line type ) and a non&uniBue 5ey. ?$12 is a hashed table with line type ? and a uniBue 5ey. The line types/ and therefore the entire tables/ are convertible. It is therefore possible to assign the contents of ?$12 to )$12. 8hen you assign the unsorted table ?$12 to the sorted table )$12/ the contents are automatically sorted by the 5ey of )$12.
*E"+*T ,_it&_as)nA<.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 fta& T5"E S+*TE. T-1 E +/ 7IT3 N+N-0NIQ0E ita& T5"E 3-S3E. T-1 E +/ 7IT3 0NIQ0E 6E5 fl T5"E f. f 6E5 ta&le_line, i ta&le_line,

.+ E TI2ES. INSE*T s%-index INT+ T-1 E ita&. EN..+. 7*ITE4 ;!ontents of ita&;. ++" -T ita& INT+ fl. 7*ITE4 H fl. EN. ++". fta& > ita&. S6I". 7*ITE4 H ;!ontents of fta& after -ssi)n#ent;. ++" -T fta& INT+ fl. 7*ITE4 H fl. EN. ++". EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output.

".

Comparison 8e can use internal tables as operands in logical e-pressions as: ?$12- T"5 '1$"'L ?$12.. The T"5 '1$"'L can be any relational operator (EQ, +, TL, NE, T, LT, T+, LE, L, GT, L+, GE$. Aor table with header line we must place two brac5ets (6 8$ after the table name. If two internal tables contain the same number of lines/ they are compared line by line/ component by component. If components of the table lines are themselves internal tables/ they are compared recursively. If you are testing internal tables for anything other than eBuality/ the comparison stops when it reaches the first pair of components that are uneBual/ and returns the corresponding result. This e-ample creates two standard tables/ ?$12 and 3$12. ?$12 is filled with 0 lines and copied to 3$12. Then/ another line is appended to ?$12 and the first logical e-pression tests whether ?$12 is greater than 3$12. After appending the same line to 3$12/ the second logical e-pression tests whether both tables are eBual. Then/ another line is appended to ?$12 and the third logical e-pressions tests whether 3$12 is less than or eBual to ?$12. 9e-t/ another line is appended to 3$12. Its contents are uneBual to the contents of the last line of ?$12. The ne-t logical e-pressions test whether ?$12 is not eBual to 3$12. The first table field whose contents are different in ?$12 and 3$12 is 9"!- in the last line of the table: 0# in ?$12 and D# in 3$12. Therefore/ in the last logical e-pression/ ?$12 is less than 3$12.
*E"+*T ,_it&_co#parA:.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S #ain. EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #ain. .-T-4 1EGIN +/ line,

"!

col: T5"E i, col< T5"E i, EN. +/ line. .-T-4 ita& Fta& I6E T-1 E +/ line, I6E T-1 E +/ line.

.+ E TI2ES. line-col: > s%-index. line-col< > s%-index == <. -""EN. line T+ ita&. EN..+. Fta& > ita&. line-col: > :A. line-col< > <A. -""EN. line T+ ita&. I/ ita& > Fta&. 7*ITE H ;ita& is )reater t$an Fta&;. EN.I/. -""EN. line T+ Fta&. I/ ita& > Fta&. 7*ITE H ;ita& is eIual to Fta&;. EN.I/. line-col: > EA. line-col< > BA. -""EN. line T+ ita&. I/ Fta& <> ita&. 7*ITE H ;Fta& is less t$an or eIual to ita&;. EN.I/. line-col: > 8A. line-col< > DA. -""EN. line T+ Fta&. I/ ita& <> Fta&. 7*ITE H ;ita& is not eIual to Fta&;. EN.I/. I/ ita& < Fta&. 7*ITE H ;ita& is less t$an Fta&;. EN.I/. EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output of the above code.

.#

Sorting The standard and hashed tables can be sorted by using the SORT statement. 7sing SORT for sorted tables is syntactically prohibited. Aollowing is the synta- of SORT statement. SORT ?$12 6STABLE8 < < 6ASCENDING;DESCENDING8 6AS TEXT8 6BY <comp 6ASCENDING;DESCENDING8 6AS TEXT8= <comp, 6ASCENDING;DESCENDING8 6AS TEXT8= ... 8 =. STABLE is used to perform stable sorting/ which means that the relative seBuence of lines that does not change in the sort 5ey remains unchanged in the sort. The addition ASCENDING or DESCENDING can be used to specify the sort direction e-plicitly as ascending or descending. If neither of the additions is entered/ the table is sorted in ascending order. The addition AS TEXT specified that te-t&type components are sorted according to the locale (defines language&dependent and country&dependent characteristics of characters/ such as the sort seBuence or uppercase+lowercase conversion$ of the current te-t environment (part of the runtime environment of an ABAP program and is made up of a language/ a locale and a system codepage.$. If AS TEXT is not specified/ te-t&type components are sorted according to the encoding in the code page of the current te-t environment. 8ith the addition BY 9"@5?/ the table is not sorted according to the table 5ey/ but instead according to the components 9"@5- 9"@5.... that are specified after it. The program below demonstrates sorting.
*E"+*T ,_it&_sortA:.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S4 #ain, #a(e_list. "*IK-TE SE!TI+N. ! -SS-.-T-4 1EGIN +/ line,

land T5"E na#e T5"E a)e T5"E 'ei)$t T5"E EN. +/ line. ! -SS-.-T- ita& EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #a(e_list.

c ENGT3 E, c ENGT3 :A, i, p .E!I2- S <,

I6E ST-N.-*. T-1 E +/ line 7IT3 N+N-0NIQ0E 6E5 land.

++" -T ita& INT+ line. 7*ITE4 H line-land !+ +* C, line-na#e !+ +* C, line-a)e !+ +* C, line-'ei)$t !+ +* C. EN. ++". S6I". EN.2ET3+.. 2ET3+. #ain. line-land > ;G;. line-na#e > ;3ans;. line-a)e > <A. line-'ei)$t > ;BA.AA;. -""EN. line T+ ita&. line-land > ;0S-;. line-na#e > ;3o'ard;. line-a)e > GA. line-'ei)$t > ;O8.AA;. -""EN. line T+ ita&. line-land > ;G1;. line-na#e > ;Lenn%;. line-a)e > :B. line-'ei)$t > ;8A.AA;. -""EN. line T+ ita&. line-land > ;/;. line-na#e > ;2ic$ele;. line-a)e > EA. line-'ei)$t > ;DA.AA;. -""EN. line T+ ita&. line-land > ;G;. line-na#e > ;6arl;. line-a)e > DA. line-'ei)$t > ;C8.AA;. -""EN. line T+ ita&. 7*ITE4 ; and; !+ +* 8, ;Na#e; !+ +* 8, ; -)e; !+ +* 8, ; 7ei)$t; !+ +* 8. 0 INE. 7*ITE H ;7it$out sortin); !+ +* D. !2ET3+. #a(e_list. 7*ITE ;7it$ sortin); !+ +* D. S+*T ita&.

.,

!-

2ET3+. #a(e_list.

7*ITE ;Sta&le sortin); !+ +* D. S+*T ita& ST-1 E. !2ET3+. #a(e_list. 7*ITE ;Sortin) &% land and 'ei)$t; !+ +* D. S+*T ita& .ES!EN.ING 15 land 'ei)$t -S!EN.ING. !2ET3+. #a(e_list. EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output of the above e-ample.

In the following e-ample the table is sorted three times. Airst/ it is sorted binarily by the TEXT field. Second/ it is sorted binarily by the XTEXT field. Third/ it is sorted alphabetically by the TEXT field. Since there is no directly corresponding case in =nglish/ we have ta5en the results from a )erman te-t environment.

.0

*E"+*T

,_it&_sortA<.

! -SS exa#ple .E/INITI+N. "01 I! SE!TI+N. ! -SS-2ET3+.S4 #ain, #a(e_list. "*IK-TE SE!TI+N. ! -SS-.-T-4 1EGIN +/ line, text T5"E c xtext T5"E x EN. +/ line. ! -SS-.-T- ita& EN.! -SS. ! -SS exa#ple I2" E2ENT-TI+N. 2ET3+. #a(e_list. ++" -T ita& INT+ line. 7*ITE H line-text !+ +* C. EN. ++". S6I". EN.2ET3+.. 2ET3+. #ain. line-text > ;0#er;. "convertes a text to a "result is assigned to !+NKE*T TE9T line-text INSE*T line INT+ T-1 E sortable byte sequence and the xtext INT+ S+*T-1 E !+.E line-xtext. ita&.

ENGT3 D, ENGT3 :DA,

I6E 3-S3E. T-1 E +/ line 7IT3 0NIQ0E 6E5 text.

line-text > ;P#er;. !+NKE*T TE9T line-text INT+ S+*T-1 E !+.E line-xtext. INSE*T line INT+ T-1 E ita&. line-text > ;+#er;. !+NKE*T TE9T line-text INT+ S+*T-1 E !+.E line-xtext. INSE*T line INT+ T-1 E ita&. line-text > ;I#er;. !+NKE*T TE9T line-text INT+ S+*T-1 E !+.E line-xtext. INSE*T line INT+ T-1 E ita&. 7*ITE H ;Sorted &inaril% &% text field; !+ +* D. S+*T ita&. !2ET3+. #a(e_list. 7*ITE H ;Sorted &inaril% &% xtext field; !+ +* D. S+*T ita& 15 xtext. !2ET3+. #a(e_list.

.1

7*ITE H ;Sorted alp$a&eticall% &% text field; !+ +* D. S+*T ita& -S TE9T. !2ET3+. #a(e_list. EN.2ET3+.. EN.! -SS. ST-*T-+/-SE E!TI+N. exa#ple>>#ain? @.

Aollowing is the output.

.D

Classes an! -b.ects


6b4ect 6riented Programming is based on the encapsulation of data and its associated functionality in classes. 3lasses in turn are used to create instance (ob4ects$. ABAP 6b4ects represents the part of the ABAP programming language that allows for 66P on the basis of classes. The ABAP 6b4ects streamlined the e-isting ABAP synta- using the concept of synta- cleansing that is many outdated and obsolete language constructs are forbidden in ABAP 6b4ects/ which are allowed outside of classes only for reasons of compatibility. A class is the pattern or template for an ob4ect much li5e a data type is the template for a data ob4ect. 3lasses in ABAP 6b4ects can be declared either globally or locally. 1lobal Classes A global class is visible and can be used in every program of the same AS ABAP/ provided that no limitation by the pac5age of the class e-ists. The global classes of an AS ABAP form its class library. )lobal classes can only created in class pools program type using the 3lass Builder tool (S=,1$ of the ABAP 8or5bench. 8e should define global classes whenever we need ob4ects of the same type in different programs. The global class should be prefi-ed with 9!_ . #ocal Classes A local class is only visible in the program in which it is defined. 2ocal classes can be defined in any ABAP program/ e-cept type groups and interface pools. 8e should use local classes for ob4ects that are only reBuired in one program. 2ocal class hides a global class of the same name. The name of local class should be prefi-ed with !9!_. 3lasses also behave li5e data types that are distinguished into global data types in the ABAP ;ictionary and local data types in any program.

Creating Classes
Both global and local classes are always declared in the declaration part of the program/ and they are implemented in its implementation part. Aor local classes we must enter the relevant statements for the reBuired program in the ABAP =ditor/ while for global classes we must use the 3lass Builder (S=,1$ and fill the relevant input templates of the 3lass Builder with data. The 3lass Builder then generates the corresponding statements in the class pool of the class. The only code to enter for the global classes is the implementation of the methods. The 3lass Builder hides the class pool behind user interface. Cowever/ we can use the 5eyboard instead of the mouse/ by selecting )otoRSection in 3lass Builder which enables to edit the code of a global class in the ABAP =ditor. The 3lass

.G

Builder contains a small testing environment that can be used to test functionality of the methods of a global class but for e-tensive tests/ the ABAP 7nit tool could be used.

Declaration an! Implementation Part


In terms of synta-/ each class definition always consists of a declaration part and an implementation part. In declaration part we define various class components (Attributes/ <ethods and =vents$. The implementation part contains the code for the class components methods and events. The basic structure of a class is as follows: CLASS @49!1AA DEFINITION. ......... ENDCLASS. .................. ......... CLASS @49!1AA IMPLEMENTATION. ......... ENDCLASS. 8ith global classes/ we usually wouldnEt see this structure directly. 6nce we have created a global class/ the 3lass Builder displays the empty class as shown below:

Aollowing are the different components of a class.

Attributes
Attributes are internal data fields within a class that can have any ABAP data type. The state of an ob4ect is determined by the contents of its attributes. In local classes instance attributes are declared using the DATA statement/ static attributes are declared with CLASS-DATA and constant attributes are declared with CONSTANTS 5eyword. In global classes/ we can simply enter the attributes and their properties in the Attributes tab of 3lass Builder. The constant in 3lass Builder can be created by specifying 9onstant in the @e$el column of the ttributes tab and enter initial value in the Initial 3olumn.

."

Metho!s
<ethods are procedures in a class that define the behavior of an ob4ect. They can access all of the attributes of a class. This allows them to change the data content of an ob4ect. They also have a parameter interface/ with which users can supply them with values when calling them/ and receive values bac5 from them. The private attributes of a class can only be changed by methods in the same class. <ethods can be called by using the CALL METHOD statement. Instance methods are declared using the METHODS 5eyword while the static methods are declared with CLASS-METHODS. <ethods are implemented with 5eywords METHOD @ $%_71@ . K ENDMETHOHD. In the 3lass Builder/ we must enter the methods and their properties in the Aethods tab.

%vents
6b4ects or classes can use events to trigger event handler methods in other ob4ects or classes. In a normal method call/ one method can be called by any number of users. 8hen an event is triggered/ any number of event handler methods can be called. The lin5 between the trigger and the handler is not established until runtime. In a normal method call/ the calling program determines the methods that it wants to call. These methods must e-ist. 8ith events/ the handler determines the events to which it wants to react. There does not have to be a handler method registered for every event. The lin5 between trigger and handler is established dynamically in a program using the SET HANDLER statement. The events of a class can be triggered in the methods of the same class using the RAISE EVENT statement. Instance events are declared using the EVENTS 5eyword while the static methods are declared with CLASS-EVENTS.

..

In global classes/ events are declared on the E$ents tab of 3lass Builder.

&isibilit" Sections
=ach component of the class must be assigned to one of the following three visibility sections. The visibility sections define the visibility of the components of the class.

Public Section
All components of public section can be accessed by all e-ternal users/ the methods of subclasses and by the methods of the class. These components represent the interface between the class and the e-ternal world.

Protecte! Section
All components of protected section can be accessed by the methods of the subclasses and the methods of class. They represent the interface between the class and its subclasses.

Private Section
3omponents in this section can only be used within the methods of the class. They are not part of the interfaces of the class. Aollowing is the synta- used to separate the declaration part of class into three visibility sections: CLASS @49!1AA DEFINITION. PUBLIC SECTION ......... PROTECTED SECTION ......... PRIVATE SECTION ......... ENDCLASS. Aollowing e-ample demonstrate the basic structure of a local class.
REPORT J_""5_9!1AAC-. DEFINITION.

CLASS !9!_ @5!"4

PUBLIC SECTION. *I+sta+ce ,eth-ds dec.ared !+ /ub.!c *sect!-+ 0!s!b!.t1 METHODS A $_ @5!"4 .

.!

METHODS B $_ @5!"4

PRIVATE SECTION. *I+sta+ce attr!butes dec.ared !+ */r!0ate sect!-+ 0!s!b!.t1 DATA ?( TYPE 9 LENGTH I. DATA 71@ TYPE A$'?7B. DATA 1((' AA TYPE A$'?7B. DATA 514 TYPE ). ENDCLASS. CLASS !9!_ @5!"4 IMPLEMENTATION.

*I+sta+ce ,eth-ds !,/.e,e+tat!-+ METHOD A $_ @5!"4 . ?( + UACC-U. 71@ + UMD%1@@1( AAB%1' K%17U. 1((' AA + UP A%1&1', P1W?A$17U. 514 + U/CCCC.CU. ENDMETHOD. METHOD B $_ @5!"4 . WRITE UE@5!"4 D $1?!AU. SKIP. WRITE* S UID* U, ?(. WRITE* S UN1@ * U, 71@ . WRITE* S UA((' AA* U, 1((' AA. WRITE* S UP14 U, 514. ENDMETHOD. ENDCLASS. CLASS !9!_( @" DEFINITION. PUBLIC SECTION. *stat!c ,eth-d CLASS-METHODS @1?7. ENDCLASS. CLASS !9!_( @" IMPLEMENTATION. METHOD @1?7. *e,/2-b3 !s a refere+ce 0ar!ab.e 4h!ch 4!.. be */-!+t!+g t- .c.2e,/.-1ee refere+ce t1/e *-r c.ass DATA @5_"23 TYPE REF TO !9!_ @5!"4 . *!+sta+!tate e,/.-1ee -b3ect a+d ass!g+ the -b3ect *refere+ce t- the referc+e 0ar!ba.e e,/2-b3

!#

CREATE OBJECT

@5_"23.

*the !+sta+ce c-,/-+e+t se.ect-r -/erat-r !s used *t- ca.. !+sta+ce ,eth-ds @5_"23-LA $_ @5!"4 O P. @5_"23-LB $_ @5!"4 O P. ENDMETHOD. ENDCLASS. START-OF-SELECTION. *the stat!c c-,/-+e+t se.ect-r -/erat-r !s used t*ca.. stat!c ,eth-d !9!_( @"+L@1?7O P.

Aollowing is the output of the above e-ample.

In the class builder/ we must select the assignment of a component to a visibility section separately for each component in that we choose the option .ublic/ .rotected/ or .ri$ate for each component in the $isibilit% column.

Cowever/ if we want to write programming code/ we can select )oto Public Section/ Protected Section or Private Section to enter the complete declaration part of global class/ in the same way as that of a local class in the ABAP =ditor.

Metho!s 'evisite!
8e have already defined and called methods earlier/ here we discuss the finer points of methods in ABAP 6b4ects.

Parameter Inter aces


The parameter interface of a method is defined by the additions to the METHOD and CLASS-METHODS statements when the method is declared or by selection of Parameters in the 3lass Builder. 9o further details of the parameter interface are reBuired in the implementation section between METHOD and ENDMETHOD. Cowever/ we can display the interface during implementation of global classes. The parameter interface of a method comprises formal parameters. Aormal parameters are local data ob4ects that are declared in the methodEs parameter interface rather then in the body of the method. The actual parameters are used to initiali'e the formal parameters. Actual parameters are placed in the parameter list of the method invocation. 8ithin a method/ formal parameters can be used via their names in operand positions. The following properties can be defined for a formal parameter: Parameter Type Oind of Parameter Passing Parameter Typing !,

Supply Type of Parameter

8e should note that methods in ABAP 6b4ects can not be overloaded. In other words/ we can not use the same method names with different parameter interfaces/ even when we redefine methods in subclasses. 8e can define the following parameters: Parameter $"pe )nput Parameters+ Input parameters are defined after the IMPORTING addition to the METHODS or CLASS-METHODS statement/ or are declared by selecting Importing in the Type column on the Parameters tab page in the 3lass Builder. The input parameters contain values that are passed into the method from the calling program. These values originate outside of the method and they are imported into it. 8hen a method is called/ the value of the assigned actual parameter (parameter passed from calling statement$ is assigned to the input parameter. Input parameters for which pass by reference are defined can not be overwritten in the method. Input parameters for which pass by value are defined are not passed to the actual parameter when the procedure is e-ited.

The following e-ample demonstrates the use of input parameters.

!0

REPORT

J_""5_@ $%(C-.

PARAMETERS* 7D@2 '- TYPE ?, 7D@2 '. TYPE ?. CLASS !9!_ >1@5! PUBLIC SECTION. METHODS 1(( IMPORTING 7"- TYPE 7". TYPE METHODS AD2 IMPORTING 7"- TYPE 7". TYPE METHODS (?: IMPORTING 7"- TYPE 7". TYPE CLASS-METHODS @1?7. ENDCLASS. CLASS !9!_ >1@5! IMPLEMENTATION. ? ?. ? ?. ? ?. DEFINITION.

METHOD 1((. DATA AD@ TYPE ? VALUE C. AD@ + 7"- , 7".. WRITE* S USD@ +U, AD@ LEFT-JUSTIFIED. ENDMETHOD. METHOD AD2. DATA A TYPE ? VALUE C. A + 7". , 7"-. WRITE* S USD2$'19$?"7 +U, A LEFT-JUSTIFIED. ENDMETHOD. METHOD (?:. DATA ( TYPE ? VALUE C. ( + 7". DIV 7"-. WRITE* S UD?:?A?"7 +U, ( LEFT-JUSTIFIED. ENDMETHOD. METHOD @1?7. DATA "23 TYPE REF TO !9!_ >1@5! . CREATE OBJECT "23. "23-L1((O 7"- + 7D@2 '- 7". + 7D@2 '. P. "23-LAD2O 7"- + 7D@2 '- 7". + 7D@2 '. P.

!1

"23-L(?:O 7"- + 7D@2 '- 7". + 7D@2 '. P. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

After e-ecuting the above code we get the following output.

Output Parameters+ 6utput parameters are specified after the EXPORTING addition to the METHODS or CLASS-METHODS statement/ or are declared by selecting E:porting in the *%pe column on the .arameters tab page in the 3lass Builder. The output parameters contain values returned from the method. These values originate within method and they are e-ported out of it. 8hen a method is called/ the value of the assigned actual parameter (parameter passed from calling statement$ is not assigned to an output parameter for which pass by value is defined. 6utput parameters can be overwritten in the method. If the method is e-ited without errors using ENDMETHOD or RETURN/ the output parameter is passed to the actual parameter. Aollowing e-ample demonstrate the use of output parameters.
REPORT J_""5_@ $%(C..

PARAMETERS* 7D@2 '- TYPE ?, 7D@2 '. TYPE ?, "5 '17( TYPE 9. CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION.

!D

CLASS-METHODS @1?7. METHODS 5 ')"'@_1'?$%@ $?9 *,ea+s the /ara,eters 4!.. tra0e. *!+ fr-, /r-gra, !+t- ,eth-d dur!+g *ca..!+g 4here these 4!.. act as e5/-rt!+g IMPORTING 7"- TYPE ? 7". TYPE ? "5 TYPE 9 *,ea+s the /ara,eter 4!.. tra0e. *-ut fr-, the ,eth-d !+t- the */r-gra, at ca..!+g 4here !t 4!.. *acts as !,/-rt!+g EXPORTING 'A!$ TYPE ?. ENDCLASS. CLASS !9!_ >1@5! IMPLEMENTATION.

METHOD 5 ')"'@_1'?$%@ $?9. IF "5 + U,U. 'A!$ + 7"- , 7".. ELSEIF "5 + U-U. 'A!$ + 7". - 7"-. ELSEIF "5 + UMU. 'A!$ + 7"- M 7".. ELSEIF "5 + USU. 'A!$ + 7"- DIV 7".. ELSE. MESSAGE UI7:1!?( O5 '1$"'U TYPE UIU. ENDIF. ENDMETHOD. METHOD @1?7. DATA "23 TYPE REF TO !9!_ >1@5! . DATA ' AD!$ TYPE ?. CREATE OBJECT "23. *here EXPO)TING s/ec!f!es that the /ara,eters *4!.. tra0e. -ut fr-, the /r-gra, a+d at the *sa,e t!,e these 4!.. be !,/-rt!+g t- the ,eth-d "23-L5 ')"'@_1'?$%@ $?9O EXPORTING 7"- + 7D@2 '7". + 7D@2 '. "5 + "5 '17( *,ea+s th!s /ara,eter

!G

*4!.. tra0e. !+ fr-, ,eth-d *!+t- /r-gra, 4here !t !s *act!+g as e5/-rt!+g IMPORTING 'A!$ + ' AD!$ P. WRITE* UR AD!$ + U, ' AD!$. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output.

)nput 4 Output Parameters+ I+6 parameters are specified after the CHANGING addition to the METHODS or CLASS-METHODS statement or are declared by selecting 9hanging in the *%pe column on the .arameters tab page in the 3lass Builder. I+6 parameters contain values that are passed into the method/ changed by the code within the method and then returned. These values originate outside the methodK they are passed into it/ and passed bac5. 8hen a method is called/ the value of the assigned actual parameter (parameter passed from calling statement$ is assigned to the I+6 parameter/ and if the method is e-ited without errors using ENDMETHOD or RETURN/ the I+6 parameter is passed to the actual parameter. I+6 parameters can be overwritten in the method.

!"

The previous e-ample is repeated with the use of I+6 parameters.


REPORT J_""5_@ $%(C/.

PARAMETERS* 7D@2 '- TYPE ?, 7D@2 '. TYPE ?, "5 '17( TYPE 9. CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. METHODS 5 ')"'@_1'?$%@ $?9 CHANGING 7"- TYPE ? 7". TYPE ? "5 TYPE 9 'A!$ TYPE ?. ENDCLASS. CLASS !9!_ >1@5! IMPLEMENTATION.

METHOD 5 ')"'@_1'?$%@ $?9. IF "5 + U,U. 'A!$ + 7"- , 7".. ELSEIF "5 + U-U. 'A!$ + 7". - 7"-. ELSEIF "5 + UMU. 'A!$ + 7"- M 7".. ELSEIF "5 + USU. 'A!$ + 7"- DIV 7".. ELSE. MESSAGE UI7:1!?( O5 '1$"'U TYPE UIU. ENDIF. ENDMETHOD. METHOD @1?7. DATA "23 TYPE REF TO !9!_ >1@5! . DATA ' AD!$ TYPE ?. CREATE OBJECT "23. "23-L5 ')"'@_1'?$%@ $?9O CHANGING 7"- + 7D@2 '7". + 7D@2 '. "5 + "5 '17( 'A!$ + ' AD!$ P. WRITE* UR AD!$ + U, ' AD!$. ENDMETHOD.

!.

ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of the above code listing.

#eturn %alue+ A method can have only one return value/ for which pass by value must be declared. This return value can be declared after the RETURNING addition to the METHODS or CLASS-METHODS statement/ or by selecting 0eturning in the *%pe column on the .arameter tab page in the class builder. A return value is handled in the same way that an output parameter is handled in the methodK however/ a method with a return value is a functional method/ which/ in addition to the return value/ can have only input parameters. A functional method can be used in operand operations. The return value is then used in these operations. The following e-ample shows the use of return value.
REPORT J_""5_@ $%(C0.

CLASS !9!_@1$% DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. METHODS )19$"'?1! IMPORTING 7 TYPE ? RETURNING *0a.ue add!t!-+ s/ec!f1 that *fact 4!.. be /assed b1 0a.ue :1!D O)19$P TYPE ?. ENDCLASS. CLASS !9!_@1$% IMPLEMENTATION.

!!

METHOD )19$"'?1!. )19$ + -. IF 7 + C. RETURN. ELSE. DO 7 TIMES. )19$ + )19$ M A4-?7( >. ENDDO. ENDIF. ENDMETHOD. METHOD @1?7. DATA "23 TYPE REF TO !9!_@1$%. DATA 'A!$ TYPE ?. CREATE OBJECT "23. 'A!$ + "23-L)19$"'?1!O - P. WRITE* UF19$"'?1! ") 0 + U, 'A!$ RIGHT-JUSTIFIED. 'A!$ + "23-L)19$"'?1!O / P. WRITE* S UF19$"'?1! ") -C + U, 'A!$ RIGHT-JUSTIFIED. 'A!$ + "23-L)19$"'?1!O F P. WRITE* S UF19$"'?1! ") -- + U, 'A!$ RIGHT-JUSTIFIED. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_@1$%+L@1?7O P.

,##

Aollowing is the output produced by above listing.

8hen we declare a parameter/ we must select the type that matches the behavior of that parameter e-actly. A parameter that is received but not changed by the method is an input parameter. A parameter that is output but is not received is an output parameter or a return value. A parameter that is received changed and output is an I+6 parameter. Aigure below shows how parameters are passed and received from the method.

Iin! o Parameter Passing The formal parameter is passed either ass pass by value or pass by reference. Pass by %alue+ 8ith pass by value/ a local data ob4ect is created as a copy of the actual parameter for each formal parameter when the method is called. In case of input parameters and I+6 parameters/ the value of the actual parameter is assigned to this data ob4ect. The value of the formal parameter is only assigned to output parameters/ I+6 parameters and return values if the method is e-ited without errors using ENDMETHOD or RETURN. The synta- of pass by value is shown below using the e-ample of the return value )19$:

,#

K RETURNING VALUEO)19$P K Pass by #e(erence+ 8ith pass by reference/ a reference to the actual parameter is passed to the method for each formal parameter for which an actual parameter is specified when we call the method/ regardless of the parameter type. The method thus uses the actual parameter itself/ and changes to formal parameters have a direct effect on the actual parameter. Aollowing is the synta- of pass by reference using the e-ample of input parameter ?51'1: K IMPORTING REFERENCEO?51'1P K In the 3lass Builder/ we define the 5ind of parameter passing by selecting the .ass b% $alue chec5 bo- on the .arameters tab page or leaving this blan5. Thus pass by reference is the default transfer type/ which is used unless a different type is specified/ both in the synta- and in the 3lass Builder. The method should always be programmed in such a way that the behavior of its parameters corresponds to the semantics defined by the parameter type: o ;o not e-ecute read access to an output parameter that is passed by reference because its initial value is not defined. o If you add lines to an internal table or e-tend a string that is defined as an output parameter that is passed by reference/ you must initiali'e the parameter before the first access. Pass by reference always perform better than pass by value because no data ob4ect has to be created when a procedure is called and no data transport ta5es place. The e-ample in listing below shows the usage of by value and by reference parameters.
REPORT J_""5_@ $%(CI.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. PRIVATE SECTION. METHODS* @ $%_24:1! IMPORTING :1!D O?(>P TYPE ?, @ $%_24' ) IMPORTING ' ) ' 79 O?(>P TYPE ?. DATA @AB TYPE A$'?7B. ENDCLASS. CLASS !9!_ >1@5! METHOD @1?7. IMPLEMENTATION.

,#,

DATA "23 TYPE REF TO !9!_ >1@5! . CREATE OBJECT "23. WRITE* UC1!!?7B @ $%"( 24 V1!D U. WRITE* S U+++++++++++++++++++++++U. "23-L@ $%_24:1!O EXPORTING ?(> + A4-?7( > P. SKIP. WRITE* UC1!!?7B @ $%"( 24 RA ) ' 79 U. WRITE* S U++++++++++++++++++++++++++++U. "23-L@ $%_24' )O EXPORTING ?(> + A4-?7( > P. ENDMETHOD. METHOD @ $%_24:1!. DO / TIMES. @AB + ?(>. CONCATENATE U@ $%_24:1!* U @AB INTO @AB. WRITE* S @AB. ENDDO. ENDMETHOD. METHOD @ $%_24' ). DO / TIMES. @AB + ?(>. CONCATENATE U@ $%_24' )* U @AB INTO @AB. WRITE* S @AB. ENDDO. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of the above e-ample.

,#0

Parameter $"ping Typing means that to assign a type to a formal parameter. The synta- used for this purpose is a TYPE or LIKE addition/ which must be specified after each formal parameter. Aor e-ample: METHODS @4_@ $% EXPORTING 51'1@ TYPE (1$1_$45

In 3lass Builder/ fill the *%ping (*%pe/ *%pe 0e" *o/ or @ike$ and *eference type columns accordingly on the Parameters tab page in order to specify the type.

,#1

The type must be accessible to all users of the methodK we can specify built&in ABAP types/ global types from the ABAP ;ictionary or types from the public visibility section of a global class for public methods. 8ith protected methods/ additional types from the protected visibility section of the class can also be used/ while types from the private visibility section and local types from the class pool can be used for private method types only. The main difference between typing and data declaration is that a formal parameter is assigned its actual data type only when it is lin5ed to an actual parameter when a method is called. All technical properties of the actual parameter are then passed to the formal parameter. In order for an actual parameter to be passed/ its data type must match the typing (technical properties must be compatible$ of the formal parameter. The typing of a formal parameter may be complete or generic. Aor complete typing/ use TYPE to refer to a complete data type or LIKE to refer to a data ob4ect. Aor generic typing/ we can use the built&in generic types (174, 174 $12! , (1$1, KK$. Internal table types are also generic if the table 5ey is not fully defined. If we need to use a generic type/ we should always be as specific as possible/ use generic types line 7D@ '?9/ A?@5! and >A QD 79 instead of 174. Aollowing e-ample demonstrate the usage of generic typing.
REPORT J_""5_@ $%(CE.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. METHODS @ $%IMPORTING ?51' TYPE 174. ENDCLASS. CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA "23 TYPE REF TO !9!_ >1@5! . CREATE OBJECT "23. "23-L@ $%-O EXPORTING ?51' + U-C.0U P. ENDMETHOD. METHOD @ $%-. DATA* A$' TYPE A$'?7B, 7D@ TYPE ?, )!$ TYPE ). A$' + ?51'. WRITE* UV1!D ") ?7 A$'?7B )"'@1$ + U, A$' RIGHT-JUSTIFIED.

,#D

SKIP. 7D@ + ?51'. WRITE* S UV1!D ") ?7 ?7$ B ' )"'@1$ + U, 7D@ LEFT-JUSTIFIED. SKIP. )!$ + ?51'. WRITE* S UV1!D ") ?7 )!"1$ )"'@1$ + U, )!$ LEFT-JUSTIFIED. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output.

Suppl" $"pe o Parameter Aor every formal parameter that awaits a value (Input parameters and I+6 parameters$/ an actual parameter must be specified when the method is called. The assignment of actual parameters to output parameters and return values is always optional. Aor input parameters and I+6 parameters/ this rule can be avoided by declaring the parameter as optional. The synta- is shown below/ using the e-ample of I+6 parameter: METHODS @4_@ $% CHANGING 951' 6r $45 (1$1_$45 OPTIONAL K

METHODS @4_@ $% CHANGING 951' $45 (1$1_$45 (1$1_"23 9$ K

DEFAULT

An optional formal parameter for which no actual parameter is specified is initiali'ed in accordance with its type. 8ith addition DEFAULT the value and type of an appropriately specified replacement parameter (1$1_"23 9$ are copied. ,#G

In the 3lass Builder/ we can ma5e a formal parameter optional by selecting the +ptional column/ or by entering a value in the De"ault $alue column.

It is recommended that to ma5e all formal parameters optional/ with the e-ception of those for which a different entry is actually reBuired each time the method is called. 6therwise/ we will force the callers to specify unnecessary actual parameters/ for which type&specific au-iliary variables often have to be created. The following program demonstrates the use of .E/-0 T parameter.
REPORT J_""5_@ $%(CF.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. PRIVATE SECTION. METHODS 5'?7$ IMPORTING ?71@ TYPE A$'?7B ?9!1AA TYPE A$'?7B DEFAULT U-C$%U. ENDCLASS. CLASS !9!_ >1@5! IMPLEMENTATION. METHOD 5'?7$. WRITE* UY"D' 71@ ?A* U, ?71@ . IF ?9!1AA IS NOT SUPPLIED. WRITE* S UY"D' 9!1AA ?A* U, ?9!1AA COLOR E. ELSE. WRITE* S UY"D' 9!1AA ?A* U, ?9!1AA. ENDIF. SKIP. ENDMETHOD. METHOD @1?7. DATA "23 TYPE REF TO !9!_ >1@5! . CREATE OBJECT "23. "23-L5'?7$O EXPORTING ?71@ + UJ1@?!U ?9!1AA + UI$%U P.

,#"

"23-L5'?7$O EXPORTING ?71@ + UAAB%1' K%17U P. "23-L5'?7$O EXPORTING ?71@ + UMD(1A1?'U ?9!1AA + U.7(U P. "23-L5'?7$O EXPORTING ?71@ + UK%1(?31U P. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output produced by the above listing.

Metho! Calls
Static Metho! Calls Statically method can be invo5ed as component of a class (static$ or an ob4ect. To call an instance method we have to use the instance component selector (-L$ and for static method calls we have to use the static component selector (+L$. "23-L@4_@1$%O P. 6r C!1AA_71@ +L@4_@1$%O P.

,#.

If a method has several non&optional input parameters/ the statement is as followsK here a data ob4ect is e-plicitly assigned to each input parameter. @4_@1$%O ?51'1- + ("23?51'1. + ("23. K P. If actual parameters are to be assigned to any formal parameters/ the synta- is as follows: @4_@ $%O EXPORTING ?51'1- + ("23?51'1. + ("23. K IMPORTING "51'1- + ("23"51'1. + ("23. K CHANGING 951'1- + ("23951'1. + ("23. K P. 8ith EXPORTING/ we supply the input parameters defined with IMPORTING. 8ith IMPORTING/ we receive values from output parameters defined with EXPORTING. 8ith CHANGING/ we assign the actual parameters to the I+6 parameters defined with CHANGING. The eBual sign is not an assignment operator in this case. Instead/ its function is to bind actual parameters to formal parameters. *unctional Metho! Calls A functional method can have any number of input parameters and only one return value that is passed by value. The functional methods are intended to be used in operand position. To call the function method the RECEVING addition can be used to receive the return value as: @4_@ $%O EXPORTING ?51'1- + ("23?51'1. + ("23. K. RECEIVING '51'1 + ("23 P. Cowever/ this statement is hardly used in practice. The functional eBuivalent for the above statement is as follows: ("23 + @4_@ $%O ?51'1- + ("23- ?51'1. + ("23. K P. 8hen the statement is e-ecuted the method is called and the return value is used as an operand. In following e-ample two functional methods B $_1' 1 and B $_:"!D@ are implemented.

,#!

REPORT

J_""5_@ $%(CX.

SELECTION-SCREEN BEGIN OF SCREEN -CC. PARAMETERS* 5_'1(?DA TYPE ?, 5_% ?B%$ TYPE ?. SELECTION-SCREEN END OF SCREEN -CC. CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. CLASS !9!_94!?7( ' DEFINITION. PUBLIC SECTION. METHODS* B $_1' 1 RETURNING :1!D O'_1' 1P TYPE ), B $_:"!D@ RETURNING :1!D O'_:"!D@ P TYPE ). CONSTANTS 5? TYPE ) VALUE U/.-0-IYU. DATA* '1(?DA TYPE ), % ?B%$ TYPE ). ENDCLASS. CLASS !9!_94!?7( ' IMPLEMENTATION. METHOD B $_1' 1. '_1' 1 + 5? M @ -L'1(?DA MM .. ENDMETHOD. METHOD B $_:"!D@ . '_:"!D@ + @ -LB $_1' 1O P M @ -L% ?B%$. ENDMETHOD. ENDCLASS. CLASS !9!_ >1@5! IMPLEMENTATION.

METHOD @1?7. DATA* "23 TYPE REF TO !9!_94!?7( ', :"!D@ TYPE A$'?7B. CALL SELECTION-SCREEN -CC STARTING AT IC -C. IF A4-AD2'9 + C. CREATE OBJECT "23. "23-L'1(?DA + 5_'1(?DA. "23-L% ?B%$ + 5_% ?B%$. :"!D@ + "23-LB $_:"!D@ O P. WRITE* UV"!D@ 7 * U, :"!D@ .

, #

ENDIF. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of above code.

D"namic Metho! Call To call a method dynamically we must use the language element CALL METHOD. The method to be called can be specified by dynamic to5en specifications in various forms. The synta- for the dynamic to5en specification is usually such that instead of the static synta-/ a brac5eted identifier is given that contains the actual synta-: K O?( 7$?)? 'P K ;ynamic method call is also 5nown as ;ynamic Invo5e. The dynamic method call can be in the form of as: CALL METHOD < O@ $%P_71@ ; "23-LO@ $%_71@ P ; O9!1AA_71@ P+LO @ $%_71@ P ; 9!1AA+LO@ $%_71@ P ; O9!1AA_71@ P+L@ $%_71@ = 6PARAMETER-TABLE 5$128.

The PARAMETER-TABLE is used to assign actual parameters to all formal parameters of a dynamically called method. Aor 5$12/ specify a hashed table of table type ABAP_PARMBIND_TAB or of row type ABAP_PARMBIND from ABAP type group (ABAP program that contains the definitions of globally visual data types and constants and that is loaded via the usage of its data types and constants$. ;uring e-ecution of the CALL METHOD statement/ this table must contain e-actly one row for every non& optional formal parameter and can contain e-actly one row for every optional formal parameter. The table columns are: 9A<= of type 9 and length 0# for the name of the respective formal parameter in uppercase letters. OI9; of type 9 of length for the 5ind of the formal parameter (EXPORTING/ IMPORTING/ CHANGING/ RECEIVING$. HA27= of type REF TO data as a pointer to an appropriate actual parameter.

2isting in the following e-ample demonstrates the dynamic method call.


REPORT J_""5_@ $%(CY.

*C(2G'I2F)ONTEND2&E)6ICE& c.ass -f the c.ass .!brar1 *c-+ta!+s ,eth-ds f-r /r-cess!+g f!.es PARAMETERS* 5_9!1AA TYPE A$'?7B DEFAULT UCL_GUI_FRONTEND_SERVICESU, 5_@ $% TYPE A$'?7B DEFAULT UDIRECTORY_EXISTU, 5_?7 TYPE A$'?7B DEFAULT UDIRECTORYU, 5_:1!D TYPE A$'?7B DEFAULT UC*ZWINDOWSU, 5_"D$ TYPE A$'?7B DEFAULT URESULTU. CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. *TYPE7POO(& dec.ares the data t1/es a+d c-+sta+ts *-f t1/e gr-u/, aba/ !s the /redef!+ed t1/e gr-u/ *the tab.e t1/e aba/2fu+c2/ar,b!+d2tab be.-+gs t*the t1/e gr-u/ aba/ TYPE-POOLS 1215. ENDCLASS. CLASS !9!_ >1@5! METHOD @1?7. IMPLEMENTATION. TYPE TYPE TYPE TYPE A$'?7B, 1215_51'@2?7(, 1215_51'@2?7(_$12, REF TO 9>_'""$,

DATA* "D$_:1!D 51'1@ $ ' 51'1@ $ 'A ''"'

, ,

@AB

TYPE A$'?7B.

*set tab. c-,/-+e+ts 51'1@ $ '-71@ + 5_?7. *c.2aba/2-b3ectdescr !s a g.-ba. c.ass, /r-0!des *)u+t!,e T1/e &er0!ces 51'1@ $ '-W?7( + 9!_1215_"23 9$( A9'+L >5"'$?7B. GET REFERENCE OF 5_:1!D INTO 51'1@ $ '-:1!D . INSERT 51'1@ $ ' INTO TABLE 51'1@ $ 'A. 51'1@ $ '-71@ + 5_"D$. 51'1@ $ '-W?7( + 9!_1215_"23 9$( A9'+L' $D'7?7B. GET REFERENCE OF "D$_:1!D INTO 51'1@ $ '-:1!D . INSERT 51'1@ $ ' INTO TABLE 51'1@ $ 'A. TRY. CALL METHOD O5_9!1AAP+LO5_@ $%P PARAMETER-TABLE 51'1@ $ 'A. CONCATENATE UR $D'7 V1!D * U "D$_:1!D MESSAGE @AB TYPE UIU. INTO @AB.

CATCH 9>_A4_(47_91!!_ ''"' INTO ''"'. MESSAGE ''"' TYPE UIU DISPLAY LIKE UEU. ENDTRY. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of the above e-ample.

, 0

Class Instantiation
The addition CREATE defines the conte-t in which class can be instantiated that is/ where the CREATE OBJECT statement can be e-ecuted for that class. Publicly instantiated class allows any user to create ob4ects. 3lasses with protected instantiation allow the creation of ob4ects in methods of subclasses. In classes with private instantiation/ it is only the class itself that can create ob4ects. The synta- that controls the instantiation of a class is as follows: CLASS @49!1AA DEFINITION CREATE PUBLIC;PROTECTED;PRIVAE. ......... ENDCLASS. If we donEt specify any value/ the class can be publicly instantiated by default. In the following e-ample the demo class is declared with private instantiation.
REPORT J_""5_9!1AAC..

CLASS !9!_( @" DEFINITION CREATE PRIVATE. PUBLIC SECTION. DATA 1$$' TYPE 9 LENGTH .C. ENDCLASS. CLASS !9!_ >1@5! DEFINITION.

, 1

PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. CLASS !9!_ >1@5! METHOD @1?7. DATA "23 TYPE REF TO !9!_( @". CREATE OBJECT "23. "23-L1$$' + UABAP O23 9$AU. WRITE* UV1!D ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P. ") 1$$' + U, "23-L1$$'. IMPLEMENTATION.

6n compilation the above code produces the following error.

Multiple Instantiation The e-ample below shows how to manage any number of ob4ects for the same class. The handling of several ob4ects via an internal table demonstrates the synthesis from the 1)2 language ABAP and the 66 language elements of ABAP 6b4ects. 6ther 66 languages such as >ava do not provide any direct language elements that would solve the tas5 shown here.
REPORT 4_""5_@?7A$. DEFINITION.

CLASS J9!_: %?9!

PUBLIC SECTION. METHODS 199 ! '1$ IMPORTING ( !$1 TYPE ?. METHODS A%"&_A5 (. PRIVATE SECTION.

, D

DATA A5 ENDCLASS.

( TYPE ?.

CLASS J9!_: %?9!

IMPLEMENTATION.

METHOD 199 ! '1$ . A5 ( + A5 ( , ( !$1. ENDMETHOD. METHOD A%"&_A5 (. DATA "D$5D$ TYPE A$'?7B. "D$5D$ + A5 (. MESSAGE "D$5D$ TYPE UIU. ENDMETHOD. ENDCLASS. CLASS !9!_( @" DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. CLASS !9!_( @" IMPLEMENTATION. METHOD @1?7. DATA* : %?9! ?_:$12 7 A5 ( TYPE TYPE TYPE TYPE REF TO J9!_: %?9! , TABLE OF REF TO J9!_: %?9! , ? VALUE I, ?.

DO 7 TIMES. CREATE OBJECT : %?9! . A5 ( + A4-?7( > M -C. : %?9! -L199 ! '1$ O ( !$1 + A5 APPEND : %?9! ENDDO. TO ?_:$12.

( P.

LOOP AT ?_:$12 INTO : %?9! . : %?9! -LA%"&_A5 (O P. ENDLOOP. ENDMETHOD. ENDCLASS.

, G

START-OF-SELECTION. !9!_( @"+L@1?7O P.

Aollowing is the output of above listing.

-b.ect Creation in a *actor" Metho! Aactory method is an 66 design pattern/ and is often used to refer to any method whose main purpose is creation of ob4ects. =-ample below demonstrates the factory method.
REPORT J_""5_)19@$%(.

CLASS !9!_: %?9! DEFINITION CREATE PRIVATE. PUBLIC SECTION. *)ET')NING def!+es a f-r,a. /ara,eter ref *as a retur+ 0a.ue" The retur+ 0a.ue ,ust *be /assed b1 0a.ue 4!th 6#('E" CLASS-METHODS 9' 1$ RETURNING :1!D O' )P TYPE REF TO !9!_: %?9! .

METHODS* 199 ! '1$ IMPORTING ( !$1 TYPE ?, A%"&_A5 (. PRIVATE SECTION. DATA A5 ( TYPE ?. ENDCLASS. CLASS !9!_( @" DEFINITION.

, "

PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. CLASS !9!_: %?9! IMPLEMENTATION. METHOD 9' 1$ . CREATE OBJECT ' ). ENDMETHOD. METHOD 199 ! '1$ . *,e !s a+ !,/.!c!t.1 created .-ca. *refere+ce 0ar!ab.e, 4h!ch /-!+ts t- the *!+sta+ce !+ 4h!ch the ,eth-d !s curre+t.1 *be!+g e5ecuted" The stat!c t1/e -f ,e !s *the c.ass !+ 4h!ch the !+sta+ce ,eth-d !s *!,/.e,e+ted @ -LA5 ( + @ -LA5 ( , ( !$1. ENDMETHOD. METHOD A%"&_A5 (. DATA "D$5D$ TYPE A$'?7B. "D$5D$ + @ -LA5 (. MESSAGE "D$5D$ TYPE UIU. ENDMETHOD. ENDCLASS. CLASS !9!_( @" IMPLEMENTATION. METHOD @1?7. DATA : %_"23 TYPE REF TO !9!_: %?9! . *create the -b3ect a+d ass!g+ !t t*0eh2-b3 refere+ce : %_"23 + !9!_: %?9! +L9' 1$ O P. : %_"23-L199 ! '1$ O ( !$1 + -CC P. : %_"23-LA%"&_A5 (O P. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_( @"+L@1?7O P.

Aollowing is the out put produced by the above code.

, .

*rien!s Classes 4Suspen!ing %ncapsulation5


An e-ternal user can only access the public components of a class. Cowever/ in some cases/ classes must cooperate very closely so that they need to access the protected and private components of each other. To do this we can use the concept of friendship between classes. A class can offer friendship to other classes (and interfaces$ by using the FRIENDS addition in the class definition part behind which all classes (and interfaces$ are listed are granted friendship. )ranted friendship is a one&side process. A class that grants friendship is not automatically a friend of its friends. Inheritors of friends also become friendsK however/ the granting of friendship can not be inherited. The friend of a super class is not automatically the friend of its subclasses. A friendship should be used when a class is used as a container of data/ storing the services of classes in specific service class (agents$ and in test classes of ABAP 7nit. The FRIENDS must be specified as the last after the other additions. Aollowing is the synta-. CLASS 9- DEFINITION. ......... ENDCLASS. ..................... CLASS @49!1AA DEFINITION CREATE PRIVAE FRIENDS 9-. ......... ENDCLASS. , !

In listing below the !9!_: %?9! _1B 7$ is service class which must be declared as a friend of !9!_: %?9! class.
REPORT J_""5_)'? 7(.

CLASS !9!_: %?9! _1B 7$ DEFINITION DEFERRED. CLASS !9!_: %?9! DEFINITION CREATE PRIVATE FRIENDS !9!_: %?9! _1B 7$.

PUBLIC SECTION. METHODS* 199 ! '1$ IMPORTING ( !$1 TYPE ?, A%"&_A5 (. PRIVATE SECTION. DATA A5 ( TYPE ?. ENDCLASS. CLASS !9!_ >1@5! DEFINITION.

PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. CLASS !9!_: %?9! _1B 7$ DEFINITION. PUBLIC SECTION. CLASS-METHODS 9' 1$ ENDCLASS. CLASS !9!_: %?9! _1B 7$ IMPLEMENTATION. METHOD 9' 1$ . CREATE OBJECT ' ). ENDMETHOD. ENDCLASS. CLASS !9!_: %?9! IMPLEMENTATION. ( , ( !$1. RETURNING :1!D O' )P TYPE REF TO !9!_: %?9! .

METHOD 199 ! '1$ . @ -LA5 ( + @ -LA5 ENDMETHOD.

METHOD A%"&_A5 (. DATA "D$5D$ TYPE A$'?7B.

,,#

"D$5D$ + @ -LA5 (. WRITE* UV %?9! S5 ( ?A* ENDMETHOD. ENDCLASS. CLASS !9!_ >1@5!

U, "D$5D$.

IMPLEMENTATION.

METHOD @1?7. DATA : %_"23 TYPE REF TO !9!_: %?9! . : %_"23 + !9!_: %?9! _1B 7$+L9' 1$ O P. : %_"23-L199 ! '1$ O ( !$1 + -CC P. : %_"23-LA%"&_A5 (O P. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

If a local class is referred to within a class and the local class hasnEt been declared yet/ it must be made 5nown using local CLASS DEFINITION DEFERRED statement. This is becauseK the ABAP compiler compiles a program in one single process. If we donEt publish the local class/ the FRIENDS addition would cause a synta- error due to an un5nown class. Aollowing is the output of the above listing.

1arbage Collection
6b4ects occupy space in the main memory. If they are no longer needed/ they can and should be deleted. The garbage collector or )3 of the ABAP runtime environment is responsible for the delectation of ob4ects. The )3 deletes ob4ects that are no longer referenced by reference variables. The )3 is called periodically by the ABAP runtime environment. It traces reference variables of deleted ob4ects. This means/ if an ob4ect that is no longer referenced contains attributes of the reference variable type/ its references are traced by the )3. If no reference variable points to the ob4ects found in this process/ those ob4ects are deleted as well.

,,

8e can e-plicitly initiali'e references to ob4ects using the CLEAR statement. 6ther mechanisms that can cause references to ob4ects to disappear are for e-ampleK when a reference is assigned/ the original reference in the target variable is lost/ or a reference variable is a local variable of a method that is deleted when the method ends. 6n the other hand/ we should note that many references to ob4ects can e-ists @ that 5eep the ob4ects alive. Aor e-ample/ the methods of an ob4ect can be registered as event handlers or ob4ects are managed or used by framewor5 that can not be accessed directly. To delete these 5inds of references/ event handlers must be deregistered and special methods of the framewor5s must be called. 6therwise/ memory lea5s can occurs which may result in memory bottlenec5s/ particularly if many ob4ects or large ob4ects are used. Thus/ always release unused ob4ects for the )3 and use <emory Inspector too to chec5 if the garbage collection was successful.

Constructors
A constructor is a special method that is e-ecuted automatically by the runtime environment. 3onstructors are used to put an ob4ect into a defined initial status. As with all components of classes/ we distinguish between instance constructors and static constructors. Instance Constructor Instance 3onstructor is a predefined method of class called 9"7A$'D9$"'. This method is automatically e-ecuted once/ immediately after the creation of an ob4ect of the class. Thus/ instance constructor serves to initiali'e individual instances. It must be declared and implemented li5e a usual method. The instance constructor is reBuired to be declared in the public visibility section. Cowever/ the actual visibility is determined by where the class can be instantiated/ which is defined using the CREATE addition of CLASS DEFINITION. The parameter interface of an instance constructor is limited to input parameters (IMPORTING$/ because the instance constructor is e-clusively used to define an ob4ect status and is not supposed to provide any other behavior. The synta- for instance constructor of local classes is: CLASS !9!_@49!1AA DEFINITION CREATE PUBLIC;PROTECTED;PRIVATE. PUBLIC SECTIONS. METHODS 9"7A$'D9$"' 6IMPORTING I TYPE $4 K 8 KKKKKKK ENDCLASS. CLASS !9!_@49!1AA IMPLEMENTATION. METHOD 9"7A$'D9$"'. KKKK ,,,

ENDMETHOD. ENDCLASS. To create the constructor for global classes/ we can select the Edit 9reate 9onstructor function or the 9onstructor from application toolbar.

To fill the input parameters of the instance constructor with values/ the CREATE OBJECT statement contains an addition: CREATE OBJECT "23_' ) EXPORTING ? + 1. =ach non&optional input parameter ? must be lin5ed to an actual parameter 1 via the + sign after EXPORTING. If an e-ception occurs in an instance constructor/ the created ob4ect will be deleted immediately during the e-ecution of the CREATE OBJECT statement/ and the corresponding reference variable is set to its initial value. The following e-ample shows the use of the instance constructor.
REPORT J_""5_?7A$_9"7A$'D9$.

CLASS !9!_: %?9! DEFINITION. PUBLIC SECTION. METHODS* 9"7A$'D9$"' IMPORTING ?9"!"' TYPE A$'?7B, 199 ! '1$ IMPORTING ( !$1 TYPE ?, A%"&_A5 (. PRIVATE SECTION. DATA* 9"!"' TYPE A$'?7B, A5 ( TYPE ?. ENDCLASS. CLASS !9!_: %?9! IMPLEMENTATION.

METHOD 9"7A$'D9$"'. @ -L9"!"' + ?9"!"'. ENDMETHOD.

*c-+struct-r

,,0

METHOD 199 ! '1$ . @ -LA5 ( + @ -LA5 ENDMETHOD.

( , ( !$1.

METHOD A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + @ -LA5 (. CONCATENATE @ -L9"!"' U*U @AB INTO @AB. MESSAGE @AB TYPE UIU. ENDMETHOD. ENDCLASS. CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. CLASS !9!_ >1@5! METHOD @1?7. DATA* ' (_: TYPE REF TO !9!_: %?9! , 2!D _: TYPE REF TO !9!_: %?9! , B' 7_: TYPE REF TO !9!_: %?9! . CREATE OBJECT* ' (_: EXPORTING ?9"!"' + UR (U, 2!D _: EXPORTING ?9"!"' + UB!D U, B' 7_: EXPORTING ?9"!"' + UG' 7U. ' (_:-L199 ! '1$ O -CC P. 2!D _:-L199 ! '1$ O .CC P. B' 7_:-L199 ! '1$ O /CC P. ' (_:-LA%"&_A5 (O P. 2!D _:-LA%"&_A5 (O P. B' 7_:-LA%"&_A5 (O P. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P. IMPLEMENTATION.

Aollowing is the output of the above code listing.

,,1

Static Constructor The static constructor is a predefined method of a class called 9!1AA_9"7A$'D9$"'. This method is automatically e-ecuted once for each class in a program before the class is accessed for the first time. The static constructor is used to initiali'e the static attributes of a class. The static constructor must always be declared in the public visibility section of the class. A static constructor does not have any parameter interface. 8e use the static constructor to apply the Singleton pattern. The synta- for the static constructor of local classes is: CLASS !9!_@49!1AA DEFINITION. PUBLIC SECTION. CLASS-METHOD 9!1AA_9"7A$'D9$"'. KKKKK. ENDCLASS. CLASS !9!_@49!1AA IMPLEMENTATION. METHOD 9!1AA_9"7A$'D9$"'. KKKKK. ENDMETHOD. ENDCLASS. To implement the static constructor for global classes we can select the Edit 9reate 9lass 9onstructor function or the 9lass 9onstructor from application toolbar. Aollowing listing implements the static constructor.
REPORT J_""5_A$1$?9_9"7A$'D9$.

CLASS !9!_: %?9! _1B 7$ DEFINITION DEFERRED. CLASS !9!_: %?9! DEFINITION CREATE PRIVATE FRIENDS !9!_: %?9! _1B 7$.

,,D

PUBLIC SECTION. METHODS* 199 ! '1$ A%"&_A5 (.

IMPORTING ( !$1 TYPE ?,

PRIVATE SECTION. DATA A5 ( TYPE ?. ENDCLASS. CLASS !9!_: %?9! IMPLEMENTATION. METHOD 199 ! '1$ . @ -LA5 ( + @ -LA5 ( , ( !$1. ENDMETHOD. METHOD A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + @ -LA5 (. MESSAGE @AB TYPE UIU. ENDMETHOD. ENDCLASS. CLASS !9!_: %?9! _1B 7$ DEFINITION CREATE PRIVATE. PUBLIC SECTION. CLASS-DATA 1B 7$ TYPE REF TO !9!_: %?9! _1B 7$ READ-ONLY. CLASS-METHODS 9!1AA_9"7A$'D9$"'. METHODS 9' 1$ RETURNING :1!D O' )P TYPE REF TO !9!_: %?9! . ENDCLASS. CLASS !9!_: %?9! _1B 7$ IMPLEMENTATION. METHOD 9!1AA_9"7A$'D9$"'. CREATE OBJECT !9!_: %?9! _1B 7$+L1B 7$. ENDMETHOD. *c.ass2c-+struct-r METHOD 9' 1$ . CREATE OBJECT ' ). ENDMETHOD. ENDCLASS. CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. CLASS !9!_ >1@5! METHOD @1?7. IMPLEMENTATION.

,,G

DATA* 1B 7$ : %?9! TYPE REF TO !9!_: %?9! _1B 7$, TYPE REF TO !9!_: %?9! .

1B 7$ + !9!_: %?9! _1B 7$+L1B 7$. : %?9! + 1B 7$-L9' 1$ O P. : %?9! -L199 ! '1$ O -CC P. : %?9! -LA%"&_A5 (O P. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of the above e-ample.

Destructors
;estructor is class method which is called when the ob4ect is deleted by the garbage collection. In fact/ many 66P languages contain these 5inds of methods. Aor several reasons li5e performance/ transaction concept etc/ ABAP 6b4ects doesnEt provide any destructors for application development.

#ocal Declarations in Class Pool


3lass pool is a container for e-actly one global class and more than one data types and local ob4ect types (local classes and interfaces$. All the reusable code is programmed here. A class pool is loaded into memory by using the global class/ for e-ample/ a public method of global class can be called from another ABAP program or it can be lin5ed with a transaction code. They are declared with the CLASS-POOL statement but as it is created with 3lass Builder (S=,1$ of ABAP 8or5bench/ which means it is generally not displayed as a single continues source code. It is obvious that we can create local types/ classes and interfaces in class pool/ howeverK local data and processing bloc5s other than the methods are not permitted.

,,"

To create a local type in a class pool/ select Boto9lass(local *%pe@ocal 9lass de"initions!*%pes or @ocal *%pes from application toolbar in the class builder. This ta5es us to the ABAP =ditor for an include program that is integrated in the global declaration part of the class pool. Cere we can define program local types using TYPES statement. 2ocal types defined this way can be referenced only in private visibility section of the global declaration part of the global class. The local classes are declared in the same include program as local types. To create a local class in a class pool/ we must also select Boto9lass(local *%pe@ocal 9lass de"initions!*%pes or @ocal *%pes and to implement the local classes/ select Boto9lass( local *%pes@ocal 9lass implementations or 'mplementation from the application toolbar. This ta5es us to the ABAP =ditor for an include program that is integrated in the implementation part of the class pool.

8e can use local classes to modulari'e a class pool beyond the methods of the global class. In class pool local classes play the same roles as the local classes in other ABAP programs. They are not visible from outside. If we want to access the protected and private components of global class/ we must declare it as a local friend of the class. To do that/ we can use the following special statement: CLASS B!"21!_9!1AA DEFINITION LOCAL FRIENDS K.. !"91!_9!1AA KK This statement does not have an associated ENDCLASS statement and can be contained in the include for the local class definition. The modulari'ation of a global class through local classes of the class pool is a recommended procedure. The following e-ample demonstrates the use of local class in global class. . )oto transaction S=,1. ,. )ive a name and press create. A pop up window appears as5ing for short description/ instantiation (li5e Public/ Private/ Abstract and Protected$ and type of the class (normal ABAP 3lass$. Select the appropriate class type. If you donEt want to create any subclass of this class/ then chec5 the chec5bo- named %Ainal(.

,,.

0. 3reate 6b4ect ;irectory =ntry dialog appears/ assign the pac5age and clic5 save to continue. The 6b4ect ;irectory is a directory of all the *epository 6b4ects that ma5e up the SAP System. 8hen you create an ob4ect/ the corresponding ob4ect directory entry is also created.

1. 9e-t dialog prompt for transport reBuest. The transport reBuest our pac5age belongs to is already in the relevant field. Again 3onfirm it. D. 9ow you will get the class builder screen.

,,!

G. Arom application toolbar select 2ocal Types to define local class in the class pool. =nter the following lines of code/ save and e-it the editor.

". To implement the local class in class pool/ select the 'mplementation option from application toolbar and enter the following lines of code.

.. 3lic5 on methods tab. )ive a method name/ level (Instance or Static$/ visibility (Public / protected or private $ and description.

,0#

!. ;ouble clic5 on method name and you will get an editor to perform the coding. =nter the following code.

#. Save and activate the global class. . To consume the global class create report N_GLBL_CLIENT and enter the following code.

,0

,. Aollowing output is produced after e-ecuting the above code.

,0,

Inheritance
The inheritance mechanism for an 66P language provides options that help to reuse the same or similar parts of a class/ and create a hierarchy of classes. In ob4ect orientation/ inheritance refers to the speciali'ation of classes by deriving subclasses (derived or child classes$ from super classes (base class or parent class$. ;erived or more specific classes are referred to as Subclass/ while more general classes are called superclasses. ABAP 6b4ects implements the concept of simple inheritance/ according to this conceptK each class can have several subclasses but only one superclass. In simple inheritance/ inheritance relationships are represented by an inheritance tree. The root node of the inheritance tree in ABAP 6b4ects is the predefined/ empty and abstract class "23 9$. All classes in ABAP 6b4ects that do not e-plicitly inherit from another class are implicit direct subclasses of "23 9t. 8hen subclasses of e-plicitly defined classes are created/ these inherit the components of their superclasses and can add new components. The relationship between a subclass and its superclass should always be e-pressed as %is& a( relationship. Aor e-ample a he-agon is&a shape. 6n the other hand the %has&a( relationship also called aggregation or composition is based on usage/ rather than inheritance of a class. Aor e-ample a horse has&a halter.

Creating Subclasses
Inheritance relationship can only be defined when a subclass is declared. A superclass has no 5nowledge of any subclasses it may have. 6nly a subclass is aware that it is the heir+inheritor of another class. The synta- for deriving a subclass from a superclass is as follows: CLASS AD2_9!1AA DEFINITION INHERITING FROM AD5 '_9!1AA. ................ ENDCLASS. Any non&final class that is visible at this point can be specified for AD5 '_9!1AA. To create a subclass in the 3lass Builder/ select Superclass on the .roperties tab page. Then enter any non&final/ global class as a superclass in the Superclass field. The Undo inheritance and 9hange inheritance options allow to change the inheritance relationship.

,00

Aor each class that doesnEt have an e-plicit INHERITING FROM addition/ the system implicitly adds the INHERITING FROM "23 9$ addition/ which means that any class without an INHERITING addition is automatically a direct subclass of the "23 9$ root class. The e-ample below two classes car and truc5 are derived from vehicle class.
REPORT J_""5_?7% '?$179 .

CLASS !9!_: %?9! DEFINITION. PUBLIC SECTION. METHODS* 199 ! '1$ IMPORTING ?:$45 TYPE A$'?7B ?( !$1 TYPE ?, A%"&_A5 (. PROTECTED SECTION. DATA* A5 ( TYPE ?, :$45 TYPE A$'?7B. ENDCLASS. *.c.20eh!c.e DEFINITION

CLASS !9!_: %?9! IMPLEMENTATION. METHOD 199 ! '1$ . @ -LA5 ( + @ -LA5 ( , ?( !$1. @ -L:$45 + ?:$45 . ENDMETHOD. *acce.erate METHOD A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + @ -LA5 (. CONCATENATE :$45 U ?A $'1: !!?7B &?$% A5 ( + U @AB INTO @AB. WRITE @AB. ENDMETHOD. *sh-42s/eed ENDCLASS. *.c.20eh!c.e I8P(E8ENT#TION

,01

CLASS !9!_91' DEFINITION INHERITING FROM !9!_: %?9! . ENDCLASS. *.c.2car DEFINITIO CLASS !9!_$'D9W DEFINITION INHERITING FROM !9!_: %?9! . PUBLIC SECTION. METHODS* !"1( IMPORTING ?)' ?B%$ TYPE A$'?7B, D7!"1(. PROTECTED SECTION. DATA )' ?B%$ TYPE A$'?7B. ENDCLASS. *.c.2truc9

DEFINITIO

CLASS !9!_$'D9W IMPLEMENTATION. METHOD !"1(. @ -L)' ?B%$ + ?)' ?B%$. WRITE* UT'D9W ?A !"1( ( &?$%U, @ -L)' ?B%$. ENDMETHOD. *.-ad METHOD D7!"1(. CLEAR @ -L)' ?B%$. WRITE* UT'D9W ?A D!"1( (U, @ -L)' ?B%$. ENDMETHOD. *u+.-ad ENDCLASS. *.c.2truc9 I8P(E8ENT#TION CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. *.c.2e5a,/.e DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* 91'_' ) TYPE REF TO !9!_91', $'D9W_' ) TYPE REF TO !9!_$'D9W. CREATE OBJECT* 91'_' ), $'D9W_' ). 91'_' )-L199 ! '1$ O EXPORTING ?:$45 + UC1'U ?( !$1 + -/C P. 91'_' )-LA%"&_A5 (O P. SKIP. $'D9W_' )-L!"1(O UGD'U P. SKIP. $'D9W_' )-L199 ! '1$ O EXPORTING ?:$45 + UT'D9WU ?( !$1 + --C P.

,0D

$'D9W_' )-LA%"&_A5 (O P. SKIP. $'D9W_' )-LD7!"1(O P. ENDMETHOD. *,a!+ ENDCLASS. *.c.2e5a,/.e I8P(E8ENT#TION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

The !9!_91' and !9!_$'D9W classes both derived from !9!_: %?9! . Therefore/ they inherit the attribute and methods of the !9!_: %?9! class. Since speed is declared in the PROTECTED SECTION/ it is also visible in the subclasses. The !9!_$'D9W class is speciali'ed with an additional attribute for freight and additional methods for loading and unloading. Since !9!_91' class ob4ects are the same as that of the !9!_: %?9! class/ since no methods have been added/ !9!_91' doesnEt reBuire an implementation part. Aollowing is the output of the above code:

&isibilit" Sections in Inheritance


The public $isibilit% section of a subclass contains all public components of all superclasses/ plus its own additional public components. These components can be accessed e-ternally using component selectors. The protected $isibilit% section of a subclass contains all protected components of all superclass/ plus its own additional protected components. These components cannot be accessed e-ternally using component selectors. Arom an e-ternal point of view/ protected is the same as private. The pri$ate $isibilit% section of subclass contains only the subclassEs own private components. These components can only be accessed in the method implementations of the subclass. The private components are also inherited in principle/ but are not visible in the subclass.

,0G

A superclass is not aware of any subclasses it may have. If we create a non&final class in a class library and release it for use/ we can never 5now as a developer/ which subclasses our class will eventually have other than those we define our self. If we then subseBuently add new components to the public or protected section of our class/ and any of its subclasses happen to have a component of its own with the same name/ this become syntactically incorrect. Therefore/ it is only secure to add private components. To limit the subclasses of a class to at least the same pac5age/ non&final classes should preferably be organi'ed in pac5ages for which the .ackage 9heck as Ser$er property is activated. This ensures that only ob4ects declared in the pac5age interface of the pac5age can be addressed from other transportable pac5ages. A pac5age interface is a subset of the visible development elements of a pac5age that are visible e-ternally. A pac5age interface can also contain development elements of a subpac5age if they are included in a pac5age interface of the subpac5age.

Metho! 'e!e inition


8hen a method is called in the subclass/ it is e-ecuted in the same way it was implemented in the superclass. Cowever/ since the main purpose of inheritance is to speciali'e classes/ the behavior of the method of a superclass may be too general for the more specific purpose of the subclass. In some cases/ the implementation of superclass must be enhanced in the subclass/ while in other instancesK the implementation must be completely changed. Cowever/ the semantics of the method must remain stable for the e-ternal userK because all this user ever sees is the constant interface (including documentation$ and not the implementation itself. Instance methods can be redefined in subclasses to speciali'e the behavior of subclass ob4ects. Static methods can not be redefined. *edefining methods means creating a new implementation of the method is a subclass without changing the interface (ABAP 6b4ects doesnEt currently support method overloadingK i.e. methods are redefined with separate or changed parameter interface$. 8hen a method is redefined in a subclass/ an additional implementation is created/ which hides the previous implementation when the subclass and further subclasses are used. =very reference that refers to an ob4ect of the subclass uses the redefined method. 2i5e the methods belonging to the subclass/ a redefined method accesses the private attributes of the subclass. The synta- for redefining an instance method in a subclass is as follows: METHODS @4_@ $% REDEFINITION. This statement must be specified in the declaration part of the subclass in the same visibility section as the actual declaration of the method is the superclass. The definition of parameter interface is not repeated.

,0"

In the 3lass Builder/ we redefine an inherited method by displaying it on the Aethods tab. To do so/ we must use the UtilitiesSettings function of the 3lass Builder to select the Displa% 'nherited 9omponents lso entry. Then/ we must highlight the method and select the *edefine function. 9ow we can navigate to the implementation in the same way as with normal methods.

In the implementation of redefined method/ we can use the pseudo re"erence (AD5 '-L$ to access the original method of the direct superclass. This overrides the hiding of the redefined method. 8e can now apply method redefinition to our previous e-ample of inheritance.
REPORT J_""5_@ $%(_' ( ).

CLASS !9!_: %?9! DEFINITION. PUBLIC SECTION. METHODS* 199 ! '1$ IMPORTING ?( !$1 TYPE ?, A%"&_A5 (. PROTECTED SECTION. DATA* A5 ( TYPE ?. ENDCLASS. *.c.20eh!c.e DEFINITION

CLASS !9!_: %?9! IMPLEMENTATION. METHOD 199 ! '1$ . @ -LA5 ( + @ -LA5 ( , ?( !$1. ENDMETHOD. *acce.erate METHOD A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + @ -LA5 (. WRITE @AB. ENDMETHOD. ENDCLASS.

*sh-42s/eed *.c.20eh!c.e I8P(E8ENT#TION

CLASS !9!_91' DEFINITION INHERITING FROM !9!_: %?9! . PUBLIC SECTION.

,0.

METHODS A%"&_A5 ENDCLASS.

( REDEFINITION. *.c.2car DEFINITIO

CLASS !9!_91' IMPLEMENTATION. METHOD A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + @ -LA5 (. CONCATENATE UC1', S5 (* U @AB INTO @AB RESPECTING BLANKS. WRITE @AB. ENDMETHOD. *sh-42s/eed ENDCLASS. *.c.2car I8P(E8ENT#TION CLASS !9!_$'D9W DEFINITION INHERITING FROM !9!_: %?9! . PUBLIC SECTION. METHODS* 199 ! '1$ REDEFINITION, A%"&_A5 ( REDEFINITION, !"1( IMPORTING ?)' ?B%$ TYPE A$'?7B, D7!"1(. PROTECTED SECTION. DATA )' ?B%$ TYPE A$'?7B. PRIVATE SECTION. CONSTANTS @1>_A5 ENDCLASS. ( TYPE ? VALUE UXCU. *.c.2truc9 DEFINITIO

CLASS !9!_$'D9W IMPLEMENTATION. METHOD 199 ! '1$ . AD5 '-L199 ! '1$ O ?( !$1 P. IF @ -LA5 ( L !9!_$'D9W+L@1>_A5 (. @ -LA5 ( + !9!_$'D9W+L@1>_A5 (. ENDIF. ENDMETHOD. *acce.erate

METHOD A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + @ -LA5 (. CONCATENATE UT'D9W &?$% U @ -L)' ?B%$ U, S5 (* U @AB INTO @AB RESPECTING BLANKS. WRITE @AB. ENDMETHOD. METHOD !"1(. *sh-42s/eed

,0!

@ -L)' ?B%$ + ?)' ?B%$. ENDMETHOD.

*.-ad

METHOD D7!"1(. CLEAR @ -L)' ?B%$. WRITE* UT'D9W ?A D!"1( (U, @ -L)' ?B%$. ENDMETHOD. *u+.-ad ENDCLASS. *.c.2truc9 I8P(E8ENT#TION CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. *.c.2e5a,/.e DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* 91'_' ) TYPE REF TO !9!_91', $'D9W_' ) TYPE REF TO !9!_$'D9W. CREATE OBJECT* 91'_' ), $'D9W_' ). 91'_' )-L199 ! '1$ O -/C P. 91'_' )-LA%"&_A5 (O P. SKIP. $'D9W_' )-L!"1(O UGD'U P. $'D9W_' )-L199 ! '1$ O --C P. $'D9W_' )-LA%"&_A5 (O P. SKIP. $'D9W_' )-LD7!"1(O P. ENDMETHOD. *,a!+ ENDCLASS. *.c.2e5a,/.e I8P(E8ENT#TION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the out put of above listing.

,1#

Abstract Classes an! Metho!s


An abstract class provides a common definition for a super class that multiple sub classes can share. The synta- for defining an abstract class is: CLASS @4_9!1AA DEFINITION ABSTRACT. KKKKKKKKK ENDCLASS. Abstract class can:t be instantiated using CREATE OBJECT. Abstract class can have both abstract and non&abstract methods. ;erived class must implement all the abstract methods. An abstract method can be defined as: METHODS @4_@ $% ABSTRACT. An abstract method canEt be implemented in its own class/ but only in a concrete subclass. 3lass that:s not abstract is called a concrete class. The method implementation mechanism is same as we discussed in method redefinition section. The only difference to a real redefinition is that we can not use the pseudo reference (AD5 '-LP in the method. 3oncrete methods can call the abstract methods because the names and parameter interfaces are completely 5nown. In 3lass Builder/ select bstract in the 'nstantiation input field on the .roperties tab as shown below:

8e can identify a method as an bstract in 3lass Builder ;etail Hiew as:

,1

The previous e-ample can be implemented in abstract class as:


REPORT J_""5_12A$'19$_9!A.

CLASS !9!_: %?9! DEFINITION ABSTRACT. PUBLIC SECTION. METHODS* 199 ! '1$ IMPORTING ?( !$1 TYPE ?, A%"&_A5 ( ABSTRACT. PROTECTED SECTION. DATA A5 ( TYPE ?. ENDCLASS. *.c.20eh!c.e DEFINITION CLASS !9!_: %?9! IMPLEMENTATION. METHOD 199 ! '1$ . @ -LA5 ( + @ -LA5 ( , ?( !$1. ENDMETHOD. *acce.erate ENDCLASS. *.c.20eh!c.e I8P(E8ENT#TION CLASS !9!_91' DEFINITION INHERITING FROM !9!_: %?9! . PUBLIC SECTION. METHODS A%"&_A5 ( REDEFINITION. ENDCLASS. *.c.2car DEFINITIO CLASS !9!_91' IMPLEMENTATION. METHOD A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + @ -LA5 (. CONCATENATE UC1' A5 ( ?A* U @AB INTO @AB RESPECTING BLANKS. WRITE @AB. ENDMETHOD. *sh-42s/eed ENDCLASS. *.c.2car I8P(E8ENT#TION CLASS !9!_$'D9W DEFINITION INHERITING FROM !9!_: %?9! . PUBLIC SECTION.

,1,

METHODS* 199 ! '1$ REDEFINITION, A%"&_A5 ( REDEFINITION, !"1( IMPORTING )' ?B%$ TYPE A$'?7B, D7!"1(. PROTECTED SECTION. DATA )' ?B%$ TYPE A$'?7B. PRIVATE SECTION. CONSTANTS @1>_A5 ( TYPE ? VALUE UXCU. ENDCLASS. *.c.2truc9 DEFINITIO CLASS !9!_$'D9W IMPLEMENTATION. METHOD 199 ! '1$ . AD5 '-L199 ! '1$ O ?( !$1 P. IF @ -LA5 ( L !9!_$'D9W+L@1>_A5 (. @ -LA5 ( + !9!_$'D9W+L@1>_A5 (. ENDIF. ENDMETHOD. *acce.erate METHOD A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + @ -LA5 (. CONCATENATE UT'D9W &?$% U @ -L)' ?B%$ U, A5 (* U @AB INTO @AB RESPECTING BLANKS. WRITE @AB. ENDMETHOD. *sh-42s/eed METHOD !"1(. @ -L)' ?B%$ + )' ?B%$. ENDMETHOD. *.-ad METHOD D7!"1(. CLEAR @ -L)' ?B%$. WRITE UT'D9W ?A D7!"1( (U. ENDMETHOD. *u+.-ad ENDCLASS. *.c.2truc9 I8P(E8ENT#TION CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. *.c.2e5a,/.e DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* 91'_' ) TYPE REF TO !9!_91', $'D9W_' ) TYPE REF TO !9!_$'D9W. CREATE OBJECT* 91'_' ), $'D9W_' ). 91'_' )-L199 ! '1$ O -/C P. 91'_' )-LA%"&_A5 (O P. $'D9W_' )-L!"1(O UP"$1$"U P. SKIP.

,10

$'D9W_' )-L199 ! '1$ O --C P. $'D9W_' )-LA%"&_A5 (O P. SKIP. $'D9W_' )-LD7!"1(O P. ENDMETHOD. *,a!+ ENDCLASS. *.c.2e5a,/.e I8P(E8ENT#TION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of the above code.

*inal Classes an! Metho!s


A class or instance method can be declared as final to protect it from uncontrolled speciali'ation. The synta- for defining a final class is:
CLASS @4_9!1AA DEFINITION FINAL. KKKKKKKKK ENDCLASS.

<ethods of a final class are implicitly final and cannot be e-plicitly declared as final. In the 3lass Builder/ we can create a final class by selecting the 2inal chec5bo- on the .roperties tab.

In a non&final class/ individual instance methods can be declared as final. The synta- is:
METHODS @4_@ $% FINAL.

,11

In the 3lass Builder/ we can identify an instance method as 2inal in the Detail Vie#.

A final method canEt be redefined in subclasses. A final method canEt be abstract at the same time. A class can be abstract and final at the same time/ but only its static components are usable in this case. Although we can declare instance components in such a class/ it is not recommended.

Static Attributes an! Metho!s in Inheritance


A subclass can access the contents of the public and protected static attributes of all superclasses or a superclass shares itEs public and protected static attributes with all subclasses. Therefore/ static attributes in inheritance are not assigned to a single class/ but to a path of the inheritance tree. Static attributes can be accessed from outside via class component selector (+L$ using all class names involved/ or from inside in all affected classes where a static attribute is visible. 3hanges to the value are visible in all relevant classes. A static constructor is e-ecuted when a class is addressed for the first time. If a static attribute is addressed via the class name of a subclass but declared in a superclass/ only the static constructor of the superclass is e-ecuted. Static methods canEt be redefined in ABAP 6b4ects/ because static components should occur e-actly one in a inheritance path so that the can be shared by all subclasses. 2isting below shows a simple e-ample.
REPORT J_""5_?7%'$_A$1$?9.

CLASS !9!_@49!1AA- DEFINITION. PUBLIC SECTION. CLASS-DATA 1$$' TYPE A$'?7B. ENDCLASS. *.c.2,1c.ass: DEFINITION

,1D

CLASS !9!_@49!1AA. DEFINITION INHERITING FROM !9!_@49!1AA-. ENDCLASS. *.c.2,1c.ass2 DEFINITIO CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. *.c.2e5a,/.e DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. !9!_@49!1AA.+L1$$' + US$1$?9 1$$'?2D$ A ( @"U. MESSAGE !9!_@49!1AA-+L1$$' TYPE UIU. ENDMETHOD. *,a!+ ENDCLASS. *.c.2e5a,/.e I8P(E8ENT#TION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

After e-ecution the following message bo- is displayed.

Constructors in Inheritance
Instance constructor is used to set the instance attributes of every single ob4ect during instancing process/ the static constructor are is responsible for the static attributes of the class before the class is first accessed. Because a subclass inherits all attributes of its superclasses in inheritance/ this automatically begs the Buestion %Cow can the constructors ensure that the inherited attributes are initiali'ed as well when the subclass is usedV(

Instance Constructors
=very class has a predefined instance constructor named 9"7A$'D9$"'. Thus/ instance constructor deviate from the rule that there are only uniBue components names along the path of the inheritance tree. 3onseBuently/ the instance constructors of the individual classes of an inheritance tree must be completely independent of one another. To avoid naming conflicts/ the following rules apply:

,1G

Instance constructors of superclasses cannot be redefined in subclasses. Instance constructors cannot be e-plicitly called via the 9"7A$'D9$"' O P statement.

A subclass must ensure that the instance constructors of all superclasses are e-ecuted as well. Aor this purpose/ the instance constructor of every subclass must contain a call AD5 '-L9"7A$'D9$"'O K P. of the instance constructor of the direct superclass/ even if the constructor is not e-plicitly declared. The only e-ceptions to this rule are the direct subclasses of the root node/ "23 9$. In superclasses in which the instance constructor is not e-plicitly declared and implemented/ the implicitly e-isting implementation of the instance constructor is run. It automatically ensures that the instance constructor of the ne-t higher superclass is called. The e-ecution of a subclass instance constructor can be divided into three phases that are presented in the comment lines of listing below. METHOD 9"7A$'D9$"'. MP%1A --* A99 AA $" A$1$?9 1$$'?2D$ A "7!4 KKKKKKKKKKKKKKKK. MP%1A -.* E> 9D$?"7 ") AD5 ' 9!1AA 9"7A$'D9$"'OAP, M&%?9% ?A 1B1?7 (?:?( ( ?7 $%' 5%1A A ?) ?@5! @ 7$ ( AD5 '-L9"7A$'D9$"' EXPORTING K. MP%1A -/* A$$'?2D$ A ") AD5 '9!1AA 1' 9"'' 9$!4 M?7?$?1!?J (, 199 AA $" ?7A$179 1$$'?2D$ A "7!4 KKKKKKKKKKKKKKKK. ENDMETHOD. The methods of subclasses are not visible in constructors. If an instance constructor calls an instance method of the same class via the implicit self&reference (@ $/ the method is called in the way in which it is implemented in the class of the instance constructor/ and not the possibly redefined method of the subclass to be instantiated. 2isting below shows the behavior of instance constructors in inheritance using a simple e-ample.
REPORT J_""5_?7%'$_9"7A$D9$'.

CLASS !9!_: AA ! DEFINITION. PUBLIC SECTION. METHODS 9"7A$'D9$"' IMPORTING ?71@ TYPE A$'?7B. PROTECTED SECTION.

,1"

DATA 71@ ENDCLASS.

TYPE A$'?7B. *.c.20esse. DEFINITION

CLASS !9!_: AA ! IMPLEMENTATION. METHOD 9"7A$'D9$"'. 71@ + ?71@ . WRITE* S U!9!_: AA !*9"7A$'D9$"', 71@ +U, 71@ . ENDMETHOD. *c-+struct-r ENDCLASS. *.c.20esse. I8P(E8ENT#TION CLASS !9!_A%?5 DEFINITION INHERITING FROM !9!_: AA !. ENDCLASS. *.c.2sh!/ DEFINTION CLASS !9!_@"$"'A%?5 DEFINITION INHERITING FROM !9!_A%?5. PUBLIC SECTION. METHODS 9"7A$'D9$"' IMPORTING ?71@ TYPE A$'?7B ?)D !1@"D7$ TYPE ?. PRIVATE SECTION. DATA )D !1@"D7$ TYPE ?. ENDCLASS. *.c.2,-t-rsh!/ DEFINITIO CLASS !9!_@"$"'A%?5 IMPLEMENTATION. METHOD 9"7A$'D9$"'. AD5 '-L9"7A$'D9$"'O ?71@ P. )D !1@"D7$ + ?)D !1@"D7$. WRITE* S U!9!_@"$"'A%?5*9"7A$'D9$"', 71@ U, 71@ , U )D !1@"D7$ U, )D !1@"D7$. ENDMETHOD. *c-+struct-r ENDCLASS. *.c.2,-t-rsh!/ I8P(E8ENT#TION CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. *.c.2e5a,/.e DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* "23_: AA ! TYPE REF TO !9!_: AA !, "23_A%?5 TYPE REF TO !9!_A%?5, "23_@"$"A%?5 TYPE REF TO !9!_@"$"'A%?5. WRITE UC' 1$?7B V AA ! O23 9$U COLOR I. SKIP. CREATE OBJECT "23_: AA ! EXPORTING ?71@ + UG%1$1 K%?A$14U.

,1.

WRITE S UC' 1$?7B S%?5 O23 9$U COLOR I. SKIP. CREATE OBJECT "23_A%?5 EXPORTING ?71@ + UK%?A$14U. WRITE S UC' 1$?7B M"$"A%?5 O23 9$U COLOR I. SKIP. CREATE OBJECT "23_@"$"A%?5 ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P. EXPORTING ?71@ + UR1W"$14 K%?A$14U ?)D !1@"D7$ + 0CC. *,a!+ *.c.2e5a,/.e I8P(E8ENT#TION

Aollowing is the output of the above e-ample.

Static Constructors
=very class has a static constructor named 9!1AA_9"7A$'D9$"'. Along an inheritance tree the same rules that apply to the instance constructor also apply to the static constructor. 8hen a subclass is addressed for the first time in a program/ its static constructor is run. Before that/ however/ the preceding static constructors of the entire inheritance tree must have been run. Because a static constructor should be called only once during the e-ecution of a program/ when a subclass is addressed for the first time/ the ne-t higher superclass is searched whose static constructor has not yet run. Then this static

,1!

constructor is e-ecuted first/ followed by the constructors of all subclasses up to and including the addressed subclass. In contrast to instance constructors/ a static constructor does not have to e-plicitly call the static constructor of its superclass. Instead/ the runtime environment automatically ensures that the static constructors are called in the correct order. In a subclass/ we can always assume that the static attributes of the superclasses have been correctly initiali'ed. 9ote that the static constructors are parameter less. The previous e-ample is repeated with the use of static constructorsK note the difference between the output of both e-amples.
REPORT J_""5_?7%'$_9"7A$D9$'_A$1$?9.

CLASS !9!_: AA ! DEFINITION. PUBLIC SECTION. CLASS-METHODS 9!1AA_9"7A$'D9$"'. CLASS-DATA 71@ TYPE A$'?7B. ENDCLASS. *.c.20esse. DEFINITION CLASS !9!_: AA ! IMPLEMENTATION. METHOD 9!1AA_9"7A$'D9$"'. 71@ + UG%1$1 K%?A$14U. WRITE* S U!9!_: AA !*9!1AA_9"7A$'D9$"', 71@ +U, 71@ . ENDMETHOD. *c-+struct-r ENDCLASS. *.c.20esse. I8P(E8ENT#TION CLASS !9!_A%?5 DEFINITION INHERITING FROM !9!_: AA !. ENDCLASS. *.c.2sh!/ DEFINTION CLASS !9!_@"$"'A%?5 DEFINITION INHERITING FROM !9!_A%?5. PUBLIC SECTION. CLASS-METHODS 9!1AA_9"7A$'D9$"'. CLASS-DATA )D !1@"D7$ TYPE ?. ENDCLASS. *.c.2,-t-rsh!/ DEFINITIO CLASS !9!_@"$"'A%?5 IMPLEMENTATION. METHOD 9!1AA_9"7A$'D9$"'. 71@ + UR1W"$14 K%?A$14U. )D !1@"D7$ + -CC. WRITE* S U!9!_@"$"'A%?5*9!1AA_9"7A$'D9$"', 71@ + U, 71@ , U, )D !1@"D7$ U, )D !1@"D7$. ENDMETHOD. *c-+struct-r ENDCLASS. *.c.2,-t-rsh!/ I8P(E8ENT#TION CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. *.c.2e5a,/.e DEFINITION

,D#

CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* "23_: AA ! TYPE REF TO !9!_: AA !, "23_A%?5 TYPE REF TO !9!_A%?5, "23_@"$"'A%?5 TYPE REF TO !9!_@"$"'A%?5. WRITE UV AA ! C!1AAU COLOR I. SKIP. CREATE OBJECT "23_: AA !. WRITE S US%?5 C!1AAU COLOR I. SKIP. CREATE OBJECT "23_A%?5. WRITE S UM"$"A%?5 C!1AAU COLOR I. SKIP. CREATE OBJECT "23_@"$"'A%?5. ENDMETHOD. ENDCLASS. START-OF-SELECTION. !9!_ >1@5! +L@1?7O P. *,a!+ *.c.2e5a,/.e I8P(E8ENT#TION

Aollowing is the output.

Instantiation in Inheritance
The instantiation of subclass means the instantiation of all superclasses in a single ob4ect/ where the initiali'ation of the superclass attributes is ensured by calling the superclass constructors. The additions CREATE PUBLIC;PROTECTED;PRIVATE of the CLASS statement or the corresponding 3lass Builder settings/ respectively/ control for each class who can create an instance of the class or call its instance constructor. In inheritance/ this results in three scenarios whose behavior is defined in ABAP 6b4ects as follows:

,D

Superclass 5ith Public )nstantiation+ The instance constructor of the superclass is publicaly visible. If the instantiatiability of a subclass can be e-plicitly specified in one of the three ways. A subclass can control the visibility of its own instance constructor independently of the superclass. Superclass 5ith Protected )nstantiation+ The instance constructor of the superclass is visible in subclasses. If the instantiatiability of a subclass is not e-plicitly it inherits the protected instantiation of the superclass. The instantiatiability of a subclass can be e-plicitly specified in one of three ways. A subclass can control the visibility of its own instance constructor independently of the superclass and can thus also publish the protected instance constructor of the superclass in the specified section. Superclass 5ith Private )nstantiation+ The instance constructor of the superclass is visible only in the superclass. There are two different scenarios here: o The subclass is not a friend of the superclassK because only the superclass itself can call its instance constructor/ the subclass cannot be instantiated. Therefore/ the subclass has an implicit addition/ CREATE NONE. The instantiatiability if the subclass cannot be e-plicitly specified because this would mean a publication oft the superclass constructor in the specified section. o The subclass is a friend of the superclassK if the instantiatiability of the subclass has not been e-plicitly specified/ it inherits the private instantiation of the superclass. The instantiatiability of a subclass can be e-plicitly specified in one of the three ways. As a friend/ a subclass can publish the private constructor of the superclass in the specified section.

If a superclass with private instantiation has been defined in a path of the inheritance tree/ no subclass can be instantiated by e-ternal users/ and a subclass canEt even instantiate itself because it doesnEt have access to the instance constructor of the superclass. Thus/ a class defined for private instantiation should be mar5ed final to prevent subclasses. =-ception from this rule only e-ist if a privately instantiatable superclass offers its friendship to its subclasses.

,D,

Inter aces
Interfaces or standalone interfaces are li5e a ##\ abstract superclass that defines the methods a subclass must implement. <ethods of interface are all abstract. 2i5e the subclasses that implement the abstract methods of their abstract superclasses/ all classes that want to use an interface must implement its methods. 8ith the e-ception/ that we can also define static methods without implementation/ which is not possible in abstract classes because static methods can not be redefined. 8e can not directly create ob4ects of interfaces similar to abstract classes. If a class implements a standalone interface/ it can be addressed via this interface. There are specific interface reference variables for this purpose. These can point to ob4ects of all classes that contain the respective standalone interface. Because/ any classes can implement the same interface/ their ob4ects can be addressed via the same interface reference variable. Interfaces are used to achieve a decoupling between a class and a user. A very nice application e-ample of this decoupling is given by the enhancebility of delivered ABAP application programs in customer systems using Business Add&Ins (BAdIs$. BAdIs are based on standalone interfaces that are declared in the original system. The actual functionality of a BAdI is provided only in follow&up systems by implementing the standalone interface in classes.

Creating Inter aces


The declaration of interfaces hardly varies from the declaration of a class. As with classes/ we distinguish global and local interfaces in the same way that we do global and local classes. Therefore/ the same rules apply regarding their usability. )lobal interfaces can be used in any program if the pac5age assignment of the program permits it. 2ocal interfaces can only be used in the same program. The synta- for declaring a local interface is: INTERFACE !?)_71@ . DATA K. CLASS-DATA ... METHODS ... CLASS-METHODS ... ................. ENDINTERFACE. Interface can contain e-actly the same components as classes. 7nli5e classes/ however/ interfaces donEt need to be divided into different visibility sections because interface components has by default public visibility. The local interface should be prefi-ed with !?)_ .

,D0

To create a global interface/ use the 3lass Builder 4ust as we would for global classes. The global interface should be prefi-ed with ?)_ . Aigure below shows the 3lass Builder for a global interface. To create components we need to specify the same input as we do for classes/ e-cept for the assignment to a visibility section. In the shown screenshot/ we created the methods ACCELERATE and SHOW_SPPED.

The Aethod *%pe specifies whether the method is a normal method/ an event handler/ a constructor/ etc. The 3lass Builder generates the corresponding ABAP statements in an interface pool. An interface pool is a container for e-actly one global interfaceK it cannot contain any local type declarations e-cept for the publication of type groups/ the source code of which can also be edited directly via Boto'nter"ace Section.

,D1

There is no implementation part of an interface Therefore/ it is not necessary to add the DEFINITION to INTERFACE. The character (G$ is escape character that can be written directly before a name in order to distinguish it from an ABAP 5eyword of the same name in a statement.

Implementing Inter aces


A class can implement one or more interfaces. The essential reBuirement for implementing an interface is that the interface is 5nown to the implementing class. Therefore/ it must be declared globally in the class library or locally in the same program. Additionally/ the usage of the interface must be permitted by the pac5age assignment. The synta- for integrating the interface is: CLASS !9!_@4_9!1AA DEFINITION. PUBLIC SECTION. INTERFACES* ?7$)-, ?7$). ... KKKKKKKKKKKK. KKKKKKKK. ENDCLASS. 6nly global interfaces can be integrated in the public visibility section of a class. In 3lass Builder we can do this on the 'nter"aces tab in the 9hange 9lass window.

,DD

In the bstract and 2inal columns/ we can specify that all methods of the interface should be either abstract or final in the class. In the INTERFACES statement/ this is e-pressed by the optional addition ALL METHODS ABSTRACT;FINAL. Implementing an interface e-tends the public interface (section$ of the class by the interface components. =very component 9"@5 of an implemented interface ?7$) becomes a full component of the class and is identified within the class via the name K ?7$)[9"@5 K The tilde sign ([$ is the interface component selector. The prefi- ?7$)[ is helpful in avoiding the naming conflicts when a class has its own component of the same name li5e an interface component. 8e might be tempted to address/ the interface components of an ob4ect "23 as follows: "23-L?7$)[9"@5. In point of fact/ this wor5/ however/ this 5ind of access is not recommended. The interface component selector should only be used within classes and interfaces. To access the interface components of ob4ects/ we must use the reference variables that are declared with a reference to an interface: DATA ?7$)_' ) TYPE REF TO !?)_?7$ '). An interface reference variable ?7$)_' ) can point to the ob4ects of all classes implementing the !?)_?7$ ') interface. The interface reference variable only 5nows its own interface components. 6ther components (class specific components or components of other interfaces$ can not be addressed via an interface reference variable instead class reference variable should be used to address the non&interface components of the class. By simply assigning a class reference variable (pointing to an ob4ect$ to an interface reference variable enable us to access the interface components. This mechanism is 5nown as upcast. ?7$)_' ) + !9!_9!A.

If we are only interested in the interface components of a class/ we can create the ob4ect of the class via an interface reference variable as: CREATE OBJECT ?7$)_' ) TYPE !9!_9!A. =-ample below demonstrates the usage of interface reference variables. ,DG

REPORT

J_?7$ ')19 C-.

INTERFACE !?)_('?: _"23 9$. METHODS* 199 ! '1$ IMPORTING ?( !$1 TYPE ?, A%"&_A5 (. ENDINTERFACE. *.!f2dr!0e2-b3ect CLASS !9!_: %?9! DEFINITION. PUBLIC SECTION. INTERFACES* !?)_('?: _"23 9$. PRIVATE SECTION. DATA A5 ( TYPE ?. ENDCLASS. *.c.20eh!c.e DEFINITION CLASS !9!_: %?9! IMPLEMENTATION. METHOD !?)_('?: _"23 9$[199 ! '1$ . A5 ( + A5 ( , ?( !$1. ENDMETHOD. *.!f2dr!0e2-b3ect;acce.erate METHOD !?)_('?: _"23 9$[A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + A5 (. CONCATENATE UV %?9! S5 (* U @AB INTO @AB. WRITE S @AB. ENDMETHOD. *.!f2dr!0e2-b3ect;sh-42s/eed ENDCLASS. *.c.20eh!c.e I8P(E8ENT#TION CLASS !9!_ ! 9$'"7 DEFINITION. PUBLIC SECTION. INTERFACES* !?)_('?: _"23 9$. PRIVATE SECTION. CONSTANTS 9 TYPE ? VALUE /CCCCC. DATA A5 (_": '_9 TYPE 5 DECIMALS /. ENDCLASS. *.c.2e.ectr-+ DEFINITION CLASS !9!_ ! 9$'"7 IMPLEMENTATION. METHOD !?)_('?: _"23 9$[199 ! '1$ . @ -LA5 (_": '_9 + @ -LA5 (_": '_9 , ?( !$1 S 9. ENDMETHOD. *.!f2dr!0e2-b3ect;acce.erate METHOD !?)_('?: _"23 9$[A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + @ -LA5 (_": '_9. CONCATENATE UE! 9$'"7 S5 (SC* U @AB INTO @AB. WRITE S @AB. ENDMETHOD. *.!f2dr!0e2-b3ect;sh-42s/eed ENDCLASS. *.c.2e.ectr-+ I8P(E8ENT#TION CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. PRIVATE SECTION.

,D"

TYPES $12_?7$' ) TYPE TABLE OF REF TO !?)_('?: _"23 9$. CLASS-METHODS A%"&_@AB IMPORTING ?$12_?' ) TYPE $12_?7$' ). ENDCLASS. *.c.2e5a,/.e DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD A%"&_@AB. DATA ?') LIKE LINE OF ?$12_?' ). LOOP AT ?$12_?' ) INTO ?'). ?')-LA%"&_A5 (O P. SKIP. ENDLOOP. ENDMETHOD. *,sg METHOD @1?7. DATA* ?)_$12 TYPE $12_?7$' ), ?' ) LIKE LINE OF ?)_$12, : %_' ) TYPE REF TO !9!_: %?9! . CREATE OBJECT : %_' ) TYPE !9!_: %?9! . *u/caset!+g ?' ) + : %_' ). ?' )-L199 ! '1$ O -CC P. APPEND ?' ) TO ?)_$12. CREATE OBJECT ?' ) TYPE !9!_ ! 9$'"7. ?' )-L199 ! '1$ O .ICCCC P. APPEND ?' ) TO ?)_$12. !9!_ >1@5! +LA%"&_@ABO ?)_$12 P. ENDMETHOD. *.c.2e5a,/.e ENDCLASS. *.c.2e5a,/.e I8P(E8ENT#TION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

The output of the above code listing is shown below:

,D.

As far as the static components of interface are concerned/ we can only use the interface name to access the constants. ?7$) +L9"7A$_1$$'. The static attributes have different values depending on the class and the static methods can be differently implemented in every class. To access the static components of interfaces/ independently of the instance/ we would have to use the name of an implementing class and the interface component selector: 9!1AA_71@ +L?7$)[9"@5. =-ample below demonstrates the constants declared in an interface.
REPORT J_?7$ ')19 C.. ") ?7$ ')19 *!f2f:

INTERFACE !?)_)-. CONSTANTS 1$$ TYPE A$'?7B VALUE UC"7A$17$ 1$$'?2D$ U. ENDINTERFACE. CLASS !9!_9- DEFINITION. PUBLIC SECTION. ?7$ ')19 A* !?)_)-. ENDCLASS.

*.c.2c: DEFINITION

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. *.c.2e5a,/.e DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. WRITE !?)_)-+L1$$. SKIP. WRITE !9!_9-+L!?)_)-[1$$. ENDMETHOD. *,a!+ ENDCLASS. *.c.2e5a,/.e I8P(E8ENT#TION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of the above e-ample.

,D!

Composite an! Component Inter aces


The INTERFACES statement cannot only be used in classes but also in the declaration of an interface. This mechanism allows us to compose several interfaces into one interface. The composition of interfaces can be useful when modeling comple- applications. Aollowing is the synta-: INTERFACE !?)_71@ . INTERFACES* ?7$')19 -, ?7$ ')19 ., K KKKKKKKKKKKKKKKK ENDINTERFACE. 9ow the interface !?)_71@ integrates additional interfaces (?7$ ')19 -, ?7$ ')19 ., K$ and are composed of its own components plus the components of the integrated interfaces. In 3lass Builder we can compose other interface on the 'nter"aces tab. An interface containing at least one other interface is called composite or nested interface. An interface integrated in another interface is called a component interface. *ote+ ll component inter"ace o" a composite inter"ace are on the same le$el& o" names like !+tterface<;!+terface2;!+terface2 is not possible& 3onsider the e-ample: INTERFACE !?)_?7$ ')19 -. KKKKKK ENDINTERFACE. INTERFACE !?)_?7$ ')19 .. INTERFACES* !?)_?7$ ')19 - K KK.. ENDINTERFACE. INTERFACE !?)_?7$ ')19 /. INTERFACES* !?)_?7$ ')19 -, !?)_?7$ ')19 . K KK... nesting

,G#

ENDINTERFACE. In the e-ample above the component interface !?)_?7$ ')19 - of the composite interface !?)_?7$ ')19 . becomes a component interface of !?)_?7$ ')19 /. A composite interface contains each component interface e-actly once. Although !?)_?7$ ')19 - is integrated in !?)_?7$ ')19 / both directly as a component interface of !?)_?7$ ')19 / and indirectly via !?)_?7$ ')19 ./ it only occurs once. In !?)_?7$ ')19 // it can be addressed under the name !?)_?7$ ')19 -/ even if it was not integrated directly. If a composite interface is implemented in a class/ all interface components of the interface behave as if their interface had been implemented only once. Because every interface is included e-actly once in a composite interface/ naming conflicts cannot occur. The way an implemented interface is composed is irrelevant when it is implemented in a class. 3onsider the ne-t e-ample: INTERFACE !?)_?7$ ')19 -. METHODS @ $%. ENDINTERFACE. INTERFACE !?)_?7$ ')19 .. INTERFACES !?)_?7$ ')19 -. METHODS @ $%. ENDINTERFACE. INTERFACE !?)_?7$ ')19 /. INTERFACES !?)_?7$ ')19 -. METHODS @ $%. ENDINTERFACE. INTERFACE !?)_?7$ ')19 0. INTERFACES* !?)_?7$ ')19 ., !?)_?7$ ')19 /. ENDINTERFACE. CLASS !9!_( @" DEFINITION. PUBLIC SECTION. INTERFACES !?)_?7$ ')19 0. ENDCLASS. CLASS !9!_( @" IMPLEMENTATION. METHOD !?)_?7$ ')19 -[@ $%. ....... ENDMETHOD. METHOD !?)_?7$ ')19 .[@ $%. ....... ENDMETHOD. METHOD !?)_?7$ ')19 /[@ $%. ,G

....... ENDMETHOD. ENDCLASS. A method @ $% of the same name is declared in three individual interfaces and thus implemented in three different ways using the interface component selector. The composition of the interfaces does not play any role. The !?)_?7$ ')19 [@ $% method is implemented only once/ although it occurs in two interfaces , !?)_?7$ ')19 . and !?)_?7$ ')19 /. If we list one or more of other interfaces (!?)_?7$ ')19 -, !?)_?7$ ')19 . "' !?)_?7$ ')19 /$ in addition to !?)_?7$ ')19 0 in the declaration part of the !9!_( @"/ the components and the implementation part of the class do not change at all/ because the compiler always ensures for a class as well as in composite interfaces that every component e-ists only once. If the class implements a composite interface/ the interface components should be accessed using interface reference variable of the type of the appropriate component interface. This can be achieved through upcasting. The interface component selector should not be used for this purposeK however/ it can be used in a composite interface to ma5e the components of component interfaces as accessible as native components via aliasing.

Alias Names
The complete name of a component that is added via an interface to a class or another interface is ?7$)[9"@5. Aor this name/ we can define an alias name at the level at which the interface is integrated using the INTERFACES statement: ALIASES 71@ FOR ?7$)[9"@5.

Alias names can be assigned when interfaces are implemented in the declaration part of a class or when interfaces are composed in the declaration of an interface. In the 3lass Builder we can enter alias names for classes and for interfaces in the liases tab.

,G,

In classes/ alias names belong to the namespace of the components of a class and must be assigned to a visibility section 4ust li5e the other components. The visibility of an alias name from outside the class depends on its visibility section and not on the visibility section of the assigned interface component. 2isting below shows the usage of alias names.
REPORT J_?7$ ')19 C/.

INTERFACE !?)_('?: _"23 9$. METHODS* 199 ! '1$ IMPORTING ?( !$1 TYPE ?, A%"&_A5 (. ENDINTERFACE. \!?)_('?: _"23 9$ CLASS !9!_: %?9! DEFINITION. PUBLIC SECTION. INTERFACES* !?)_('?: _"23 9$. PRIVATE SECTION. DATA A5 ( TYPE ?. ENDCLASS. \!9!_: %?9!

DEFINITION

CLASS !9!_: %?9! IMPLEMENTATION. METHOD !?)_('?: _"23 9$[199 ! '1$ . A5 ( + A5 ( , ?( !$1. ENDMETHOD. \!?)_('?: _"23 9$[199 ! '1$ METHOD !?)_('?: _"23 9$[A%"&_A5 (. DATA @AB TYPE A$'?7B. @AB + A5 (. CONCATENATE UV %?9! S5 (* U @AB INTO @AB. WRITE S @AB. ENDMETHOD. \!?)_('?: _"23 9$[A%"&_A5 ( ENDCLASS. \!9!_: %?9! IMPLEMENTATION CLASS !9!_ ! 9$'"7 DEFINITION. PUBLIC SECTION. INTERFACES* !?)_('?: _"23 9$. ALIASES 199 ! '1$ FOR !?)_('?: _"23 9$[199 ! '1$ . PRIVATE SECTION. CONSTANTS 9 TYPE ? VALUE /CCCCC. DATA A5 (_": '_9 TYPE 5 DECIMALS /. ENDCLASS. \!9!_ ! 9$'"7 DEFINITION CLASS !9!_ ! 9$'"7 IMPLEMENTATION. \?7A$ 1( ") \METHOD !?)_('?: _"23 9$[199 ! '1$ . METHOD 199 ! '1$ . @ -LA5 (_": '_9 + @ -LA5 (_": '_9 , ?( !$1 S 9. ENDMETHOD. \!?)_('?: _"23 9$[199 ! '1$ METHOD !?)_('?: _"23 9$[A%"&_A5 (. DATA @AB TYPE A$'?7B.

,G0

@AB + @ -LA5 (_": '_9. CONCATENATE UE! 9$'"7 S5 (SC* U @AB INTO @AB. WRITE S @AB. ENDMETHOD. \!?)_('?: _"23 9$[A%"&_A5 ENDCLASS. \!9!_ ! 9$'"7 IMPLEMENTATION CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. PRIVATE SECTION. TYPES $12_?7$' ) TYPE TABLE OF REF TO !?)_('?: _"23 9$. CLASS-METHODS A%"&_@AB IMPORTING ?$12_?' ) TYPE $12_?7$' ). ENDCLASS. \!9!_ >1@5! DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD A%"&_@AB. DATA ?') LIKE LINE OF ?$12_?' ). LOOP AT ?$12_?' ) INTO ?'). ?')-LA%"&_A5 (O P. SKIP. ENDLOOP. ENDMETHOD. \@AB METHOD @1?7. DATA* ?')_$12 TYPE $12_?7$' ), ?')_' ) LIKE LINE OF ?')_$12, : %_' ) TYPE REF TO !9!_: %?9! , ! _' ) TYPE REF TO !9!_ ! 9$'"7. CREATE OBJECT : %_' ). ?')_' ) + : %_' ). ?')_' )-L199 ! '1$ O -CC P. APPEND ?')_' ) TO ?')_$12. 9' 1$ OBJECT ! _' ). ?')_' ) + ! _' ). ?')_' )-L199 ! '1$ O .CC P. APPEND ?')_' ) $" ?')_$12. !9!_ >1@5! +LA%"&_@ABO ?')_$12 P. ENDMETHOD. \!9!_ >1@5! ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

The interface method is implemented in the class via its alias name and called by a user li5e a direct method of the class. Thus using alias names/ a class can publish its interface components as class&specific components. Aollowing is the output of the above code listing.

,G1

9ote/ because names can not be concatenated in composite interfaces/ alias names provide the only means of addressing those components that would otherwise not be available in the composite interface. Aor e-ample: INTERFACE ?7$)-. METHODS @ $%-. ENDINTERFACE. INTERFACE ?7$).. INTERFACES ?7$)-. ALIASES @ $%- FOR ?7$)-[@ $%-. ENDINTERFACE. INTERFACE ?7$)/. INTERFACES ?7$).. ALIASES @ $%- FOR ?7$).[@ $%-. ENDINTERFACE. The ?7$)/ interface can use the alias name @ $%- in ?7$). to address the @ $%component of the ?7$)- interface in its own ALIASES statement. 8ithout alias names in ?7$)./ this would not be possible because the name ?7$).[?7$)-[@- is not permitted. 9ow the user of ?7$)/ can accesses the component @ $%- in ?7$)as: ?' )-L@ $%-O P. 8ithout alias names in intf0/ the access would loo5 as follows: ?' )-L?7$)-[@ $%-O P.

Inter aces an! Inheritance


The usage of inheritance always ma5es sense when different classes have generali'ation+speciali'ation relationship. The advantage of inheritance is that the subclasses reuse all properties already programmed in the superclass/ but at the same time/ this causes a very tight coupling (dependency$ between superclass and subclasses.

,GD

That is a subclass strongly depends on its superclass. =very change to non&private components of a superclass changes all of its subclasses. As a software engineering principle we must follow the loose coupling or decoupling rule. The interfaces or stand alone interfaces can be used to achieve the loose coupling. Interfaces allow the user to handle the most different classes/ which donEt need to be related to each other. In 66 modeling/ interfaces provide an abstraction that is independent of classes. Irrespective of the actual implementation/ the services reBuired by a user can be described. Additionally/ interfaces also implement an aspect of multiple inheritance because several interfaces can be implemented in the class. In interface multiple inheritance/ the diamond problem (A method that is declared in a superclass is redefined in two subclasses/ which/ in turn/ ma5e up the superclass of another subclass/ which implementation is used in this subclassV$ does not occur/ because in the implementation of composite interfaces every interface method e-ists only once.

,GG

Pol"morphism
The term polymorphism literally means %many forms(. Arom an ob4ect&oriented perspective/ the term is used to describe a language feature that allows you to use instances of classes belonging to the same inheritance hierarchy interchangeably. In a polymorphic design/ we can create generic methods. This generic approach to programming is often described using the term design by interface. The basic concept here is to adopt a component&based architecture where each component clearly defines the services (i.e. interface$ they provide. These interfaces ma5e it easy for components to be weaved together into larger assemblies. Cere/ notice that we havenEt said anything about how these components are implemented. As long as the components implement the services described in their interface @ it really doesnEt matter how they are implemented. Arom an ob4ect&oriented perspective/ this means that we can swap out a given ob4ect for another so long as they share the same interface. In order to do so/ we need to be able to perform type casts and dynamic method calls.

$"pe Casting an! D"namic Bin!ing


<ost of the time/ whenever we tal5 about the type of an ob4ect reference variable in ABAP 6b4ects/ we are tal5ing about its static type. The static type of an ob4ect reference variable is the type that is specified after the TYPE REF TO addition in declaration as: DATA "23_' ) TYPE REF TO 9!1AA;?7$ ')19 . The static type is fi-ed during entire runtime of the program. An ob4ect reference variable also has a dynamic type associated with it. The dynamic type of an ob4ect reference variable is the class of the ob4ect to which the ob4ect reference variable is currently pointing. The reference variable usually receives its dynamic type via assignment/ parameter transfers or via CREATE OBJECT statement as: CREATE OBJECT "23_' ) TYPE 9!1AA. 9ormally/ the static and dynamic type of an ob4ect reference variable will be the same as: CREATE OBJECT "23_' ). Cere dynamic type will be similar to static type of "23_' ). Cowever/ it is technically possible for an ob4ect reference variable to point to an ob4ect that is not an instance of the class type used to define the ob4ect reference. According to the golden rule of reference variables/ %The static type always more general or eBual to the dynamic type(. The syntachec5 and the ABAP runtime environment ensure that this rule is never bro5en. The actual meaning of the golden rule for the two possible types of reference variables in ABAP 6b4ects is:

,G"

Aor a class reference variable/ the static type is a classK the dynamic type can be the same class or one of its subclasses. Aor an interface variable/ the static type is an interface. The dynamic type can be any class implementing the interface/ particularly even a subclass of such a class.

Aor e-ample/ notice how we are assigning an instance of the !9!_!?"7 subclass to the ' )_17?@1! ob4ect reference variable (whose static type is the parent class !9!_17?@1!$ in the code e-cerpt below. DATA* ' )_17?@1! ' )_!?"7 TYPE REF TO !9!_17?@1!, TYPE REF TO !9!_!?"7.

CREATE OBJECT ' )_17?@1!. CREATE OBJECT ' )_!?"7. ' )_17?@1! + ' )_!?"7. This 5ind of assignment is not possible without a type cast. 8e canEt perform a type cast using 4ust any classK the source and target ob4ect reference variables must be compatible (e.g./ their static types must belong to the same inheritance hierarchy$. In the e-ample above/ once the assignment is completed/ the dynamic type of the ' )_17?@1! reference variable will be the !9!_!?"7 class. Therefore/ at runtime/ when a method call such as %' )_17?@1!-L%D7B'4O P( is called/ the ABAP runtime environment will use the dynamic type information to bind the method call with the implementation provided in the !9!_!?"7 class. The type cast above is classified as a narro#ing cast (or upcast$ as we are narrowing the access scope of the referenced !9!_!?"7 ob4ect to the components defined in the !9!_17?@1! superclass. In upcast we only assign more specific reference variables (e.g. subclass$ to eBual or more general (e.g. superclass$ ones and thus we can only move upwards in the inheritance tree. An up cast assignment can be performed using the eBual sign (+$ or the MOVE TO statement. The opposite of narrowing cast is #idening cast (or do#ncast$ li5es this: DATA* ' )_17?@1! ' )_!?"7 TYPE REF TO !9!_17?@1!, TYPE REF TO !9!_!?"7.

CREATE OBJECT ' )_17?@1! TYPE !9!_!?"7. ' )_!?"7 ]+ ' )_17?@1!. In this case/ we are using the TYPE addition to the CREATE OBJECT statement to create an instance of class !9!_!?"7 and assign its reference to the ' )_!?"7 ob4ect

,G.

reference variable. Then/ we use the casting operator (]+ or ]TO in case of MOVE$ to perform a widening cast when we assign the ' )_17?@1! ob4ect reference to ' )_!?"7. The Buestion mar5 e-plicitly shifts the chec5ing of the golden rule from the synta- chec5 to the program runtime. The assignment is only e-ecuted if the golden rule is then fulfilled for the target variableK otherwise/ the e-ception CX_SY_MOVE_CAST_ERROR is caused/ which can be handed in a TRY control structure. In downcast a more general reference variable (e.g. superclass$ is assigned to a more specific reference variable (e.g. superclass$ and we thus move downward in the inheritance tree. 2isting below shows an e-ample of up cast and down cast in inheritance.
REPORT J_?7% '?$_("&7_D5_91A$C-.

CLASS !9!_17?@1! DEFINITION. PUBLIC SECTION. METHODS* %D7B'4. ENDCLASS. \!9!_17?@1! DEFINITION CLASS !9!_!?"7 DEFINITION INHERITING FROM !9!_17?@1!. PUBLIC SECTION. METHODS* %D7B'4 REDEFINITION, )1A$?7B. ENDCLASS. \!9!_!?"7 DEFINITION CLASS !9!_17?@1! IMPLEMENTATION. METHOD %D7B'4. WRITE* S UA7 17?@1! ?A %D7B'4U. ENDMETHOD. \%D7B'4 ENDCLASS. \!9!_17?@1! IMPLEMENTATION CLASS !9!_!?"7 IMPLEMENTATION. METHOD %D7B'4. WRITE* S UA L?"7 OK?7B ") JD7B! P ?A %D7B'4.U, U RD7 1A )1A$ 1A 4"D 917..GU . ULINE AT S.XOEP. ENDMETHOD. \%D7B'4 METHOD )1A$?7B. WRITE* S US$"5 'D77?7B. L?"7 ?A "7U, UF1A$?7B $"(14.U. ULINE AT S.EOFP. ENDMETHOD. \)1A$?7B ENDCLASS. \!9!_!?"7 IMPLEMENTATION CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. \!9!_ >1@5! CLASS !9!_ >1@5! IMPLEMENTATION.

DEFINITION

,G!

METHOD @1?7. DATA* ' )_17?@1! ' )_!?"7 ' )_!?"7_$ @5 ' )_91A$_ ''"'

TYPE TYPE TYPE TYPE

REF REF REF REF

TO TO TO TO

!9!_17?@1!, !9!_!?"7, !9!_!?"7, 9>_A4_@": _91A$_ ''"'.

\D591A$ OAD29!1AA ?A 1AA?B7 ( $" AD5 '9!1AAP CREATE OBJECT ' )_!?"7_$ @5. ' )_17?@1! + ' )_!?"7_$ @5. \("&791A$ OAD5 '9!1AA ?A 1AA?B7 ( $" AD29!1AAP \&?$% A $$?7B D5 $% 5'"5 ' "23 9$ ' ) ' 79 ?7 $% ' 79 TRY. ' )_!?"7 ]+ ' )_17?@1!. CATCH 9>_A4_@": _91A$_ ''"' INTO ' )_91A$_ ''"'. WRITE* S UD"&7 91A$ )1?! ( -U COLOR + E. ENDTRY. IF ' )_!?"7 IS NOT INITIAL. CALL METHOD ' )_!?"7-L%D7B'4O P. SKIP. CALL METHOD ' )_!?"7-L)1A$?7BO P. ENDIF. SKIP. \("&791A$ &?$%"D$ A $$?7B D5 $% $% SD5 ' ' ) ' 79 CLEAR* ' )_17?@1!, ' )_!?"7, ' )_91A$_ ''"'. CREATE OBJECT ' )_17?@1!. TRY. ' )_!?"7 ]+ ' )_17?@1!. CATCH 9>_A4_@": _91A$_ ''"' INTO ' )_91A$_ ''"'. WRITE* S UD"&7 91A$ )1?! ( .U COLOR + E. ENDTRY. IF ' )_!?"7 IS NOT INITIAL. CALL METHOD ' )_!?"7-L%D7B'4O P. CALL METHOD ' )_!?"7-L)1A$?7BO P. ENDIF. ENDMETHOD. ENDCLASS. \@1?7 \!9!_ >1@5! IMPLEMENTATION 5'"5 ' "23 9$ ' ) ' 79 ?7 SD5 ' ' )

,"#

START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of above code listing.

2isting below shows an e-ample of the down cast when using the interfaces.
REPORT J_?7% '?$_("&7_91A$C.. IMPORTING ?( !$1 TYPE ?, (.

INTERFACE !?)_('?: . METHODS* 199 ! '1$

A%"&_A5 ENDINTERFACE. CLASS !9!_ ! 9$'"7 DEFINITION. PUBLIC SECTION. INTERFACES* !?)_('?: , ?)_A '?1!?J12! _"23 9$. PRIVATE SECTION. CONSTANTS 9 TYPE ? VALUE /CCCCC. DATA A5 (_": '_9 TYPE 5 DECIMALS /. ENDCLASS. \!9!_ ! 9$'"7 DEFINITION CLASS !9!_: %?9! DEFINITION. PUBLIC SECTION. INTERFACES !?)_('?: . PRIVATE SECTION. DATA A5 ( TYPE ?. ENDCLASS. \!9!_: %?9!

DEFINITION

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. PRIVATE SECTION. TYPES ?' )_$12 TYPE TABLE OF REF TO !?)_('?: . CLASS-METHODS* @AB IMPORTING ?$12 TYPE ?' )_$12, A '?1!?J IMPORTING ?' ) TYPE REF TO !?)_('?: . ENDCLASS. \!9!_ >1@5! DEFINITION

,"

CLASS !9!_ ! 9$'"7 IMPLEMENTATION. METHOD !?)_('?: [199 ! '1$ . @ -LA5 (_": '_9 + @ -LA5 (_": '_9 , ?( !$1 S 9. ENDMETHOD. \!?)_('?: [199 ! '1$ METHOD !?)_('?: [A%"&_A5 (. DATA "D$5D$ TYPE A$'?7B. "D$5D$ + @ -LA5 (_": '_9. CONCATENATE UE! 9$'"7 A5 (S9* U "D$5D$ INTO "D$5D$. WRITE S "D$5D$. ENDMETHOD. \!?)_('?: [A%"&_A5 ( ENDCLASS. \!9!_ ! 9$'"7 IMPLEMENTATION CLASS !9!_: %?9! IMPLEMENTATION. METHOD !?)_('?: [199 ! '1$ . A5 ( + A5 ( , ?( !$1. ENDMETHOD. \!?)_('?: _"23 9$[199 ! '1$ METHOD !?)_('?: [A%"&_A5 (. DATA "D$5D$ TYPE A$'?7B. "D$5D$ + A5 (. CONCATENATE UV %?9! S5 (* U "D$5D$ INTO "D$5D$. WRITE S "D$5D$. ENDMETHOD. \!?)_('?: [A%"&_A5 ( \!?)_('?: [199 ! '1$ ENDCLASS. \!9!_: %?9! IMPLEMENTATION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* ?7$')_' )A TYPE ?' )_$12, ?' ) LIKE LINE OF ?7$')_' )A. CREATE OBJECT ?' ) TYPE !9!_: %?9! . ?' )-L199 ! '1$ O -CC P. APPEND ?' ) TO ?7$')_' )A. CREATE OBJECT ?' ) TYPE !9!_ ! 9$'"7. ?' )-L199 ! '1$ O .ICCCC P. APPEND ?' ) TO ?7$')_' )A. !9!_ >1@5! +L@ABO ?7$')_' )A P. ENDMETHOD. \@1?7 METHOD @AB. DATA ?' ) LIKE LINE OF ?$12. LOOP AT ?$12 INTO ?' ). ?' )-LA%"&_A5 (O P. A '?1!?J O ?' ) P. ENDLOOP. ENDMETHOD. \@AB

,",

METHOD A '?1!?J . DATA* A '!_' ) >@!_A$' TRY.

TYPE REF TO ?)_A '?1!?J12! _"23 9$, TYPE >A$'?7B.

A '!_' ) ]+ ?' ). \C1!!A $% A5 9?)? ( XSLTSST, XSLT ") $% ' 5"A?$"'4 \XSLTSST ?A 5'"B'1@@?7B !17BD1B )"' ( A9'?2?7B $'17A)"'@ \2 $& 7 ABAP (1$1 17( XML )"'@1$A.XSLTSST 5'"B'1@A 1' T'17A)"'@1$?"7 E(?$"' OSTRANSP. F?'A$ 51'1@ $

1$?"7A (?$ ( ' ?A

\DA?7B $%

\$% $'17A)"'@1$?"7 $" DA )'"@ $% ' 5"A?$"'4 CALL TRANSFORMATION ?( SOURCE "23 9$ + A '!_' ) RESULT XML >@!_A$' . CATCH 9>_A4_@": _91A$_ ''"'. RETURN. ENDTRY. \T% DISPLAY_XML_STRING )D79$?"7 @"(D! ") $% ' 5"A?$"'4 \(?A5!14A $% ' AD!$ ") A '?1!?J1$?"7 ?7 17 HTML 2'"&A ' 9"7$ '"! CALL FUNCTION UDISPLAY_XML_STRINGU EXPORTING >@!_A$'?7B + >@!_A$'. ENDMETHOD. \A '?1!?J ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

The IF_SERIALINABLE_OBJECT is a predefined tag interface. By integrating the tag interface/ classes or other interfaces stand out against the ABAP runtime environment. A tag interface generally does not contain its own interface components/ but instead assigns a particular tas5 to the integrating classes or interfaces and changes the way they are handled by the ABAP 3ompiler. 6nce the IF_SERIALINABLE_OBJECT is integrated in the class/ the attributes of that class ob4ect can seriali'ed to I<2 using the CALL TRANSFORMATION statement. Before seriali'ation ta5es place/ the interface reference variable is chec5ed if the referenced ob4ect is seriali'able. This happens using the down cast. Aollowing is the output produced by the above code listing.

,"0

Implementing Pol"morphism
The e-ample code below defines an abstract base class called !9!_17?@1! and two concrete subclasses: !9!_91$ and !9!_("B. In order to ma5e the See&n&Say generic/ we define the interface of the %5!14OP( method to receive an instance of class !9!_17?@1!. Cowever/ in the @1?7 method/ youEll notice that we create instances of !9!_91$ and !9!_("B and pass them to the See&n&Say. Cere/ we didnEt have to perform an e-plicit type cast as narrowing type casts are performed implicitly in method calls. Aurthermore/ since the !9!_91$ and !9!_("B classes inherit the methods %B $_$45 OP( and %A5 1WOP( from class !9!_17?@1!/ we can use instances of them in the !9!_A _17(_A14 generically.

,"1

REPORT

J_5"!4@"'5%?A@C-.

CLASS !9!_17?@1! DEFINITION ABSTRACT. PUBLIC SECTION. METHODS* B $_$45 ABSTRACT, A5 1W ABSTRACT. ENDCLASS. \!9!_17?@1! DEFINITION CLASS !9!_91$ DEFINITION INHERITING FROM !9!_17?@1!. PUBLIC SECTION. METHODS* B $_$45 REDEFINITION, A5 1W REDEFINITION. ENDCLASS. \!9!_91$ DEFINITIO CLASS !9!_("B DEFINITION INHERITING FROM !9!_17?@1!. PUBLIC SECTION. METHODS* B $_$45 REDEFINITION, A5 1W REDEFINITION. ENDCLASS. \!9!_("B DEFINITIO CLASS !9!_A _17(_A14 DEFINITION. PUBLIC SECTION. CLASS-METHODS* 5!14 IMPORTING ?@_17?@1! TYPE REF TO !9!_17?@1!. ENDCLASS. \!9!_A _17(_A14 DEFINITION CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. \!9!_ >1@5! CLASS !9!_91$ IMPLEMENTATION. METHOD B $_$45 . WRITE* UC1$U. ENDMETHOD. METHOD A5 1W. WRITE* UM "&U. ENDMETHOD. ENDCLASS. CLASS !9!_("B IMPLEMENTATION. METHOD B $_$45 . WRITE* UD"BU. ENDMETHOD. METHOD A5 1W. WRITE* UB1'WU. ENDMETHOD.

DEFINITION

\B $_$45

\A5 1W \!9!_91$ IMPLEMENTATION

\B $_$45

\A5 1W

,"D

ENDCLASS.

\!9!_("B IMPLEMENTATION

CLASS !9!_A _17(_A14 IMPLEMENTATION. METHOD 5!14. WRITE* UT% U. CALL METHOD ?@_17?@1!-LB $_$45 . WRITE* UA14AU. CALL METHOD ?@_17?@1!-LA5 1W. ENDMETHOD. \5!14 ENDCLASS. \!9!_A _17(_A14 IMPLEMENTATION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* ' )_91$ TYPE REF TO !9!_91$, ' )_("B TYPE REF TO !9!_("B. CREATE OBJECT ' )_91$. CREATE OBJECT ' )_("B. _17(_A14+L5!14O EXPORTING ?@_17?@1! + ' )_91$ P. NEW-LINE. !9!_A _17(_A14+L5!14O EXPORTING ?@_17?@1! + ' )_("B P. ENDMETHOD. \@1?7 ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P. !9!_A

As mentioned earlier/ one of the primary advantages of using polymorphism in a design li5e this is that we can easily plug in additional animals without having to change anything in class !9!_A _17(_A14. Aollowing output is produced by e-ecuting the above code.

,"G

The following e-ample demonstrates the polymorphism using both interfaces and abstract classes. . 3reate and activate the table J$_199"D7$A as shown below:

,. To create and activate the global interface J_?)_199"D7$ open the 3lass Builder (S=,1$ as shown below:

,""

0. 3reate and activate the global abstract class J_9!_199"D7$ as shown below:

,".

1. 9e-t to implement the methods of J_9!_199"D7$, double clic5 each method to write code for it/ as show below:

,"!

D. The following concrete global class J_9!_9% 9W?7B_199"D7$ speciali'es the abstract J_9!_199"D7$ as shown below:

,.#

G. The

redefined &?$%('1& method of concrete global class J_9!_A1:?7BA_199"D7$ throws an e-ception when the account is overdrawn.

,.

The following application program wor5s with ban5 accounts in a very general way.
REPORT J_?7$ ')19 _217W?7B.

CLASS !9!_199"D7$_@171B @ 7$ DEFINITION. PUBLIC SECTION.

,.,

METHODS %17(! _( 2?$_21!179 "D7$

FOR EVENT ": '('1& OF J_9!_9% 9W?7B_199 IMPORTING ?( 1@"D7$.

ENDCLASS.

\!9!_217W_@171B @ 7$ DEFINITION

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS* @1?7, &?$%('1& IMPORTING 199"D7$ TYPE REF TO J_?)_199"D7$ 1@"D7$ TYPE J$199"D7$A-1@"D7$, $'17A) ' IMPORTING A"D'9 TYPE REF TO J_?)_199"D7$ $1'B $ TYPE REF TO J_?)_199"D7$ 1@"D7$ TYPE J$199"D7$A-1@"D7$. ENDCLASS. \!9!_ >1@5! DEFINITION CLASS !9!_199"D7$_@171B @ 7$ IMPLEMENTATION. METHOD %17(! _( 2?$_21!179 . DATA $ >$ TYPE A$'?7B. $ >$ + 1@"D7$. CONCATENATE ^H17(!?7B ( 2?$ ^ $ >$ ^ )"' 199"D7$ ^ ?( INTO $ >$. MESSAGE $ >$ TYPE UIU. ENDMETHOD. \%17(! _( 2?$_21!179 ENDCLASS. \!9!_217W_@171B @ 7$ IMPLEMENTATION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD &?$%('1&. DATA $>$ TYPE A$'?7B. TRY. 199"D7$-L&?$%('1&O 1@"D7$ P. CATCH J9>_7 B1$?: _1@"D7$. $>$ + 199"D7$-L?(. CONCATENATE UW?$%('1&1! 7"$ 5"AA?2! MESSAGE $>$ TYPE UIU. ENDTRY. ENDMETHOD. \&?$%('1&

)'"@ U $>$ INTO $>$.

METHOD $'17A) '. DATA $>$ TYPE A$'?7B. TRY. A"D'9 -L$'17A) 'O 1@"D7$ + 1@"D7$ $1'B $ + $1'B $ P. CATCH J9>_7 B1$?: _1@"D7$. $>$ + A"D'9 -L?(. CONCATENATE UT'17A) ' 7"$ 5"AA?2! )'"@ U $>$ INTO $>$.

,.0

MESSAGE $>$ TYPE UIU. ENDTRY. ENDMETHOD. \$'17A) ' METHOD @1?7. DATA* 199TYPE REF TO J_?)_199"D7$, 199. TYPE REF TO J_?)_199"D7$, 199_%17(! ' TYPE REF TO J9!_199"D7$_@171B @ 7$. CREATE OBJECT* 199- TYPE J_9!_9% 9W?7B_199"D7$ EXPORTING ?( + UCCCCX-IU, 199. TYPE J_9!_A1:?7BA_199"D7$ EXPORTING ?( + UCCCC0-IU, 199_%17(! '. \' B?A$ ' $% : 7$ %17(! ' SET HANDLER 199_%17(! '-L%17(! _( 2?$_21!179 FOR ALL INSTANCES. !9!_ >1@5! +L&?$%('1&O 199"D7$ + 1991@"D7$ + -CC P. !9!_ >1@5! +L$'17A) 'O A"D'9 + 199$1'B $ + 199. 1@"D7$ + ICC P. !9!_ >1@5! +L&?$%('1&O 199"D7$ + 199. 1@"D7$ + -CCC P. !9!_ >1@5! +L$'17A) 'O A"D'9 + 199. $1'B $ + 1991@"D7$ + -CCC P. ENDMETHOD. \@1?7 ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of above e-ample.

,.1

%vents an! %vent 8an!ling


=vents enable the ob4ects of a class or a class itself to publish changes to its state/ and other ob4ects and classes can then react to this change of state. Before going deep into the details of events lets consider an e-ample how events wor5. Aboard an aircraft there are passengers/ cabin crew and the pilots. The passenger and pilots can press a button that calls a flight attendant. As soon as the event %button pressed( occurs/ the flight attendant determines who pressed the button and performs an appropriate action. In the above e-ample we are dealing with three classes (passenger/ pilot/ and cabin crew$. The instances of the passenger/ pilot classes are able to trigger events (button pressed$ in which the instances of class cabin crew ta5e interest and react accordingly by e-ecuting an appropriate method. But events can not be implemented using normal direct method calls. As to call a normal method/ the address must be 5nown and a called method must always react. But in the above caseK we donEt 5now which cabin crew instance is going to react to the button pressed event (address of method not 5nown$ and the cabin crew instance can decided not to ac5nowledge the button pressed event as they are ignored during ta5e&off and landing (method not always react$. CoweverK triggering events is an indirect method call. The event concept established through the Publish&and&Subscribe mechanism. This mechanism ta5es place on two levelsK i.e. statically at the time of declaration and dynamically at the time of program e-ecution. The Publish&and Subscribe mechanism in ABAP 6b4ects are implemented as follows:

,.D

!vents+ A class can contain events as static or instance components. =very method of that class can trigger those events. !vent Handler+ An event handler is a method of another class or the same class that can handle an event/ that is/ that can be indirectly called by the event. The role of a method as an event handler is statically specified during its declaration. !vent Handler #egistration+ The handling of an event by a proper event handler can be e-plicitly registered/ without an appropriate registration/ no handling ta5es place.

Declaring %vents
=vents declaration is the static publishing of events in Publish&and&Subscribe mechanism. =vents can be declared in one of the three visibility sections of the class or in an interface. The synta- for declaring instance and static events are: 6CLASS-8 EVENTS : 7$_71@ 6EXPORTING K VALUEO51'1@-P TYPE $45 . . .8.

Instance events can only be triggered in instance methods. Static events can be triggered in instance and static methods. An event has an optional parameter interface that may e-clusively contain output parameters that are passed by value. This interface enables the transfer of actual parameters to the formal parameters of event handlers when events are triggered. The parameter interface of event handler is determined by the parameter interface of the event. 9oteK each instance event also has an implicit output parameter named A 7( '. This output parameter has the type of an ob4ect reference variable. After the event has been triggered using the RAISE EVENT statement/ A 7( ' points to the triggering ob4ect. In 3lass Builder the events are declared on the E$ents tab as show in the figure below:

The parameter interface is declared as for methods/ where the type of the parameter does not have to be specified.

,.G

$riggering %vents
The triggering of an event is the dynamic publishing in Publish&and&Subscribe mechanism. In instance methods/ we can trigger the instance events and the static events of the corresponding classK in static methods/ we can only trigger the static events. The synta- for triggering an event is as follows: RAISE EVENT : 7$_71@ EXPORTING ... 51'1@? + :1!D ? ...

This statement interrupts the e-ecution of the method and e-ecutes all event handlers registered for the event in the order of their registration. Then the triggering method is continued behind the RAISE EVENT statement. =vents cal also be triggered during event handling. 7sing the EXPORTING addition/ actual parameters must be attached to all non&optional e-porting parameters of the event. By doing so/ the input parameters of the event handlers are provided with values.

%vent 8an!lers
=vent handler declaration is the static subscription in Publish&and&Subscribe mechanism. =very class can contain event handlers for the events of other classes or their own class. =vent handlers are methods that are specifically identified as such shown below: 6CLASS-8METHODS %17(! '_71@ FOR EVENT : 7$_71@ OF 9!1AA;?7$ ')19 IMPORTING K 51'1@? K 6A 7( '8. The addition FOR EVENT ma5es a method an event handler and assigns it to e-actly one event of a 9!1AA or an ?7$ ')19 . The class or interface specified for the event handler determines which ob4ects or classes can trigger the e-ecution of the event handler. In an instance event/ an event handler can be triggered by all ob4ects/ the classes of which are eBual to or more specific than 9!1AA or that implements the ?7$ ')19 directly or via super class. Aor a static event/ the same applies to the class. The parameter interface of an event handler may e-clusively contain input parameters that were defined with the same names as output parameters when the event was declared. An event handler does not need to ta5e all parameters/ with e-ception of the implicit parameter A 7( '. In 3lass Builder the event handler can be defined in the Detail Vie# of methods as shown below:

,."

7nder the Parameters/ only parameters of the event/ including the predefined A 7( ' parameter can be entered.

'egistering %vent 8an!lers


=vent handler registration is the dynamic subscription in Publish&and&Subscribe mechanism. Aor an event handler to react to a triggered event/ it must be registered accordingly at runtime. The registration couples event handlers to triggers. This coupling can be dissolved at any time. The synta- for registering event handlers for instance event is: SET HANDLER %17(! '- %17(! '. K FOR "23_' );6ALL INSTANCES8 6ACTIVATION 19$8. This statement registers the event handlers %17(! '-, %17(! '., K for corresponding instance events of the ob4ect to which the "23_' ) reference variable provided after FOR is pointing. The event handlers are specified li5e the methods of a static method call. The static type of "23_' ) is restricted by the specified event handler. It must be more specific or eBual to the 9!1AA classes and implement all ?7$ ')19 A that were used when declaring the individual event handlers. 8hen "23_' ) is specified/ event handlers are registered for the events of e-actly one ob4ect. Alternately/ using ALL INSTANCES/ event handlers can be registered for all ob4ects/ the instance events of which they can handle. This registration also applies to all ob4ects that are not created until after the SET HANDLER statement.

,..

In static events/ the addition FOR is omitted and the registration is performed for all classes and interfaces that can be handled by the specified handler. This means that in one statement/ either only instance events or only static events can be registered. The addition ACTIVATION determines if the specified handlers are to be registered (I$ or deregistered (% %$/ where registration is the default setting. Technically/ every registration is eBual to a line in a invisible system table. The following e-ample demonstrates the use of event handling in detail.
REPORT J_ : 7$_%17(!?7B.

CLASS !9!_5?!"$ DEFINITION. PUBLIC SECTION. EVENTS 2D$$"7_5' AA (. METHODS 91!!_)!?B%$_1$$ 7( 7$. ENDCLASS. *.c.2/!.-t DEFINITION CLASS !9!_51AA 7B ' DEFINITION. PUBLIC SECTION. DATA 9!A TYPE A$'?7B READ-ONLY. METHODS 9"7A$'D9$"' IMPORTING ?A 1$_7" TYPE ? ?9!A TYPE A$'?7B. EVENTS 2D$$"7_5' AA ( EXPORTING :1!D O A 1$_7"P TYPE ?. METHODS 91!!_)!?B%$_1$$ 7( 7$. PRIVATE SECTION. DATA A 1$_7" TYPE ?. ENDCLASS. *.c.2/asse+ger DEFINITION CLASS !9!_)!?B%$_1$$ 7( 7$ DEFINITION. PUBLIC SECTION. METHODS 9"7A$'D9$"' IMPORTING ?$?$! TYPE A$'?7B. METHODS % !5_$% _5?!"$ FOR EVENT 2D$$"7_5' AA ( OF !9!_5?!"$. METHODS % !5_$% _51AA 7B ' FOR EVENT 2D$$"7_5' AA ( OF !9!_51AA 7B ' IMPORTING A 1$_7" A 7( '. PRIVATE SECTION. DATA $?$! TYPE A$'?7B. ENDCLASS. *.c.2f.!ght2atte+de+t DEFINITION CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. *.c.2e5a,/.e DEFINITION CLASS !9!_5?!"$ IMPLEMENTATION. METHOD 91!!_)!?B%$_1$$ 7( 7$. RAISE EVENT 2D$$"7_5' AA (. ENDMETHOD. *ca..2f.!ght2atte+de+t

,.!

ENDCLASS.

*.c.2/!.-t I8P(E8ENT#TION

CLASS !9!_51AA 7B ' IMPLEMENTATION. METHOD 9"7A$'D9$"'. @ -LA 1$_7" + ?A 1$_7". @ -L9!A + ?9!A. ENDMETHOD. *c-+struct-r METHOD 91!!_)!?B%$_1$$ 7( 7$. RAISE EVENT 2D$$"7_5' AA ( EXPORTING A 1$_7" + @ -LA 1$_7". ENDMETHOD. *ca..2f.!ght2atte+de+t ENDCLASS. *.c.2/esse+ger I8P(E8ENT#TION CLASS !9!_)!?B%$_1$$ 7( 7$ IMPLEMENTATION. METHOD 9"7A$'D9$"'. @ -L$?$! + ?$?$! . ENDMETHOD. *c-+struct-r METHOD % !5_$% _5?!"$. DATA $>$ TYPE A$'?7B. CONCATENATE @ -L$?$! U % !5A 5?!"$ U INTO $>$ RESPECTING BLANKS. MESSAGE $>$ TYPE UIU. ENDMETHOD. *he./2the2/!.-t METHOD % !5_$% _51AA 7B '. DATA $>$ TYPE A$'?7B. $>$ + A 1$_7". CONCATENATE @ -L$?$! U % !5A U A 7( '-L9!A U 51AA 7B ' "7 A 1$ U $>$ INTO $>$ RESPECTING BLANKS. MESSAGE $>$ TYPE UIU. ENDMETHOD. *he./2the2/asse+ger ENDCLASS. *.c.2f.!ght2atte+de+t I8P(E8ENT#TION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* 5?!"$ TYPE REF TO !9!_5?!"$, 51AA 7B '- TYPE REF TO !9!_51AA 7B ', 51AA 7B '. TYPE REF TO !9!_51AA 7B ', 1$$ 7( 7$- TYPE REF TO !9!_)!?B%$_1$$ 7( 7$, 1$$ 7( 7$. TYPE REF TO !9!_)!?B%$_1$$ 7( 7$. CREATE OBJECT* 5?!"$, 51AA 7B '- EXPORTING ?A 1$_7" + -?9!A + UBDA?7 AA C!1AAU, 51AA 7B '. EXPORTING ?A 1$_7" + .// ?9!A + UE9"7"@4 C!1AAU, 1$$ 7( 7$- EXPORTING ?$?$! + UK"@1!U, 1$$ 7( 7$. EXPORTING ?$?$! + UA4 A%1U. SET HANDLER* 1$$ 7( 7$--L% !5_$% _5?!"$ FOR 5?!"$, 1$$ 7( 7$.-L% !5_$% _51AA 7B ' FOR ALL INSTANCES. 5?!"$-L91!!_)!?B%$_1$$ 7( 7$O P.

,!#

51AA 7B '--L91!!_)!?B%$_1$$ 7( 7$O P. 51AA 7B '.-L91!!_)!?B%$_1$$ 7( 7$O P. ENDMETHOD. *,a!+ ENDCLASS. *.c.2e5a,/.e I8P(E8ENT#TION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of the above code listing.

,!

Share! -b.ects
The ob4ects we dealt with so far reside in the internal session of an ABAP program. This means these ob4ects can be accessed only within an internal session. If we recall the topic %<emory 6rgani'ation of Application Server ABAP( we find that the only shared memory of the application server is suitable for storing ob4ects that can be accessed by all of the programs of ABAP server. Aor freBuent database access/ AS ABAP includes an implicit mechanism called SAP buffering/ where the raw data from the database is already buffered in the shared memory. Aor e-plicit and 66 access to the shared memory/ shared ob4ects have been introduced in SAP 9et8eaver ,##1. Shared memory contains an area called Shared 6b4ects <emory where ob4ects can be stored as shared ob4ects. This includes both instances of classes and anonymous data ob4ects (data ob4ects created with CREATE DATA statement$. The following sections introduce the programming interface for shared ob4ects.

Areas
The management and access to the shared ob4ects memory are performed via areas. The shared ob4ects memory is divided into area instances that can e-ist in different versions. The actual shared ob4ects are stored in the area instance versions. An area is a repository ob4ect that describes the technical properties of area instances. The term %area( in this conte-t should not be confused with a memory area in the shared ob4ect memory/ which applies only to area instances. There can be several area instances of an area. In simple terms/ an area is 4ust a collection of settings that describe the properties of area instances/ li5e versioning/ lifetime and so forth. Aor every area/ a global area class of the same name is generated. Cowever/ this is not a template for area instances but for area handles. An area handle is an ob4ect of an area class whose methods can be used by ABAP programs to access the area instances of the relevant area and thus the shared ob4ects stored therein. Area calluses provide the only possible means of access from ABAP programs to the shared ob4ects memory.

,!,

To store ob4ects as shared ob4ects in area instances/ their classes must be identified as shared memory enabled as follows: CLASS 9!A_71@ DEFINITION K SHARED MEMORY ENABLED.

In 3lass Builder/ the Shared Aemor%(Enabled property must be selected as:

;uring definition/ every area must be assigned a global shared memory&enabled class as an area root class. An area instance where shared ob4ects are stored must contain at least one instance of the area root class as a root ob4ect. The root ob4ect can contain wor5ing data itself and reference other shared ob4ects (instances of shared memory&enabled classes or data ob4ects$ of the area instance. An area handle has an attribute named ROOT that can be used to address the root ob4ect.

Accessing Share! -b.ects


The access to shared ob4ects is achieved via an area handle/ that is/ by means of an ob4ect of an area class. The shared ob4ects are stored in an area instance version in the shared memory. The properties of area handle and area instance are specified by the corresponding area in the ABAP 8or5bench. Aigure below depicts the access to shared ob4ects.

,!0

The initial access from internal session to the shared ob4ects of an area instance is always achieved via the area handle ROOT reference variable pointing to the root ob4ect. The figure above shows an area instance version with two shared ob4ects/ the root ob4ect and another ob4ect. Arom an internal session/ a reference to a shared ob4ect can only be used as long as this session is connected to the area instance via an area handle/ because this handle provides the reBuired loc5 of the area instance. The "' ) reference shown in this figure should therefore be resolved for security reasons before the access via the area handle is terminated. The same applies to references from shared ob4ects to ob4ects of the internal session. 8hile an area instance version is attached to an internal session via an area handle/ it can be regarded as its e-tension. Area instance versions to which no area handles are attached are ideally self&contained/ that is/ there should only be references within an area instance version. The static attributes of a shared memory&enabled class are not treated differently from those of a normal class.

Creating an Area
The ABAP 8or5bench includes the Area <anagement tool (T3ode/ SC<A$ to create an area. The creation of an area generates the area class of the same name. Therefore/ the area name should follow the naming conventions for global classes. =very area class inherits from the predefined class CL_SHM_AREA/ which/ in turn/ inherits from CL_ABAP_MEMORY_AREA. =very area handle therefore contains a set of predefined methods and attributes. 8hen an area is created/ the area properties are set. These are divided into basic properties/ fi-ed/ dynamic and runtime area properties. Basic Properties

,!1

The basic properties of an area are considered when the area class is generated. 8hen the basic properties of an area are changed during operation/ all area instance versions of the area are set to e-pired and the area class is regenerated. The basic properties are: rea Name: The name of an area. This is also the name of the generated global area class and is therefore uniBue across the system. It is recommended that you follow the naming conventions for global classes in the current system/ and use the prefi- %CL_%. rea 0oot 9lass: The area root class is a global shared memory&enabled class that has to be assigned to an area when it is defined. The ROOT attribute of a corresponding area handle is generated as a reference variable with the static type of the area root class. 9lient Dependent rea: An area can be described as client&dependent. In this case/ an area instance of the area is identified by a client identifier as well as by its name. 8ith client&dependent areas/ the area class methods refer to accessing an area instance on the current client. 8ith client&dependent areas/ these methods have an additional input parameter/ CLIENT/ which enables e-plicit access to other clients. rea Build *%pe: If this property is set/ a new area instance is created automatically at the time selected in the area build type. *ransactional rea: Transactional area enables data or ob4ects in the area instance versions to 4oin such areas to database contents.

*iAe! Properties The fi-ed properties determine the conte-t of an area and whether versioning ta5es place as: rea Binding: This property determines the visibility and lifetime of the area instance versions of the instance by specifying a conte-t. Possible conte-ts are: Application Server/ Session/ =-ternal Session/ and ABAP <emory. rea 'nstance Versioning: This property defines whether there can be only one or several area instance versions of an area instance. 8ithout versioning/ there is only one version and the area instance is eBuivalent to this area instance version.

D"namic Properties The dynamic properties of an area are not considered when the area class is generated. 8hen the dynamic properties of an area are changed dynamically during operation/ the current area instance versions (versions that are being built/ are active or are obsolete$ are not affected. The new dynamic properties are not used until the ne-t change loc5 is set in the corresponding version that is being built. rea 9onstructor 9lass: Any global class that implements the IF_SHM_BUILD_INSTANCE interface can be specified as an area constructor

,!D

class. The implementation of the IF_SHM_BUILD_INSTANCE[BUILD interface method is used as the area constructor. Displacement *%pe: This property determines whether and how instances of the area can be displaced. ;isplacement may be necessary if the available addressing area of the shared memory is not sufficient for all area instance versions. Possible displacement types are: ;isplacement 9ot Possible/ ;isplacement Possible with Bac5up and *ecovery and ;isplacement Possible.

'untime Depen!ent Properties The same points apply to runtime&dependent properties of an area as to dynamic area properties/ with the difference that they can only be given default values by a developer and can also be changed without a developer 5ey/ for e-ample by administrators/ during 3ustomi'ing or during operation. *untime dependent properties are: Area Build Type/ Area Si'e/ Si'e of an Area Instance Hersion/ 9umber of Hersions of an Area Instance/ and 2ifetime of an Area Instance. As an e-ample/ we would create a simple area that can be used in applications wor5ing with the flight data model.

,!G

The global class J_9!_)!?B%$_!?A$ contains an internal table )!?B%$_!?A$ of the e-isting type A5)!?_$12 from the ABAP ;ictionary/ which is filled by a A $_)!?B%$_!?A$ method. This table contains the unchangeable data that is to be accessed from different programs. 9e-t open the Area <anagement tool (T3ode/ SC<A$ to set properties for J_9!_)!?B%$A area as shown below:

,!"

8e turned off the versioning because we are not planning to change the data in the area instance at program runtime and restrict the lifetime. The restriction of the lifetime

,!.

prevents space in the shared memory from being consumed without actually being used by the program.

#oc+ing
The access to shared ob4ects is controlled via loc5s. The loc5ing concept of shared ob4ects is similar to that of a file system. This means that there are e-clusive loc5s for creating or changing shared ob4ects in area instances/ and read loc5s for accessing shared ob4ects. 0ead @ock: If a read loc5 is set for an area in program/ the current area instance version can be read. 8ithin an internal session/ there can be ma-imum of one read loc5 for an area instance. Across several sessions/ there can be several read loc5s on an area instance versions. /rite @ock: If a write loc5 is set for an area in a program/ a new area instance version can be created and can be populated with data. Update @ock: If an update loc5 is set for an area in a program/ the data of the current area instance version can be changed for areas without versioning. Aor areas with versioning/ a new are instance version is created that can then be changed.

A change loc5 (write or update loc5$ loc5s an area instance version e-clusively. 6nly previous versions can be read&accessed in parallel. 6n AS there can be a ma-imum of one change loc5 on an area instance. 8ith versioning/ a change loc5 can be set on an area instance even if there are read loc5s. 8ithout versioning/ a change loc5 can only be set if there is currently no read loc5. The loc5s are set when an internal session is attached to an area instance via an area handle. A loc5 therefore always refers to all shared ob4ects of an area instance. This loc5ing concept supports two application scenarios for shared ob4ects: Usage as a Shared Bu""er: A shared buffer contains a large amount of data that is changed rarely (once a wee5 up to once a day$. In general/ the data of a shared buffer is provided once by a single program and many users read&access the shared buffer simultaneously. A typical application of shared buffer is the storage of a catalog or other stable lists. Usage as an E:clusi$e Bu""er: An e-clusive buffer contains data that is write& or read&accessed by only one user across transaction boundaries. The data can be created by the same user or another user. A typical application of an e-clusive buffer is the storage of a shopping cart that is first populated by the customer and later read by the salesperson.

,!!

Wor+ing (ith Share! -b.ects


The shared ob4ects memory is accessed via the methods and attributes of the area handle that are partly inherited from the super classes CL_SHM_AREA and CL_ABAP_MEMORY_AREA and partly generated when an area is created. To wor5 with area instances/ the current internal session must be attached to them via an area handle. This is achieved using the following static methods of the area class: ATTACH_FOR_READ: 3reates a new area handle to the current area instance version of an e-isting area instance and sets a read loc5. 7ntil the attachment is removed/ it is possible o read&access the attached are instance version in the program. ATTACH_FOR_WRITE: 3reates a new area instance version/ attaches the area handle to it/ and sets a write loc5. 7ntil the attachment is removed/ it is possible to change access the new area instance version in the program. 8ith versioning/ a new empty area instance version is created. 8ithout versioning/ the new area instance version replaces a potential earlier area instance version. ATTACH_FOR_UPDATE: Attaches an area handle to an e-isting area instance and sets an update loc5. 7ntil the attachment is dissolved/ it is possible to change& access the attached area instance version in the program. 8ith versioning/ a new area instance version is created as a copy of the previous versions. 8ithout versioning/ the area handle is attached to the current area instance version.

In the case of success/ all methods return a reference to an area handle that holds one of the three possible loc5s on the attached area instance version. If method is not successful/ because of no area instances or e-isting loc5 denies access/ an e-ception is thrown that is defined as a subclass of CX_SHM_ATTACH_ERROR. To dissolved the connection/ the DETACH instance method is used to detached the area handle attached to an area instance version via a read loc5 while the DETACH_COMMIT or DETACH_ROLLBACK instance methods can be used to detach the area handle attached to an area instance version via a change loc5. 8hen disconnecting/ the area instance should be completed/ that is/ no reference may point from the internal session to a shared ob4ect and vice versa. Shared ob4ects can be created from shared memory&enabled classes as follows: CREATE OBJECT "23_' ) AREA HANDLE 1' 1_%17(! K

Aollowing the addition AREA HANDLE/ we must specify a reference variable of the static type of an area class that points to an area handle/ which is attached to an area instance version via a change loc5. The addition AREA HANDLE also e-ists for the CREATE DATA statement for creating anonymous data ob4ects. 0##

If a change loc5 is detached using DETACH_COMMIT/ an instance of the area root class must be set as the root ob4ect of the area instance version. Aor this purpose/ the SET_ROOT instance method of the area handle must be called while the change loc5 is set. The root ob4ect is the only shared ob4ect that can be addressed directly after attaching an area handle to an area instance version. It is recommended that we encapsulate the entire access to the shared memory in specific classes and let an application program wor5 only with these classes. Ideally/ two classes manage the accessing of shared ob4ects: A loader creates and changes area instances. A bro5er ta5es care of the read access to area instances and can also contain the necessary authori'ation chec5s (discussed in later chapters$.

In the following program/ we merged loader and bro5er into a single class.

0#

9e-t implement the static constructor and methods as shown below:

In an internal session/ there can only be one instance of class that is created in the static constructor (Singleton$. The B $_)!?B%$_!?A$ method serves as a bro5er. It sets a read loc5 on an area instance. Because there can be only one read loc5 on an area 0#,

instance within an internal session/ it is always first Bueried whether there already is an area handle. In case of a failure/ the 9' 1$ _)!?B%$_!?A$ method is called that acts as a loader. It tries to set a write loc5 and to build an area instance with a root ob4ect. Potential e-ceptions are propagated to the calling method. 8ithout e-plicitly removing the change loc5/ there would be a program crash at the end of the current internal session at the latest. If the area built has been successful/ B $_)?B%$_!?A$ tries to set another read loc5. If no area instance could be built/ B $_)!?B%$_!?A$ creates an ob4ect of the J_9!_)!?B%$_!?A$ class in the current internal session and populates the internal table )!?B%$_!?A$. 2astly/ the return value of the method is assigned a data reference to the flight list/ either in the root ob4ect of the shared ob4ect or in the local ob4ect. 9ote that the write loc5 in 9' 1$ _)!?B%$_!?A$ is e-plicitly closed/ while a read loc5 in B $_)!?B%$_!?A$ remains until the end of the internal session. In areas without versioning/ the latter is possible only if no change access are e-pected after an area has been built. The code in listing below shows an application program that wor5s with the data from the share ob4ect in the J_9!_)!?B%$A area.
REPORT J_A%1' (_"23A.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. PRIVATE SECTION. CLASS-METHODS (?A5!14 IMPORTING :1!D O?$12! P TYPE ANY TABLE. ENDCLASS. \!9!_ >1@5! DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* )!?A$_%17(! ' TYPE REF TO J_9!_)!?B%$_!?A$_%17(! ', )!?A$ TYPE REF TO A5)!?_$12. )!?A$_%17(! ' + J_9!_)!?B%$_!?A$_%17(! '+L)!?B%$_!?A$_%17(! '. TRY. )!?A$ + )!?A$_%17(! '-LB $_)!?B%$_!?A$O P. CATCH J9>_7"_)!?B%$A. MESSAGE UN" )!?B%$ !?A$ 1:1?!12! U TYPE UIU DISPLAY LIKE UEU. RETURN. ENDTRY. !9!_ >1@5! +L(?A5!14O )!?A$-LM P. ENDMETHOD. \@1?7 METHOD (?A5!14. \9!_A1!:_$12! ?A DA ( )"' A?@5! , $&"-(?@ 7A?"71! $12! DATA 1!: TYPE REF TO 9!_A1!:_$12! . TRY. 9!_A1!:_$12! +L)19$"'4O IMPORTING

0#0

'_A1!:_$12! + 1!: CHANGING $_$12! + ?$12! P. 1!:-L(?A5!14O P. CATCH 9>_A1!:_@AB. MESSAGE UALV (?A5!14 7"$ 5"AA?2! U TYPE UIU DISPLAY LIKE UEU. ENDTRY. ENDMETHOD. \(?A5!14 ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

The ob4ect of J_9!_)!?B%$_!?A$_%17(! ' is created/ and then a reference to the flight list is read. If the flight list was accessed successfully/ it is output in the (?A5!14 method using the A2H (SAP 2ist Hiewer$. Aollowing is the output of above application program.

Share! -b.ects Management


Profile parameters specify how large the areas of the shared memory can become for different reBuests li5e programs/ program data/ implicit buffers and the shared ob4ects memory. Shared memory is a valuable resource. In SAP <emory <anagement (T3ode ST#,$/ the current memory consumption can be viewed. In contrast to other reBuests to shared memory/ the reBuest for shared ob4ects memory is e-plicit. Therefore/ a programmer must ensure that all unused memory is released. There is a specific monitor for the shared ob4ects memory. It can be called via T3ode SC<< or

0#1

from SC<A. The monitor shows the properties of current area instances and also enables change actions. Some of the functions of the shared ob4ects monitor include: ;isplay all area instances/ their versions and the current loc5s. ;isplay the contents of area instance versions. ;isplay the memory consumption. 3hange the state of area instance versions (from active to obsolete$. ;elete the area instances.

If our previous program is run thrice in parallel within five minutes the display of the shared ob4ects monitor loo5s as shown in figure below:

The second area 9!_?9)_A%@_1' 1 is used by the ABAP runtime environment.

0#D

%Aception 8an!ling
=-ceptions are situations that occur while an ABAP program is being e-ecuted. =-ception situations can have different causes. 3oding may actually be implemented incorrectly. Another cause of e-ception situation is the interaction between a program and e-ternal resources/ such as user entries/ the file system or the memory. =-ception situations can be detected by either the program or the runtime environment. 8hen the ABAP program or the runtime environment detects an e-ception situation/ it triggers an e-ception. There are two main types of e-ceptions: those that can be handled (treatable$ and those that cannot be handled (untreatable$. &reatable !'ceptions+ =-ceptions that can be handled and where the program can continue e-ecuting after the ABAP program has handled the e-ception/ without the system ending up in a critical state. If such an e-ception is not handled/ a runtime error occurs. Treatable e-ceptions are predefined in the system or can be user defined. 1ntreatable !'ceptions+ =-ceptions that cannot be handled. These are critical error situations in the runtime environment. Candling is not possible and they always cause a runtime error.

After a program has terminated with a runtime error/ the system outputs a short dump that contains the name of the runtime error/ the related e-ception class/ contents of data ob4ects/ active calls and son on/ and provides the option of navigating to the ABAP ;ebugger. In the standard setup/ short dumps are stored in the system for 1 days and managed using transaction ST,,. In ABAP 6b4ects we distinguish between class&based e-ceptions (since *elease G. #$ and classic e-ception handling.

Class Base! %Aception 8an!ling


3lass&based e-ception handling is based on e-ception classes. =-ception classes can be user defined or a series of predefined e-ception classes is also available. In an e-ception situation/ an e-ception is represented by an e-ception ob4ect/ in other words/ by an instance of an e-ception class. System defined e-ceptions begin with prefi- CX_SY_/ such as CX_SY_NERODIVIDE. All e-ception classes must begin with the prefi- CX_. They are usually defined globally with the 3lass Builder of the ABAP 8or5bench. 2ocal e-ception classes can/ however/ also be defined. =very e-ception class is derived directly or indirectly from the CX_ROOT superclass/ there are three other abstract e-ception classes for structuring possible e-ceptions. Aigure below shows all four classes and their relationships in the inheritance tree.

0#G

The 5ey characteristics of the four classes are as follows: CX_ROOT* This is the super class from which every e-ception class is directly or indirectly derived. CX_STATIC_CHECK* =-ceptions from this category must be handled within procedures or declared as part of the interface. This is chec5ed by both the compiler and the runtime environment. CX_DYNAMIC_CHECK* Cere too/ e-ceptions from this category must be handled within procedures or declared as part of the interface. This is/ however/ not chec5ed statically by the synta- chec5/ but is chec5ed dynamically at the moment in which an e-ception of this type is propagated from the procedure. CX_NO_CHECK* 9either compiler nor the runtime environment chec5s whether an e-ception that leaves the conte-t of a procedure has also been declared in the interface.

Catching or 8an!ling o %Aceptions


If the e-ception occurs/ the program flow is interrupted/ an e-ception ob4ect is generated and a handler is searched for this e-ception. As a rule/ procedures call other procedures/ creating a corresponding call hierarchy. If an e-ception is not handled in a procedure/ the system attempts to propagate it to the caller of the procedure. If no handler is found in the entire call hierarchy/ the program terminates with a runtime error and a short dump is generated. But how e-ceptions actually caught and what is a handler. A handler is part of the TRY-ENDTRY control structure for catching e-ceptions. The synta- is as follows: TRY. 6$'4_2!"9W8 6CATCH 9>_9!1AA- 9>_9!1AA. ... 6INTO "23_' )8. 691$9%_2!"9W8 ............ 6CATCH 9>_9!1AA/ 9>_9!1AA0 ... 6INTO "23_' )8. 691$9%_2!"9W8 ............ 0#"

6CLEANUP 6INTO "23_' )8. 69! 17D5_2!"9W8 ENDTRY. The coding in the TRY bloc5 ($'4_2!"9W$ defines a protected area whose e-ceptions can be handled in the subseBuent CATCH bloc5s. If no e-ception occurs in the TRY bloc5 and its end reached/ processing continues after ENDTRY. If e-ception occurs in the TRY bloc5/ the system loo5s for an e-ception handler in the same or in an outer TRYENDTRY control structures. The actual e-ception handlers consist of one or more optional CATCH bloc5s (91$9%_2!"9W$. These contain the program logic that is e-ecuted if the related e-ception occurs in the TRY bloc5 of the same TRY-ENDTRY control structure. A CATCH bloc5 handles the e-ceptions from e-ception classes 9>_9!1AA- 9>_9!1AA. ... along with the e-ceptions from their respective subclasses. If the INTO addition is specified/ a reference to the e-ception ob4ect is stored in "23_' )/ where "23_' ) must be an ob4ect reference variable whose static type must be compatible with specified e-ception ob4ect. 8hen the end of a CATCH bloc5 is reached/ processing continues after ENDTRY. The more specific e-ception classes must always be listed before more general e-ception classes. 3onsider the e-ample below for catching and handling e-ceptions.
REPORT J_ >9 5_%17(!?7B.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7 IMPORTING ?"5 '17( TYPE ?. ENDCLASS. \!9!_ >1@5! DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* :1' TYPE ?, ''"' TYPE REF TO 9>_'""$, $>$ TYPE A$'?7B. TRY. :1' + - S ?"5 '17(. :1' + SQRTO ?"5 '17( P. :1' + ?"5 '17( MM ?"5 '17(. CATCH 9>_A4_J '"(?:?( INTO ''"'. $>$ + ''"'-LB $_!"7B$ >$O P. MESSAGE $>$ TYPE UIU DISPLAY LIKE CATCH 9>_A4_1'B_"D$_")_("@1?7 INTO $>$ + ''"'-LB $_!"7B$ >$O P. MESSAGE $>$ TYPE UIU DISPLAY LIKE CATCH 9>_'""$ INTO ''"'. $>$ + ''"'-LB $_!"7B$ >$O P. MESSAGE $>$ TYPE UIU DISPLAY LIKE ENDTRY.

UEU. ''"'. UEU. UEU.

0#.

ENDMETHOD. ENDCLASS.

\@1?7 \!9!_ >1@5!

IMPLEMENTATION

START-OF-SELECTION. !9!_ >1@5! +L@1?7O ?"5 '17( + C P. !9!_ >1@5! +L@1?7O ?"5 '17( + -- P. !9!_ >1@5! +L@1?7O ?"5 '17( + -CCCCC P.

In each of the handlers/ the relevant error message is output/ supplying information about the precise reason for the error. Aollowing is the output of above code listing.

The general procedure for finding the correct handler for an e-ception is shown in the figure below:

0#!

If an e-ception occurs and is caught and handled by a handler/ the normal control flow of the program is changed/ and a procedure is generally left early. This means that a program or certain ob4ects may come into an inconsistent status/ or that resources have not been released yet. The CLEANUP bloc5 in TRY-ENDTRY control structure is used to re&establish a consistent status. The statements in this bloc5 are e-ecuted if an e-ception occurs in a TRY bloc5 that is not caught by handler in the same TRY-ENDTRY control structure/ but in a surrounding TRY-ENDTRY control structure. If the INTO addition is specified/ a reference to the e-ception ob4ect is stored in "23_' )/ where "23_' ) must be an ob4ect reference variable of the CX_ROOT type. After the CLEANUP bloc5 has been e-ecuted/ the CLEANUP bloc5s for the surrounding TRY control structures are e-ecuted until the corresponding handler code has been e-ecuted. It must be noted that statements li5e RETURN or LEAVE TO/ which would cause the CLEANUP bloc5 to be left early/ result in runtime error. Also/ e-ceptions that occur within CLEANUP bloc5 must also be caught and handled there. Aigure below shows an e-ample of the control flow process when the CLEANUP bloc5 is e-ecuted.

0 #

'aising %Aceptions
=-ceptions can be raised in two ways: System&driven (by runtime environment$ or Program&driven (by the ABAP program$. The arithmetic statement :1' + -SC/ for e-ample/ causes an e-ception of the CX_SY_NERODIVDE class to be raised by the runtime environment. If the e-ception is not caught a runtime error occurs. =-ceptions can be raised in a program&driven manner using the RAISE EXCEPTION statement. RAISE EXCEPTION <<TYPE 9>_9!1AA 6EXPORTING 5- + 1- 5. + 1. ...8=;"23_' )=. If the addition TYPE is specified/ an e-ception of the e-ception class 9>_9!1AA is raised and & if necessary & an e-ception ob4ect is created. After TYPE/ every e-ception class 9>_9!1AA visible at this point can be specified. 8ith the addition EXPORTING/ you can assign appropriate actual parameters to the input parameters of the instance constructor using the same synta- as with CREATE OBJECT. Aor reasons of efficiency/ an e-ception ob4ect is only actually generated if the INTO addition of the CATCH statement is used for e-ception handling. If "23_' ) is specified/ the e-ception ob4ect must already e-ist and the "23_' ) reference variable must point to it. This may be the case if the e-ception has already been caught once but if the handler wants to raise it again (because it cannot be handled 0

completely/ for e-ample$ or if the e-ception ob4ect was generated previously by means of CREATE OBJECT. In the following e-ample/ the predefined e-ception 9>_A4_(471@?9_"AQ!_A @17$?9A is raised/ for which an e-ception te-t and its placeholder ]T6O=9] is filled by passing a value.
REPORT J_'1?A _ >9 5$?"7A.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. PRIVATE SECTION. CLASS-DATA* >5_' ) TYPE REF TO 9>_A4_(471@?9_"AQ!_A @17$?9A, $>$ TYPE A$'?7B. ENDCLASS. \!9!_ >1@5! DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. TRY. \9>_A4_(471@?9_"AQ!_A @17$?9A ' 5' A 7$ $% O5 7SQL >9 5$?"7A \$ >$?(, K 4 )"' A99 AA $" M AA1B T > \D7W7"&7_$12! _71@ , A$"' :1!D )"' A$$'?2D$ $ >$?( RAISE EXCEPTION TYPE 9>_A4_(471@?9_"AQ!_A @17$?9A EXPORTING $ >$?( + 9>_A4_(471@?9_"AQ!_A @17$? 9A+LD7W7"&7_$12! _71@ $"W 7 + U$2!_A$D( 7$U. CATCH 9>_A4_(471@?9_"AQ!_A @17$?9A INTO >5_' ). $>$ + >5_' )-LB $_$ >$O P. MESSAGE $>$ TYPE UIU DISPLAY LIKE UEU. ENDTRY. ENDMETHOD. \@1?7 ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of above code listing.

0 ,

Declaring %Aceptions in Proce!ure Inter aces


As we 5now that system attempts to propagate an e-ception/ which is not handled in a procedure/ to the caller of the procedure. In the parameter interface of a procedure/ the e-ceptions that can be propagated from the procedure must be declared. This tells the caller which e-ceptions can be e-pected from the procedure. To declare an e-ception in the interface of a procedure/ the RASING addition is used/ as the following simplified synta- for method declaration shows: METHODS @ $%_71@ ... RAISING >5>5. ...

In the 3lass Builder or Aunction Builder/ the declaration is made by listing the e-ception classes in the E:ceptions tab. The E:ception 9lass chec5bo- must be selected.

If an e-ception class is declared in an interface/ this declaration also applies to all of its subclasses. If an e-ception is not declared/ it can not leave a procedure. This raises an e-ception from the predefined class CX_SY_NO_HANDLER. The e-ample in listing below shows the effects of an e-ception declaration in an interface.
REPORT J_ >9 5_5'"9_( 9!. CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. PRIVATE SECTION. CLASS-METHODS 91!9D!1$ IMPORTING ?"5 '17( TYPE ? RAISING 9>_A4_J '"(?:?( . ENDCLASS. \!9!_ >1@5! DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION.

0 0

METHOD 91!9D!1$ . DATA :1' TYPE ?. :1' + - S ?"5 '17(. :1' + SQRTO ?"5 '17( P. ENDMETHOD. \91!9D!1$ METHOD @1?7. DATA* ''_' ) TYPE REF TO 9>_'""$, $>$ TYPE A$'?7B. TRY. 91!9D!1$ O ?"5 '17( + C P. CATCH 9>_A4_J '"(?:?( INTO ''_' ). $>$ + ''_' )-LB $_!"7B$ >$O P. CONCATENATE UCX_SY_NERODIVDE* U $>$ INTO $>$ RESPECTING BLANKS. MESSAGE $>$ TYPE UIU DISPLAY LIKE UEU. ENDTRY. 91!9D!1$ O ?"5 '17( + -- P. CATCH 9>_A4_1'B_"D$_")_("@1?7 INTO ''_' ). $>$ + ''_' )-LB $_!"7B$ >$O P. CONCATENATE UCX_SY_ARG_OUT_OF_DOMAIN* U $>$ INTO $>$ RESPECTING BLANKS. MESSAGE $>$ TYPE UIU DISPLAY LIKE UEU. CATCH 9>_A4_7"_%17(! ' INTO ''_' ). $>$ + ''_' )-LB $_!"7B$ >$O P. CONCATENATE UCX_SY_NO_HANDLER* U $>$ INTO $>$ RESPECTING BLANKS. MESSAGE $>$ TYPE UIU DISPLAY LIKE UEU. ENDTRY. ENDMETHOD. \@1?7 ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P. TRY.

8ithin @1?7 method/ the 91!9D!1$ method is called twice with different parameters. In the first case/ the 9>_A4_J '"(?:?( e-ception is raised by transferring #. This e-ception is declared in the interface of the 91!9D!1$ method. Because the e-ception is not handled locally in the 91!9D!1$ method/ it is propagated to the caller/ in other words to the @1?7 method. The second time 91!9D!1$ method is called/ the value & is transferred. This generates the 9>_A4_1'B_"D$_")_("@1?7 e-ception when attempting to determine the sBuare root. This e-ception is not declared in the interfaceK it is therefore not propagated and cannot be identified by the e-ception handler in the @1?7 method. The 9>_A4_7"_%17(! ' e-ception handler prevents the interface violation from causing a runtime error/ but which indicates that the procedure was not implemented cleanly. Aollowing is the output of above code listing. 0 1

The e-ample shows the effects of the violation of the procedure interface in which the e-ception was declared. The abstract super classes for all e-ception class CX_STATIC_CHECK/ CX_DYNAMIC_CHECK and CX_NO_CHECK come into play here because the response to the interface violation does not have to be the same for all e-ception classes. These three categories (static/ dynamic and no$ determine whether an e-plicit declaration must be made and how this is chec5ed. Table below shows in which cases which e-ception classes are to be used as a basis.

Creating %Aception Classes


All e-ception classes (global or local$ are sub classes of one of the abstract e-ception classes described in previous section: CX_STATIC_CHECK/ CX_DYNAMIC_CHECK or CX_NO_CHECK. 9o specific class can be directly derived from CX_ROOT. The predefined e-ception classes (CX_SY_...$ inherit from CX_DYNAMIC_CHECK or

0 D

CX_NO_CHECK but not from CX_STATIC_CHECK. All e-ception classes must begin with the prefi- CX_, YCX_ or NCX_. )lobal e-ception classes are defined and managed in the 3lass Builder (S=,1$. If the correct naming convention (prefi- CX_$ and the class type E:ception 9lass is chosen when a new class is created/ the 3lass Builder automatically becomes the =-ception Builder. =-ception classes have the following features: Constructor The constructor must have a predefined structure and a specific interface. 8ith global classes/ the 3lass Builder generates the correct constructor and sets it to an unchangeable status. The constructor has two IMPORTING parameters: TEXTID: This parameter can be used to determine which of your e-ception te-ts the e-ception will use. PREVIOUS: This parameter can be used to assign the PREVIOUS attribute of an e-ception class a previous e-ception.

Metho!s In e-ception classes/ we can define our own methods. The following two predefined methods are inherited from the root class CX_ROOT: GET_TEXT and GET_LONGTEXT: These methods return the e-ception te-t or the long te-t of the e-ception te-t (controlled by the TEXTID attribute$ as a character string of the string type. GET_SOURCE_POSITION: *eturns the program name/ the name of a possible include program/ and the line number of the statement that raised the e-ception.

Attributes The following attributes are inherited from CX_ROOT: TEXTID* 7sed to specify the e-ception of a class more precisely by using several e-ception te-ts. The attribuet is genrally set by the constructor/ and influences the result of the GET_TEXT method. PREVIOUS: 3an contain a reference to a previous e-ception. The attribute is particularly useful/ because it enables e-ceptions to be chained. This means that we can trac5 the path of an e-ception right bac5 to its origin.

0 G

=ach e-ception is assigned an e-planatory te-t. The e-ception te-t describes an error situation from a technical view. =-ception te-ts can contain parameters (placeholders$ that enable an error situation to be described more precisely. 8e can convert attributes into parameters of e-ception te-ts by displaying their name using the character :]: in the e-ception te-t. If the e-ception occurs/ the parameters are replaced by the content of the attributes. There are two ways of defining e-ception te-ts: %Aception $eAts in -nline $eAt 'epositor": The 6nline Te-t *epository (6T*$ is a central repository for te-t and provides services for the processing and administration. The te-t stored in the 6T* can contain a ma-imum of ,DD characters. %Aception $eAts in $able $BJJ: If the e-ception class implements the interface ?)_$-CC_@ AA1B / the short te-ts for messages in the database table T ## are used as e-ception te-ts. The te-t is identified by the message class and the message number. 9ote that here the message class is not a class in the sense of ob4ect orientation rather it is an identifier that groups messages in an application area. Attributes from the e-ception class can be assigned to placeholders ] to ]1 or ] in the message. These te-ts can contain a ma-imum of ", characters and can be sent to the program user during e-ception handling with the MESSAGE "23_' ) statement.

In the first e-ample we define our own e-ception class/ to which we assigned two alternative 6T* te-ts.

0 "

9e-t we created another e-ception I; with name NCX_EXCEPTION_EXAMPLEC.. In addition/ we have assigned a relevant te-t to the two e-ception I;s congaing a place holder _TOKEN_ to parameteri'e the output.

Aor each e-ception te-t/ the 3lass Builder creates a static constant with the same name as the e-ception te-t. This can be passed to the TEXTID parameter of the constructor to determine the e-ception te-t when the e-ception is raised. If the parameter is not passed/ a predefined e-ception te-t is used. Another attribute TOKEN (with same name as the parameter$ of type string must be created.

0 .

The following code consumes the J9>_ >9 5$?"7_ >1@5! .


REPORT J_ >9 5_( 9!C-.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. \!9!_ >1@5!

DEFINITION

CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA* ''_' ) TYPE REF TO J9>_ >9 5$?"7_ >1@5! , $>$ TYPE A$'?7B. TRY. RAISE EXCEPTION TYPE J9>_ >9 5$?"7_ >1@5! EXPORTING $ >$?( + J9>_ >9 5$?"7_ >1@5! +LJ9> _ >9 5$?"7_ >1@5! $"W 7 + U\-CC\U. CATCH J9>_ >9 5$?"7_ >1@5! INTO ''_' ). $>$ + ''_' )-LB $_$ >$O P. MESSAGE $>$ TYPE UIU DISPLAY LIKE UEU. ENDTRY. TRY. RAISE EXCEPTION TYPE J9>_ >9 5$?"7_ >1@5! EXPORTING $ >$?( + J9>_ >9 5$?"7_ >1@5! +LJ9> _ >9 5$?"7_ >1@5! C. $"W 7 + U\.CC\U. CATCH J9>_ >9 5$?"7_ >1@5! INTO ''_' ). $>$ + ''_' )-LB $_$ >$O P. MESSAGE $>$ TYPE UIU DISPLAY LIKE UEU. ENDTRY. ENDMETHOD. \@1?7 ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

After e-ecution the following output is produced.

0 !

The ne-t e-ample demonstrates the usage of e-ception te-ts from database table T ##. Airst to create the message class/ open the message transaction tool (S=! $ and create the J >95_@AB_9!A as shown below:

3reate a new class NCX_EXCEPTION_EXAMPLE_T-CC and select the /ith Aessage 9lass chec5bo-. In this case the ?)_$-CC_@ AA1B is included in the class definition automatically and prepare the 3lass Builder to use messages as e-ception te-ts.

0,#

In the ttributes tab/ the two attributes TOKEN- and TOKEN. are defined as placeholders.

9e-t to define message te-ts/ go to *e:ts tab. Place the cursor in the line with the corresponding e-ception I;/ and clic5 on the Aessage *e:t button the system displays an input template where we entered the message class already created.

0,

The following e-ample utili'es the above e-ception class.


REPORT J_ >9 5_( 9!C..

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. \!9!_ >1@5!

DEFINITION

CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA ''_' ) TYPE REF TO J9>_ >9 5$?"7_ >1@5! _$-CC. TRY. RAISE EXCEPTION TYPE J9>_ >9 5$?"7_ >1@5! _$-CC EXPORTING $"W 7- + U\I CC\U $"W 7. + U\F ?: HD7( '(\U. CATCH J9>_ >9 5$?"7_ >1@5! _$-CC INTO ''_' ). MESSAGE ''_' ) TYPE UIU DISPLAY LIKE UEU. ENDTRY. ENDMETHOD. \@1?7 ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing is the output of above code listing.

0,,

Classic %Aception 8an!ling


Aor reasons of downward compatibility/ these older concepts can still be used to handle e-ceptions in ABAP. Cowever/ these concepts should no longer be used in new programs. The classic e-ceptions handling has the following types:

Catchable 'untime %rrors


If runtime errors are caused by situations that can be handled in a meaningful way in the program/ they are catchable. 3atchable runtime errors are grouped into e-ception groups that allow similar errors to be handled together. 8e can handle catchable runtime errors with the following statement: CATCH SYSTEM-EXCEPTIONS KKKKKKK. ENDCATCH. >9- + '9- K >97 + '97.

The >9 e-pressions describe either a catchable runtime error or the name of an e-ception group. The '9 e-pressions are numeric literals. If one of the specified runtime errors occurs in the statement bloc5 between CATCH and ENDCATCH the program does not terminate. Instead/ after ENDCATCH/ the numeric value '9 assigned to the runtime error/ which is available as a return value in the A4-AD2'9 system field. The CATCH and ENDCATCH statements define control structures that can be nested as deeply as we reBuire. It must be noted that CATCH SYSTEM-EXCEPTIONS can only be used to catch runtime errors form the current call level and not from called procedures. The following e-ample demonstrates how to use the catchable runtime errors.
REPORT J_9!1AA?9_91$9%12! _ ''"'A.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. \!9!_ >1@5!

DEFINITION

0,0

CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA :1' TYPE ?. CATCH SYSTEM-EXCEPTIONS 1'?$%@ $?9_ ''"'A + 0. :1' + - S C. ENDCATCH. IF A4-AD2'9 + 0. MESSAGE UD?:?A?"7 24 N '" ''"'U TYPE UIU DISPLAY LIKE UEU. ENDIF. ENDMETHOD. \@1?7 ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

The division by # causes the catchable runtime error COMPUTE_INT_NERODIVIDE/ which is contained in the e-ception group ARITHMETIC_ERRORS. In this case/ A4AD2'9 is set to 1. Aollowing is the output of above code listing.

Sel -De ine! 4Non-Class-Base!5 %Aceptions


Self&defined (non&class&based$ e-ceptions can be defined in the interfaces of function modules and methods. Aor local class methods/ the definition is carried out by assigning a name for the e-ception after the EXCEPTIONS addition of the 6CLASS-8METHODS statement. Aor methods of global classes or function modules/ the definition is carried out by assigning a name of the e-ception in the 3lass Builder or Aunction Builder in the E:ceptions tab where the E:ception 9lasses chec5bo- is not selected here. The following statement is used to raise the self&defined (non&class&based$ e-ceptions. RAISE >9.

*aising e-ception terminates the procedure and the A4-AD2'9 system field is set. The RAISE EXCEPTION statement for raising class&based e-ceptions must not be used in

0,1

the same procedure and no class&based e-ceptions can be declared in the interface with RAISING. Self&defined (non&class&based$ e-ceptions are rendered treatable using the EXCREPTIONS addition of the CALL METHOD and CALL FUNCTION statements. This is achieved by assigning numeric values to e-ceptions/ which are moved to the A4AD2'9 system field when the e-ception occursK however/ the actual handling is carried out after the call by evaluating A4-AD2'9. If an e-ception that is raised in the procedure has not been assigned a numeric value/ a runtime error occurs. 2isting below demonstrate the self&defined (non&class&based$ e-ceptions.
REPORT J_7"7_9!A_21A (_ >95.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS* @1?7, (?:?( IMPORTING ?7D@ '1$"' TYPE ? ?( 7"@?71$"' TYPE ? EXPORTING ' AD!$ TYPE ? EXCEPTIONS (?:?( _J '". ENDCLASS. \!9!_ >1@5! DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD (?:?( . IF ?( 7"@?71$"' + C. \T45 A ' 5' A 7$A $% $ '@?71$?"7 @ AA1B A \T% @ AA1B $ >$ ?A 5!19 ( ?7 $% A4A$ @ )? !( MSGV\RAISING 1((?$?"7,$% A$1$ @ 7$ MESSAGE '1?A A 1 \7"7-9!1AA-21A ( >9 5$?"7 MESSAGE UD?:?A?"7 24 CU TYPE UAU RAISING (?:?( _J '". ELSE. ' AD!$ + ?7D@ '1$"' S ?( 7"@?71$"'. ENDIF. ENDMETHOD. \(?:?( METHOD @1?7. DATA ' AD!$ TYPE ?. (?:?( O EXPORTING ?7D@ '1$"' + ?( 7"@?71$"' + C IMPORTING ' AD!$ + ' AD!$ EXCEPTIONS (?:?( _J '" + 0 P. IF A4-AD2'9 + 0. MESSAGE A4-@AB:- TYPE UIU DISPLAY LIKE UEU. ENDIF. (?:?( O EXPORTING ?7D@ '1$"' + -

0,D

?( 7"@?71$"' + C IMPORTING ' AD!$ + ' AD!$ P. ENDMETHOD. \(?:?( ENDCLASS. \!9!_ >1@5! START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

IMPLEMENTATION

8e call the divide method twice with the denominator # so that the e-ception is raised each time. The e-ception is handled during the first call. In this case/ the system behaves as it does when the RAISE statement is used. 8e can replace the RAISE statement with MESSAGE K RAISING. The second time the method is called/ the e-ception is not handled. In this case/ the message is processed according to the specified message type (%A($/ and the program terminates. Aollowing screen shot shows the output of the above code listing.

Combining Class-Base! an! Classic %Aceptions


As we 5now from previous sections/ classic e-ceptions that can be defined by the EXCEPTIONS clause in methods and function modules are completely different concepts from those that can be defined by the RAISING clause in class&based e-ceptions. The two concepts can not be mi-ed. Therefore/ we must distinguish strictly between the two concepts. As developers/ we must opt for class&based e-ceptions/ but you may call procedure which still uses the classic e-ception concepts. Aor e-ample/ when we call a function module that uses classic e-ceptions within a method where we are using class&based e-ceptions. In this case/ the classic e-ceptions must be caught/ and a new/ corresponding class&based e-ception must be raised as shown in the following e-ample. 0,G

REPORT

J_9!1AA?9_9!A_21A (_ >5.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS* @1?7, (?:?( IMPORTING ?7D@ '1$"' TYPE ? ?( 7"@?71$"' TYPE ? EXPORTING ' AD!$ TYPE ? EXCEPTIONS (?:?( _J '", 5 ')"'@_91! RAISING 9>_A4_J '"(?:?( . ENDCLASS. \!9!_ >1@5! DEFINITION CLASS !9!_ >1@5! IMPLEMENTATION. METHOD (?:?( . IF ?( 7"@?71$"' + C. RAISE (?:?( _J '". ELSE. ' AD!$ + ?7D@ '1$"' S ?( 7"@?71$"'. ENDIF. ENDMETHOD. \(?:?( METHOD 5 ')"'@_91!. DATA ' AD!$ TYPE ?. (?:?( O EXPORTING ?7D@ '1$"' + ?( 7"@?71$"' + C IMPORTING ' AD!$ + ' AD!$ EXCEPTIONS (?:?( _J '" + 0 P. IF A4-AD2'9 + 0. RAISE EXCEPTION TYPE 9>_A4_J '"(?:?( . ELSE. WRITE* S ' AD!$ . ENDIF. ENDMETHOD. \(?:?( METHOD @1?7. DATA ''_' ) TYPE REF TO 9>_A4_J '"(?:?( . TRY. 5 ')"'@_91!O P. CATCH 9>_A4_J '"(?:?( INTO ''_' ). MESSAGE ''_' ) TYPE UIU DISPLAY LIKE UEU. ENDTRY. ENDMETHOD. \(?:?( ENDCLASS. \!9!_ >1@5! IMPLEMENTATION START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

Aollowing output is produced after the e-ecution of above report.

0,"

Assertions
An assertion is the confirmation that a specific status of the data ob4ects in a program actually e-ists. Assertions are typically used to ensure or chec5 a consistent status at specific points in the program flow. Therefore/ assertion generally e-presses an assumption that must apply in order for the program to continue to be e-ecuted. 7sing assertions can help to find more errors in the program and to improve the Buality of a program. Assertions can be activated or deactivated so that chec5s do not affect the speed of any productive programs. The synta- for the ASSERT statement is: ASSERT 6<ID B'"D5= CONDITION8 !"B_ >5. An assertion that is always active is e-pressed by 4ust the logical e-pression !"B_ >5 after the ASSERT statement. If the result of the chec5 is true/ the program flow continues as normal. If the result is false/ the program terminates with the non&catchable runtime error ASSERTION_FAILED. If the ID B'"D5 addition is specified/ an assertion is defined that can be activated e-ternally by lin5ing it to a so called chec5point group. The chec5 point group is an ABAP repository ob4ect. The behavior of the assertion can be managed e-ternally by changing the chec5point group with 3hec5points that 3an Be Activated (T3ode SAAB$. The following settings are possible: )nactive+ In this case/ the statement does not have any impact on the program flow. "og+ if an incorrect result is delivered/ an entry is written in a special log/ which can also be evaluated in 3hec5points that 3an Be Activated (T3ode SAAB$. The program e-ecution then continues with the statement following ASSERT. Abort+ This option generates the same behavior as an assertion that is always active. An untreatable e-ception is raised/ and the program terminates with the ASSERTION_FAILED runtime error. Break4"og or Break4Abort+ If an incorrect result is delivered/ the program branches to the ABAP ;ebugger.

0,.

=-ceptions focus more on the %robustness( of the program i.e. a program should still be able to run/ even if it is faced with meaningless user entries. Assertions on the other hand/ focus on %correctness( of the program i.e. the focus is on implementing a program so that it corresponds e-actly to its specification. The assertions can be used to implement the software development principle/ %design by contract (;b3$(. Aor that reason ASSERT is used at the start of method to chec5 the pre&condition according to which the method may actually be e-ecuted. At the end of the method/ a post&condition is chec5ed/ which states whether the method has functioned correctly. The e-ample on ne-t page demonstrates assertions.

0,!

To create a chec5point group/ open 3hec5points that 3an Be Activated (T3ode SAAB$. 6n initial screen enter the name for chec5point group in 3hec5point )roup frame and clic5 on the 3reate button.

00#

6n activation tab leave default values and clic5 Save.

00

By default activatable chec5points are always inactive. To activate the assertion/ on the initial screen of 3hec5points that 3an Be Activated (T3ode SAAB$/ clic5 on the Active button. 6n the resulting Activation tab select the Abort from Assertions (Aorground$ sub frame/ and clic5 Save/ as shown below.

9ow this assertion is e-clusively activated for you (by using personal activation setting$. The following code listing uses the above assertion as:
REPORT J_1AA '$?"7.

CLASS !9!_ >1@5! DEFINITION. PUBLIC SECTION. CLASS-METHODS @1?7. ENDCLASS. \!9!_ >1@5! CLASS !9!_ >1@5! IMPLEMENTATION. METHOD @1?7. DATA :1' TYPE ?. ASSERT ID J9%W_5"?7$_B'5 CONDITION :1' IS NOT INITIAL. ENDMETHOD. \@1?7 ENDCLASS. \!9!_ >1@5! START-OF-SELECTION. !9!_ >1@5! +L@1?7O P.

DEFINITION

IMPLEMENTATION

00,

After e-ecution the program will terminate with runtime error ASSERTION_FAILED and a short dump will show the position where the assertion was failed.

000

001

Vous aimerez peut-être aussi