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 (1970s) ABAP stood for “Allgemeiner Berichts-Aufbereitungs Prozessor” (Generic Report Generation Processor). That time ABAP was implemented as a macro assembler under R/2 and exclusively used for creating reports. In mid 1980s, 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 1990s, the SAP R/3 system was born and ABAP become ABAP/4, that ABAP 4GL (4th Generation Programming Language). It now formed the technical and software basis of the entire SAP System. Apart from system core which is written in C, all SAP application modules, R/3 Basis System and the development environment were now created in ABAP/4. At the end of 1990s, ABAP is extended with object oriented programming constructs and from this point on, the language was known as ABAP Objects. In the beginning of 2000s ABAP programs were made Unicode-Compatible in order to support the internationalization of the SAP System. With SAP technology platform under the name “SAP NetWeaver”, ABAP become the programming interface of the SAP NetWeaver Application Server ABAP (AS ABAP).

• • •

1

What is SAP NetWeaver?
SAP NetWeaver is SAP's (Systems Applications and Products in Data Processing) technological platform (Components, Tools and Applications) which provides a runtime and development environment for all SAP applications. SAP NetWeaver is the fully interoperable Web-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 Microsoft's .NET, IBM's WebSphere, and Sun's Java technologies. SAP NetWeaver is based on Structure Oriented Architecture (SOA). SOA define methods for systems development and integration where systems provide functionality as interoperable services. The concept of a service, specifically a Web service -- is a key part of the SOA. A Web Service is defined by the W3C as "a software system designed to support interoperable machine-to-machine interaction over a network". Loose coupling (no service is tightly attached to a single system), Interoperability and Portability define the ground rules for development, maintenance, and usage of the SOA. Enterprise SOA (eSOA) is the term SAP gives to its own SOA tools and technologies. SAP NetWeaver platform comprises of the following components, tools and applications:

2

Components:
• • • • Application Server: Supports platform-independent Web services, business applications, and standards-based development Business Warehouse: Integrate data from across the enterprise and transform it into information to drive sound decision making. Business Process Management: Provides tools to help you model, execute, and monitor business processes based on a single, consistent process model. Process Integration: Delivers SOA-based technology that supports applicationto-application (A2A) and business-to-business (B2B) integration, and to accelerate composite application development. Master Data Management: Ensures cross-system data consistency and a single version of master data for supplier, product, customer, or user-defined data objects in heterogeneous environments. SAP NetWeaver Mobile: Provides a mobile runtime environment based on open and flexible technology standards and a powerful development environment for building integrated mobile solutions with native or browser-based user interfaces. SAP NetWeaver Portal: Unifies critical information and applications to give users role-based views that span the enterprise, enabling you to take full advantage of your information resources. SAP Auto-ID Infrastructure: Gives you all the capabilities you need to integrate all automated sensing devices – including RFID (Radio Frequency Identification) technology electronically captures, stores, and transmits data readers and printers, Bluetooth devices, embedded systems, and bar-code devices. Identity Management: Helps companies manage users' access to applications securely and efficiently, while meeting audit and compliance requirements. Information Lifecycle Management: Enables companies to decommission redundant SAP system while preserving full auditing and reporting capabilities for stored data.

• •

Tools:
• Adaptive Computing Controller: Provides a central point of control for assigning computing resources and optimizing their use.

3

Composition Environment: Provides a robust environment for design, deployment, and running of composite applications that comply with a serviceoriented architecture. Developer Studio: Offers a convenient user interface and rich functionality for developing J2EE applications. Visual Composer: Allows composing model-based business applications in a flexible way, without manual coding. SAP Solution Manager: Application management solution facilitates technical support for distributed systems.

• • •

Applications
• Enterprise Search: Helps business users navigate critical business information by enabling seamless, secure access to SAP and non-SAP information and processes. Duet: Enables seamless access to SAP business processes and data via Microsoft Office. Alloy: Simplifies interaction with people, processes, and information by providing intuitive access to SAP software and information via the familiar IBM Lotus Notes. SAP Central Process Scheduling application by Redwoods: Helps companies manage, monitor, and execute business-critical processes from a central location by delivering adaptive, real-time, event-driven job scheduling and processautomation capabilities across distributed and heterogeneous platforms. Enterprise Modeling Applications by IDS Scheer: Deliver Web-based components that support the process life cycle for business process design, analysis, optimization, and implementation.

• •

4

Another way of defining SAP NetWeaver.
SAP NetWeaver is a set of capabilities that are provided by different SAP products constructed to work with each other to make applications work together, build new applications on top of existing applications and lower the Total Cost of Ownership (TCO). TCO is about all the different expenses involved in owning and running an enterprise application.

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

5

People Integration
People Integration means to bring people together and help them work more efficiently. Information Integration means to bring information from different locations and have it make sense in the context what a user do everyday.

Process Integration
Processes Integration means coordinating the flow of work across departments, divisions and between companies.

Application Platform
Application Platform is called the SAP Application Server (SAP AS). SAP AS is foundation for the entire SAP software stack. It is the engine behind the scene of SAP NetWeaver that drives all SAP’s Applications and Tools. It provides a platform for NetWeaver components (Enterprise Portal etc.) and ABAP and Java applications.

Composite Application Framework
Composite Application Framework (SAP CAF) is modeling and development environment for creating composite applications. Composite applications are applications built out of services provided by other applications.

Life Cycle Management
The SAP Lifecycle Management (SAP LM) offers all the functionality needed for integrated product and asset management like Program and project management and Quality management.

6

It provides a platform for NetWeaver components (Enterprise Portal etc). User can access it using user interfaces that are available in the form of 7 .SAP Application Server SAP Application Server (SAP AS) is foundation for the entire SAP software stack. including the remaining components of SAP NetWeaver. Figure below shows a simplified overview of the main AS ABAP components. the SAP Application Server provides two runtime environments: the ABAP runtime environment (AS ABAP) and a Java runtime environment (AS JAVA). database) to the greatest extent possible. These applications should be implemented independent of the hardware environment used (operating system. Application Server ABAP The Application Server ABAP provides the ABAP runtime environment that is a virtual machine for ABAP programs independent of the hardware. AS ABAP can be used by user or by software. SAP systems are used for mapping business processes or business applications. operating system and data base system. Both application servers work on different data (different database schemas) and are linked together by allowing mutual access through the Java Connector (JCo). It is the engine behind the scene of SAP NetWeaver that drives all SAP’s Applications and Tools. For this.

It consists of a runtime environment and a graphical development environment with special Web Dynpro tools that are integrated in the ABAP Workbench. Application program access these HTLML pages through the Internet Connection Framework (ICF). for which two protocols are used: HTTP/HTTPS/SMTP for Internet connections and SAP’s own Remote Function Call (RFC) protocol for calling ABAP functionality through any external clients. HTTPS. testing and maintenance of each. HTML pages prepared in the presentation layer are accessed. MVC is an architectural pattern used in software engineering. SAP GUI is the graphical user interface that runs on a Microsoft Windows. Software components generally access it through the network. The presentation in the SAP GUI is based on the classical dynpro technology.web browser or SAP GUIs installed on desktop PCs. Presentation in a web browser is based on Web Dynpro and Business Server Pages (BSP). The ICF uses standard protocols (HTTP. Business Server Pages Business Server Pages (BSP) can incorporate server-side scripts written directly in ABAP or Java Script. It enables direct access to all elements in the application server (such as 8 . User interfaces for AS ABAP include commercial web browsers and SAP’s SAP GUI. Apple Macintosh or UNIX desktop. WDA) is the SAP standard UI technology for developing Web applications in the ABAP environment. Web Dynpro ABAP Web Dynpro for ABAP (WD4A. Web Dynpro is based on Model View Controller (MVC). The Control Framework (CFW) supports controls (ActiveX and JavaBeans) that are implemented within the SAP GUI. The components of AS ABAP can be divided according to their tasks into three layers of a client-server system: • • • Presentation Layer Application Layer Persistence Layer Presentation Layer The components of the presentation layer are responsible for the presentation of data to users and the receiving of user entries. depending on the version of SAP GUI currently in use. When web browsers are used in application programs. permitting independent development. and SMTP) to operate communications between systems through the Internet. The pattern isolates business logic from input and presentation.

BSP also supports MVC. Application Layer The application layer is the software layer in which application programs are executed. ABAP and ABAP Objects ABAP and ABAP Objects (OO enhancement to ABAP) is the programming interface of AS ABAP for business management applications. database tables. Dynpro Dynamic program (Dynpro) defines a user interface of an ABAP program in a window of the SAP GUI. a dynpro also contains a screen processing logic written in a separate programming language that is called dialog modules in ABAP program. The application layer contains a kernel written primarily in C/C++ that servers as a platform for application programs which is independent from hardware. 9 .). ABAP Objects. but is not a prerequisite. which can be used either as an independent application or as an add-on to other tools such as Object Navigator or Class Builder. The screen of a dynpro can contain a set of predefined screen elements or GUI controls. BSPs represent the predecessor technology of Web Dynpro ABAP.function modules. and so on. The XSLT and ST processors execute XSLT and ST programs. BSP is similar to Java Server Page (JSP) as it is coded in HTML of AS ABAP Internet applications. These programs are edited with Transformation Editor of the ABAP Workbench. operating system and database. In addition to screen. User interfaces of new applications should be designed primarily with Web Dynpro ABAP. Simple Transformation (ST) is an SAP-specific language used to transform ABAP data to XML and vice versa. The kernel provides processors (virtual machines) for the following programming languages: XSLT and ST XSLT (eXtensible Stylesheet Language Transformation) allows XML formats to be converted into any other XML format. The ICF and CFW provide services between the application program and presentation layer. Each dynpro is a component of an ABAP program. ABAP programs are created with the ABAP Editor. even if it is not initially intended to use the system via the Internet. The corresponding ABAP processor accounts for the largest part of the AS ABAP kernel.

Persistence Layer The persistence layer is the software layer in which persistence data is held in a database. The Open SQL interface converts the Open SQL statements into manufacturer specific SQL and passes it onto the DBMS. and A Query Service. MODIFY. Use of JavaScript on AS ABAP has negligible significance. the CL_JAVA_SCRIPT system class provides an interface to the JavaScript Engine. customizing settings and ABAP source codes. Only the statements from Open SQL should be used in application programs. UPDATE. The central database can be accessed by ABAP programs through the database interface of AS ABAP. This means that not only the application types. The statements of Open SQL access the AS ABAP database through the Open SQL interface. These Object Services include: A Persistence Service. This interface makes AS ABAP independent from the database system that is actually used. A Transaction Service. There is no dedicated editor for JavaScript programs in the ABAP Workbench. Variables of the script can be linked to data objects of an ABAP program. Native SQL refers to statements that can be executed in ABAP programs between EXEC SQL and ENDEXEC statements. Each AS ABAP accesses a central database on which its entire dataset is stored. Communication Components Communication components are position somewhat aside from the three layers: Inter Communication Manager 10 . Object Services Object Services provide global services. to applications written in ABAP Objects. Open SQL is a sunset of SQL realized by ABAP statements and includes the Data Manipulation Language (DML) portion. DELETE) data in database tables that are defined in the ABAP Dictionary. unchanged to the DBMS. With Open SQL you can read (SELECT) and change (INSERT. but also all administrative data. The database interface is subdivided into an Open SQL interface and SQL interface. irrespective of the platform.Java Script JavaScript programs are executed by JavaScript processor. which ABAP Objects language elements cannot provide themselves. Native SQL interface passes on the manufacturer-specific SQL statements.

Internet Communication Manager (ICM) is a process in ABAP kernel that allows it to communicate directly with the Internet via HTTP/HTTPS/SMTP. 11 . or between an AS ABAP and external system. Calls are possible between different AS ABAPs. Remote Function Call Interface Remote Function Call (RFC) is an invocation of a function that is located in a different system than the one in which the calling program is running. It also enables and AS ABAP to act both as a client and as a server for Web Services. ABAP program access the ICM through the classes and interfaces of the Internet Communication Framework (ICF). ICM allows connection to web based presentation components such as Web Dynpro ABAP and BSP.

AS ABAP Processes In addition to several work processes whose number and type are determined at the startup of AS ABAP. The context contains the current data for the application program. ICM and a message server. a gateway. The following graphic illustrates the most important processes of application server ABAP. Dispatcher The dispatcher is the link between the work processes and the users logged onto the ABAP application server (that is. Each work process is linked to a memory area containing the context of the application being run. each ABAP application server contains a dispatcher. In the same way.AS ABAP Processes The SAP runtime system consists of a number of parallel processes that work together. There are the following types of work process: 12 . the SAP GUIs of the users). Work Processes Work processes are software components that execute an application. Its task is to receive requests from the SAP GUI and direct them to a free work process. it directs screen output back to the appropriate user. If all the work processes are occupied the requests are stored in the dispatcher queue.

you can also have more than one spool work process per dispatcher. Message Server The message server (MS) handles the communication between the distributed dispatchers within the ABAP stack of an SAP system. or between SAP systems and external application systems. It can also direct HTTP requests from an SAP system to a Web server and send the response back to the SAP system. You can configure more than one background work process for each dispatcher. The ICM receives requests from the Internet and forwards them to the SAP system for processing. Enqueue: Administers the lock table in the shared memory. Background (batch): Execute programs that run without interacting with the user. Only one enqueue work process is needed for each system. There is one per dispatcher. Every SAP system requires at least one spool work process. 13 . Update: Execute update requests. Internet Communication Manager The Internet Communication Manager (ICM) enables SAP systems to communicate directly with the Internet. At least one update work process per SAP system and you can have more than one per dispatcher. The message server is configured only once per SAP system. Memory Pipes are memory-based communication objects that are used to transfer data between the ICM and the work processes.• • • • • Dialog: Fulfill all requests for the execution of dialog steps triggered by an active user. Spool: Pass sequential data flows on to printers. Gateway The gateway (GW) enables communication through RFC interface between SAP systems. The lock table contains the logical database locks of the ABAP stack of the SAP system. thereby enabling scalability of several parallel application servers. Every dispatcher requires at least two dialog work processes. You need at least two background work processes for each SAP system. You can configure a maximum of one ICM process per application server.

the application layer of an AS ABAP is spread across at least one. background.Memory Organization of AS ABAP AS ABAP is the system in which an ABAP programs runs. Each application server provides a range of services of operating the AS ABAP. Therefore. whose operating systems don’t have to be identical. whose number and types are set when the AS ABAP is started. If an AS ABAP has several application servers. Work processes are software components that can execute an application. but usually several. During the ASP ABAP runtime. Figure below shows where an ABAP program runs on an application server and what memory areas it can access here. in application layer there is Message Server (MS) that is responsible for communication between the application servers. There are different types of work processes for different applications: dialog. application servers. they are usually also installed on several machines. 14 . Work process is logged on as a user to the database system for the entire runtime of an AS ABAP. From software point of view. The services of an application server are implemented by work processes. SAP Memory Management is used for memory areas of an application server. spool and update work processes. enqueue. a database logon can’t be passed on from one work process to another.

The ABAP runtime environment uses the shared memory for programs. From an ABAP program a new main session can be open via RFC (CALL FUNCTION STARTING NEW TASK). SAP Memory When a dialog user or an external client (via RFC or ICF) logs on to an AS ABAP. or enter a transaction code behind /o in the input window of standard toolbar.AS Memory Organization The memory areas of an application server that can be accessed in an ABAP program are as follows: • • • • Shared Memory SAP Memory ABAP Memory Roll Area Shared Memory Each application server has its own shared memory. The input fields of dynpros can be linked to SPA/GPA parameters and in order to pre-fill them before a dynpros is called. such as the name of the last programs called. In dialog processing. in which data clusters can be stored. in which all ABAP programs of a user session have joint access to SPA/GPA parameter (Used to fill the input fields of a called transaction with data from the calling program). program data and buffering (from database in data dictionary in a table buffer). a user session can manage up to 16 main sessions. the SAP Memory. known as the ABAP Memory. each of which is linked to separate window. ABAP Memory At least one main session or external mode is opened for each user session. 15 . Each main session is assigned a separate memory area. it is connected to an appropriate application server and opens a user session on this AS. These parameters are only suited to saving short character-type fields. you open a new main session in a new window. ABAP programs can access shared objects and data clusters in the shared memory. Each user session is assigned its own memory area. The data in the ABAP memory is retained during a sequence of program calls within a call sequence. The shared memory is the memory area that is used by all parts of an application server together. If you execute the function Create New Session in the SAP GUI. The corresponding statements are SET PARAMETER and GET PARAMETER.

An internal session will exist for as long as its first program. a maximum of nine internal sessions can be stacked as a call sequence in a main session. is executed. This is the actual memory of an ABAP Program. an internal session can theoretically require up to 4TB of memory. Technically each internal session is divided into a Program Execution Area (PXA) and a Roll Area. in which the data and objects of an ABAP program are stored while it is executed. A memory area called a Roll Area is assigned to the internal session. Only the roll area is individually reserved for an internal session and contains its changeable data. the main program. In main session. On 32-bit platforms. Roll Area With each call via SUBMIT or CALL TRANSACTION or LEAVE TRANSACTION of an ABAP program in main session. references to objects can be copied from one program to procedures of another program. The PXA 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. Only programs of a call sequence have common access to data in the ABAP memory. 16 . Within internal session. an internal session is opened.A call sequence is formed if you can return from called program to the calling program. The additional loaded programs and their data also remain loaded until the end of the internal session. the corresponding ABAP memory is also released. All programs of an internal session have joint access to anonymous data objects and instances of classes created with CREATE. When the first program of a call sequence is terminated. the theoretical maximum limit is 4GB. With program calls. and this is primarily for data transfer during program calls. On 64-bit platform. This is always the case when you call an ABAP program with SUBMIT AND RETURN or CALL TRANSACTION. only the internal session of the program that is just running exists in am active version. All memory content of previous programs is saved on the stack.

The CTS is the central tool for managing changes to repository objects that you make in the ABAP Workbench. The transport layer refers to the transport path a package should take in a system landscape. use it productively. A Practical Introduction Change and Transport System (CTS) The SAP NetWeaver repository is the central place where development components in the ABAP Workbench are stored. A change request can be created in two ways: 17 . These components include all of the: process models. The change request is then used to copy the changes from this client to other clients or systems. Transports of changes by the CTS allow you to develop in one environment.ABAP. You need a transport/change request to get something transported. business objects. The CTS records all changes in transport/change requests. and then. test your development work in a test environment. This makes sure that productive operations are not placed at risk by faulty settings or program errors. The usual landscape has a least three layers: The transport layer by itself does not transport anything. The repository also includes the ABAP Dictionary. This automatic procedure is known as a transport. if the tests are successful. CTS enable you to define transport layer as an attribute of a package. and all data and their relationships. you can release the request. When you have finished your work in ABAP Workbench. or have reached a certain stage. data models. business object models.

follow the path Start -> Programs -> SAP Netweaver 7. Log on as a BCUSER.1.01 ABAP Trial Version -> NSP -> Start Application Server. 2. Creating a Request in the Transport Organizer: 1.Select Create (F6) to create new transport request. When you create or modify objects in the ABAP Workbench. 18 . 2. Through Transport Organizer (SE09). a window appears asking you to assign the object to an existing change request (Own requests) or to create a new change request (Create request). See Package Creation Topic. To start application server.

4. Create Request dialog will appear. Select Workbench request and click continue. 5. enter short description of the change request. And Click Save. 19 . Enter SE09 transaction code in the text field of standard toolbar to open the Transport Organizer. Select the Create (F6) function from the toolbar of Transport Organizer to create new transport request.3. 6.

7. 20 . This will open up the Display Request Window. where you can see the change request in hierarchal order. You can use it now during object creations.

Package Type: You can choose between three package types: o Standard package / Not a main Package (Can contain Repository objects and other packages) o Main package (Can only contain other packages) o Structure package (Can only contain main packages) 21 . $TMP package is used for local practice and test programs. From the outside. Transport Layer: The transport layer determines if the objects of this package are to be transported to a subsequent system and. The name should follow the customer namespace conventions. All objects that can be changed using ABAP Workbench (Repository Objects) are part of package. Use access: is the right of one package to use the visible elements in the interface of a second package (but not the other way round). and so on) and handle their connection to the ABAP software logistics (Change and Transport System). For customer developments you should enter HOME as the software component. For an element to be visible outside the package. Packages help developers to modularize. With nesting you can split up larger units of the SAP System and structure them in a hierarchy. encapsulate.Packages Packages are used to organize development objects (programs. screens. tables. types. it must be contained in at least one package interface. Every AS ABAP contains a predefined package named $TMP. • When we create a package. Visibility: is a property of package elements. to which system. and decouple units in the SAP System. Description: To define the package. a package looks like a "black box. Packages may have the following attributes: • • Nesting: allows to embed packages in other packages. BAPIs. Application Component: Determine the location of the package within the application hierarchy by specifying the corresponding application component. Software Component: The software component describes a set of development objects that can only be delivered in a single unit. if so. we specify the following properties: • • • • • • Package: The name of the package to be created. function modules." They are always visible to other elements in the same package and always invisible to embedded (sub-)packages within their package. Every package starting with $ character is considered local and can’t be transported to other SAP system.

Creating Package Package can be created in two ways: a) In the navigation area of Object Navigator (SE80). f) Package Type: Not a main Package (since Main Package can’t directly contain development objects). the system branches to a dialog for creating a package. 22 . choose the object type Package from the object list and enter the name of the package in the input field below. Enter the following properties in Create Package dialog. 1. e) Transport Layer: ZNSP (For our demo system you should use the transport layer ZNSP).Note: Values like Application / Software component is developed by system administrator when system is created. Enter Package Name and push Create button. If the specified package does not already exist. a) Package: Z_MyPackage b) Description: My Training and Demo Programs c) Application Component: CA (Press F4 for selection and F1 for detail help). b) Call the package builder (SE21 or SPACKAGE). Choose Enter. d) Software Component: Home (Press F4 for selection and F1 for detail help).

4. If you have already created transport request. 3. In new create request dialog enter short description.2. After selecting Save you will be prompted for a transport request. Note: In a real-world development project you will always use a transport request that is created in the Transport Organizer (SE09) and paste this into the dialog with 23 . push Own Requests button or select the Create button to create new one.

This ensures that only objects declared in the package interface of the package can be addressed from other transportable packages.the header Prompt for transportable Workbench Request. 24 . if you just need a transport request without any particular properties. 6. Click Save button on standard toolbar and close the Package Builder. Check the Package Check as Server. you can do it the way we do it here. Pressing the Save button opens another dialog window and we are done with transport request. 5. Clicking Continue will bring Package Builder: Change Package Window.

3. 25 . separation of byte and character string processing) and "Fixed point arithmetic" (for decimal numbers the decimal separator is taken into account in calculations) should always be checked. 5. Press Save button. Right-click on the package Z_MyPackage and choose Create – Program. One of the most important program properties of an ABAP program is its type. From the list provided. Logical Databases option is no more used in ABAP Objects. Enter SE80 in text field of standard toolbar to open Object Navigator. Deselect “With TOP INCL” (Top Include) because we do not need a top include and confirm. 2. In particular. Select Package from Object List and type Z_MyPackage into text field below and press return key. 4.Creating Hello World Program in Package 1. You will see that our package is now visible in the Repository Browser. and change or add no other properties. ensure that the properties "Unicode checks active" (strict static type checks. Next dialog shows the properties of the new program. we want to select the type "Executable program" for our simple Hello-World program. Enter the name of the program we want to create Z_A_HW.

The transport request our package belongs to is already in the relevant field. 7.6. When you create an object. the corresponding object directory entry is also created. Again Confirm it. Create Object Directory Entry dialog appears. Next dialog prompt for transport request. 26 . click save to continue. The Object Directory is a directory of all the Repository Objects that make up the SAP System.

10. You can also double click the program name to open ABAP Editor. 27 . and also contains an initial statement named Report. Next the ABAP Editor is appear. This syntax consists of a few lines of comments.You can see the framework predefined by the ABAP Workbench. To configure the new ABAP Editor go to Utilities  Settings  Front-End Editor (New). 9. where you write code. Click Yes if you wanted to check the quick start.8.

28 . To change the program.11. ABAP Editor uses the Pretty Painter. To configure it go to Utilities  Settings  Pretty Painter. Check Indent and Convert Uppercase /Lowercase. 13. Click the Pretty Painter button in the ABAP Editor and the format of statements changes. To format the source code. Go to the change mode by pressing the respective button: Below the report-statement enter: 12.

15. or Execute  Direct from context menu 17. Also to call the program from other program the use the SUBMIT …. 16. The expected “Hello World” output appears in a special screen. Using the Execute function or transaction codes (SA38 and SE38). During The error-free source code is converted to byte code that is stored in the database. 29 . The error-free program must be activated. Note: ABAP Programs can be executed by two ways.14. To run the program we press the icon: of program name or by pressing F8. Select Activate function . Or Check button from standard toolbar. SA38 can be used only to execute or run a program. To check the syntactic corrections. select Check from the context menu of the program name in object list. SA38 can be used also by ABAPers to execute the program. After activation program will be visible to every user using System  Services  Reporting. It is more recommended to use by Functional Consultants/Users of the program to reduce the risk of mistakenly modification or deletion of the program. SE38 is use to display an ABAP Editor screen where transaction is not limited only to program execution but also to display or modify the program code.

With addition AND RETURN specify the system returns to the caller after the called program is terminated. 18. To display the “Hello World“ is message box change the code to: 30 . SA38 Call SE38 Call ABAP programs can also be called through transaction codes (transaction maintenance SE93).statement. and to abort the calling transaction use LEAVE TRANSACTION. To call transactions from other program use the statement CALL TRANSACTION ….

g. 31 . Call and Operational Statements). Operands. Instead of ’I’ try E. Control. Output with Type ‘I’ Output with Type ‘E’. message will be shown in status bar Dissecting the Hello World Program ABAP program consists of statements. ABAP keyword determines the category of the statement. Modularization. In our example REPORT is the keyword and ZAHWP is the operand. X for type message. Operators and Special Characters. Possible tokens include Keywords. Statements are composed of tokens and terminated by Period (. Tokens must be separated by at least one space.As a result a dialog window greets the world. (e.).

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 Blocks. Examples of objects that can be declared or defined here are data types. start with an introductory statement. in turn. The following types of processing blocks are available. every ABAP program follows a fixed program structure that divides it into two parts: a) Global Declaration part b) Procedural part Global declaration part directly follows the introductory statement.Every standalone ABAP program. select a semantically relevant program structure and make the structure visible using comment lines. subroutines and function modules with their own local data area) Dialog modules (processing blocks without local data) Event blocks (handle events of processes in the ABAP runtime environment) 32 . data objects and screens. To keep the program readable. Each time a program is executed. • • • Procedures (methods. After the global declaration part comes the procedural also known as implementation part. which will be visible and applicable throughout the entire ABAP program. The arrangement of processing blocks in the implementation part is not significant for program execution. The REPORT keyword expresses the fact that historically executable program was once exclusively used for reporting." which is supported by the ABAP Workbench and inserted at this position. Declarative statements can be used for definitions and declarations. the "top include. at least one processing block is called by the runtime environment as a point of entry. control is returned to the calling program or runtime environment. interfaces. the entire program is loaded into the memory. can call additional processing blocks of same or other program. Every ABAP statement that is not part of global declaration part always belongs to exactly one processing block. these declarations are generally made in a special include program. The order in which processing blocks are executed is controlled by calls (from other processing block) or by the ABAP runtime environment. Statements within processing block are processed sequentially. When first processing block of a program is called. all types of programs except for so-called include programs. When the last processing block is terminated. classes. For larger programs. The DATA statement declares a data object msg of type string and initializes it to a start value “Hello World“. that is. In our first program. the introductory statement is REPORT. Processing blocks can’t be nested. which. After the introductory statement.

Set the following fields in Create Class dialog. when program is executed. the implementation of the block is automatically called. The WRITE statement outputs a list and it is driven by the classic SAP Dynpro technology which should not be used to applications with state-of-the-art user interface. It will pop up the Create Class dialog. You can compare the write-statement to the output to the console in Java. To mark only the final portion of a line as a comment. You should use Dynpro-based UIs only in test-programs if you want to output (or input) some values in a quick and dirty way. That is.START-OF-SELECTION statement introduces a processing block which plays the same role in executable programs as the main method in Java program. Name: Z_CL_HW Class Type: Usual ABAP Class Brief Description: My hello world class Instantiation: Public Final: Check (Means that this class can’t be inherited) 33 . 2. Select Create  Class Library  Class from the context menu of Z_MyPackage in the Repository Browser. Object Oriented Version of “Hello World” Program 1. Comment lines are introduced by an asterisk * in the first position. you can use the character “.

Attribute: msg Level: Instance Attribute Visibility: Private Typing: Type Associated Type: string 34 . Again Confirm it. Next dialog prompt for transport request. Enter the following values in respective columns. The transport request our package belongs to is already in the relevant field.3. In the Class Builder. select the Attributes tab to define attribute for a class. click save to continue. 5. 4. Press Save button and you will be presented with Create Object Directory Entry dialog. An attribute is a data object declared within the class.

The dialog displays pending inactive objects. Make sure that the cconstructor is selected in the list. To define constructor push Constructor (F5) button in class builder. Method: print_hello Level: Instance Visibility: Public Description: This method will print hello world message 7. To declare method. enter the following in respective columns write after the CONSTRUCTOR. 9. Click Continue to activate. Next to define the method. 35 . Next type the following statement in print_hello method. To switch between the class builder and editor select previous button and next button . click on Methods tab. Type the following statement in constructor. To implement the methods click the Source Code function . This concludes the definition of class in class library so check and activate the class.6. 10. 8.

Press Save button. 36 . Deselect “With TOP INCL“ (Top Include) because we do not need a top include and confirm. 13. 14. Enter the name of the program we want to create Z_OO_HW. Next dialog shows the properties of the new program. where local classes are created and their public methods are connected to transaction codes.11. In particular. Right-click on the package Z_MyPackage and choose Create – Program. let’s create the program of type Subroutine pool. From the type list select the type "Subroutine Pool" change or add no other properties. To consume this class. ensure that the properties "Unicode checks active" and "Fixed point arithmetic" should always be checked. Note: Subroutine pool is a type of ABAP program. 12.

Next dialog prompt for transport request.15. enter the following listing. The transport request our package belongs to is already in the relevant field. This will open the ABAP Editor. Again Confirm it. 17. Create Object Directory Entry dialog appears. 16. 37 . click save to continue.

It won’t work. For us the transaction means the execution of an ABAP program via “Transaction Code“. because subroutine pool has no pre-defined starting point like START-OF-SELECTION for executable programs. 19. is historical in nature and the reason for this context is explained by the fact that a classical ABAP application program generally executed a business transaction on the database table. Note: Transaction like the name “report“ for executable program.18. 38 . Select Create  other(1)  Transaction from the context menu of our package in the repository browser and fill the dialog window that appears. It is a twenty-character name which is assigned to a screen or a method of an ABAP program and is used for program execution. Transaction Code: Z_HW Short Text: Hello World Start Object: Method of a class and Select Continue. Now if you activate and Execute (F8) the program. To solve this problem we have to define the transaction code.

On next screen maintain OO transaction.20. 39 . click save to continue. 22. OO Transaction Model: Uncheck (to fill the input fields) Class Name: z_cl_client Method: main Local in Program: Check Local in Program: Z_OO_HW 21. Create Object Directory Entry dialog appears. Click Save on standard toolbar.

40 . The selector -> is used for accessing an instance public component.. To run. The main method is a user for our global class. and ENDMETHOD we provide the implementation for method.. The implementation part of local class must implement between CLASS. Next dialog prompt for transport request.23.. Between METHOD . The REF TO means that obj is a reference variable which is pointing to z_cl_client reference type or class. /o runs the program in new window. Dissecting the OO Hello World Program The declaration part contains the declaration of local class z_cl_client.. The transport request our package belongs to is already in the relevant field.. The CREATE OBJECT creates the obj object. 24. in contrast to /n.. IMPLEMENTATION and ENDCLASS. The public section show defines the public visibility of the static method main which is defined with CLASS-METHOD statement.. Again Confirm it. enter the \oZ_HW in the input field of the standard toolbar.

ABAP Program Types Unlike Java where programs are simply containers for classes. and whether it can work with its own screens (Also known as dynpros) are the most general type of user dialog in SAP applications before NetWeaver. subroutine pool. They are declared with the CLASS-POOL statement but as it is created with Class Builder (SE24) of ABAP Workbench. Interface Pools / Global Interface Interface pool is a container for exactly one global interface. a public method of global class can be called from another ABAP program or it can be linked with a transaction code. which means it is generally not displayed as a single continues source code. interface pool. All the reusable code is programmed here. When you start an ABAP program. that is. you must call at least the first processing block from outside the program. Function groups and their function modules are the procedural predecessors of global classes with public methods. in background processing). Interface pool is created in Class Builder (SE24) of the ABAP Workbench. for Remote Function Calls (RFC). which processing blocks a program may contain how the program is handled and executed by the ABAP runtime environment. There are seven program types from which you can choose: executable program. Function groups (like exe programs and module pools) can contain 41 . which calls the first ABAP processing block. You do not define them in ABAP programs. but instead in the Screen Painter. module pool. They are introduced with the INTERFACEPOOL statement. for example. When you run an ABAP application program. This processing block can then either call further processing blocks or return control to the runtime environment. A class pool is loaded into memory by using the global class. The global interface can be implemented in any global or local classes. or through an external interface.). The program type defines the basic technical attributes of a program. class pool. for example. The program can be started either by the user or by the system (for example. there are different ABAP programs types that play different roles on the application server ABAP. that is. and include program. Class Pools / Global Class Class pool is a container for exactly one global class and more than one data types and local object types (local classes and interfaces). function group. from the runtime environment. the runtime environment starts a processor (dependent on the program type). Function Groups / Function Pools Function group contains a procedures (Function Modules) processing block.

Executable Programs Executable programs can contain all processing blocks supported in ABAP. A subroutine pool that contains a class with a main method that is connected to a transaction code is very similar to Java program. the system still executes the SUBMIT statement in the background. the source code of an executable program starts with the REPORT statement. In ABAP Objects. It is maintained directly in the ABAP Editor (SE38) of ABAP Workbench. executable should only be used if direct execution using the name is important. function groups should be used as carriers of dynpros. Module pools were originally designed for the dialog programming with dynpros. It is maintained directly in the ABAP Editor (SE38) of ABAP Workbench. Module pools are no longer play a role in ABAP Objects. with the exception of function modules. you can create local classes in subroutine pools and connect their public methods to a transaction code. Executable programs are only started with the SUBMIT statement. The use of subroutine is obsolete in ABAP Objects. Although NetWeaver AS ABAP offers several ways to call executable programs by entering their name on the screen. 42 .dynpros as components. and why running an executable program is often called reporting. which is not possible in class pools. Module pools are introduced with the PROGRAM statement. Instead. Analogously. and as many local classes as required. Executable programs are often referred to as reports. executable programs are currently only required for background processing. module pools can contain all processing blocks supported in ABAP and as many local classes as required. Subroutine Pools Subroutines pool contains a subroutine processing blocks that can be called by other programs. Function groups are also required for RFCs. With the exception of reporting event blocks and function modules. For technical point of view. instead you should branch from there into methods. You can call function groups from methods but no more functional coding should be created in function modules. If you require working with dynpros in ABAP Objects then function groups is the first choice. Today you should only handle the START-OF-SELECTION event of the reporting (exe program) process and jump from the corresponding processing block directly to a method of a local class. Module Pools Module pool acts as a container for dialog modules called by the dynpros flow logic. However. Function pools are introduced with the FUNCTION-POOL statement and maintained with Function Builder (SE37) of ABAP Workbench. Subroutine pools are created using the ABAP Editor (SE38) of ABAP Workbench and are introduced with the PROGRAM statement. Only executable programs can be called using their name.

you can use global classes or interfaces. It can be created automatically when you create an ABAP program in the ABAP Workbench by simply selecting the corresponding checkbox. The naming convention is that the name of top includes ends with “TOP”. The “TOP include” is designed for the global declaration part of an ABAP program. such as the declaration part for global data. if the programs are used in parallel. We recommend the declaration part of a local class or processing block (method). When you organize program using include program. all statements of global declaration part should be included by the top include. as it can be transported individually. No more type groups should be created in ABAP Objects.Type Groups Type groups only contain declaration part for global data types and constants which can be made visible in any ABAP program. it is preferable to separate logical program units. individual methods or function modules to be processed independently of their class pool or their function group. The names of include programs should correspond to those that are proposed by the ABAP Workbench. and similar or individual processing blocks into independent include programs. It is maintained with ABAP Dictionary (SE11) tool of the ABAP Workbench. Include Programs Include programs have no introductory program statement and. They are automatically generated by ABAP Workbench when you create programs such as class pools or function pools. types and constants can be published by global classes and interfaces. During syntax check the INCLUDE statement is replaced by the source code of the include programs. Include programs should never be sued for multiple usage of source code in several compilation units. 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. The following matrix shows all ABAP program types and their supported features. they do not represent independent compilation units with their own memory space. Type groups are predecessor technology for general type definitions in the ABAP Dictionary and in global classes or interfaces. Instead. which allows. Instead. Type groups are introduced with the TYPEPOOLS statement. The reason for this that the inclusion of an include program in several programs dramatically restricts both their maintainability. unlike all other program types. an include program that is included in several programs is loaded several times into the program memory of the application server. You can create your own include programs directly with the ABAP Editor (SE38) tool of ABAP Workbench. 43 . Include programs make large program much easier to handle. Include programs have no technical relationship to processing blocks. Further more. However.

Recommended Program Types with ABAP Objects • • • • • Use class and interface pools for reusable code in global classes and interfaces. which is technically suitable for background processes. The same applies for exe programs as for subroutine. as containers for dynpros and for RFC-enabled function modules. Subroutine pools can serve as Java-like programs in which you can call exactly one main method from outside. Use function groups only where technically necessary. 44 . that is. New module pools or type groups should no longer be created for programming with ABAP Objects. though you can call them using SUBMIT statement.

Since many functions (dynpros and RFC) of an ABAP are still offered in function modules. Instead you can create local classes for internal modularization in all program types that can contain operational code. Subroutines These are predecessors of methods for internal procedure calls in the procedural programming model. Function modules are introduced with the FUNCTION statement and concluded with the ENDFUNCTION statement. The execution of ABAP program is synonymous with a process in ABAP runtime environment. Function modules can only be created in function groups or function pools program type. You call methods from ABAP programs using the CALL METHOD statement.ABAP Program Processing Blocks An ABAP program is embedded in a runtime environment provided by Application Server ABAP. Function Modules These are predecessors of methods for external procedure calls in the procedural programming model. You call function modules from ABAP programs using the CALL FUNCTION statement. However most of the concept of processors are primarily connected to procedural/event oriented ABAP programming and has lost significance for modern ABAP Objects. It is also called internal procedures. they can continue to be called from methods. Subroutines are replaced entirely by methods and should no longer be used. Methods Method is a component of a class. Function Modules or Subroutines. • • • Procedures Dialog Modules Event Blocks Procedures Procedure processing blocks have a local data area and can have a parameter interface. Method processing blocks can only be defined in class pools program type. The following types of processing blocks are available. which controls the program by calling the processing blocks. It is also called external procedure. Procedure can be in the form of Method. OO ABAP program is built from methods that are organized in classes. 45 . METHOD statement and concluded with the ENDMETHOD statement. The runtime contains processors that execute the ABAP programs.

Selection Screen Event Block It is triggered by the screen selection processor of ABAP runtime environment during selection screen processing. Classical ABAP programs and executable programs particularly are event-oriented. You call subroutines from ABAP programs using the PERFORM statement.Subroutines are introduced with the FORM statement and concluded with the ENDFORM statement. Dialog modules called from the screen flow logic (screen command MODULE). This block can be used for global data initialization. Event blocks are called through events which are triggered by user actions on selection screens and lists or by the ABAP runtime environment. The events blocks can be divided into: Program Constructor Event Block Directly after an executable program. They can be used in ABAP programs that support their own dynpros (executable programs. They can only work with global data from the declaration part of their ABAP program. In ABAP Objects the creation and processing of classical lists is obsolete in most cases. which prevents data encapsulation. Dialog modules are rarely needed nowadays. Dialog modules processing blocks should contain little or no operational code other than method calls. which prevents data encapsulation. 46 . Dialog modules are introduced with the MODULE statement and concluded with the ENDMODULE statement. a special processing block can be executed exactly once. ABAP Objects has an explicit event concept where events are triggered by a statement in methods and are handled by special methods (event handlers). Therefore it resembles class constructor. Dialog Modules Dialog Modules are processing blocks without a local data area and without a parameter interface. a module pool. module pools). They can only work with global data from the declaration part of their ABAP program. function groups. a function group or a subroutine pool has been loaded. This processing block is defined as an event block using the event keyword LOAD-OFPROGRAM. List Event Block It is triggered by the list processor of the ABAP runtime environment during classical list processing. Selection screens are special dynpros. Event Modules Even Modules are processing blocks without a local data area and without a parameter interface.

47 .Reporting Event Block It is triggered by the reporting processor of the ABAP runtime environment if an executable program is executed. In ABAP Objects you should only implement the START-OF-SELECTION.

LEAVE TO. Examples of modularization keywords: START-OF-SELECTION. CASE. The different statement categories are as follows: Declarative Statements These statements define data types or declare data objects which are used by the other statements in a program or routine.. Examples of declarative keywords: TYPES. The collected declarative statements in a program or subroutine make up its declaration part. SET USER-COMMAND. 48 . DATA. Modularization Statements These statements define the processing blocks in an ABAP program. and always ends with a period. Control Statements You use these statements to control the flow of an ABAP program within a processing block according to certain conditions.. Examples of control keywords: IF. SUBMIT. Each statement contains one or more words separated by at least one space. TABLES. ENDMODULE. MODULE . The blocks you call can either be in the same ABAP program or in a different program. WHILE. CALL. The first keyword of statement determines the category of the statements. Call Statements You use these statements to call processing blocks that you have already defined using modularization statements.Elements of ABAP Language Statements Each ABAP program is composed of one or more statements. The first word of a statement is the keyword. Examples of call keywords: PERFORM. A statement can include one or more additions.

it is not worth using DDL statements. Open SQL: Open SQL is a subset of the standard SQL92 language. Statement sequence: WRITE ‘Hello’. write the remaining parts of the individual statements. It allows you to take advantage of all of your database’s characteristics in your programs. After the colon. INSERT. 49 . It contains only Data Manipulation Language (DML) statements. The ABAP Dictionary uses Native SQL for tasks such as creating database tables. Chain statement: WRITE: ‘Hello’. In ordinary ABAP programs. ABAP programs that use only Open SQL statements to access the database are fully portable. The database interface converts the OPEN SQL commands into commands of the relevant database.) after the last part to inform the system where the chain ends. ADD. Chained Statements The ABAP programming language allows you to concatenate consecutive statements with an identical first part into a chain statement. separating them with commas. WRITE ‘world of ABAP’. it allows you to use DDL operations. ‘to the’. Ensure that you place a period (. It does not contain any Data Definition Language (DDL) statements (such as CREATE TABLE or CREATE INDEX).Operational Statements These keywords process the data that you have defined using declarative statements. write the identical part only once and place a colon (:) after it. Examples of operational keywords: WRITE. MOVE. since you cannot then take advantage of the central administration functions of the ABAP Dictionary. such as SELECT. In particular. WRITE ‘to the’. There are two kinds of database statement in ABAP: Open SQL and Native SQL. To concatenate a sequence of separate statements. Native SQL: Native SQL statements are passed directly from the database interface to the database without first being converted. Functions of this type are contained in the ABAP Dictionary. Database Statements These statements use the database interface to access the tables in the central database system. ABAP programs that use Native SQL statements are database-specific. and DELETE.

Statement sequence: SUM SUM SUM SUM = = = = SUM SUM SUM SUM + + + + 1. 4. 2. Chain statement: SUM = SUM + : 1. 2. 4. In a chain statement. the first part (before the colon) is not limited to the keyword of the statements.‘world of ABAP’. 3. 3. 50 .

The DECIMALS is used to define the number of decimal places for packed number type (p). Local Data Objects: are accessible only from inside the methods or other procedures (function modules. Data objects can be created by using declarative statements (DATA statement) or CREATE DATA statement. Data objects created using CREATE DATA are not assigned a name (anonymous data objects) and can be addressed only via reference variables. The life cycle of local data object spans over the body of method or procedure. Data objects are instances of data types.Data Objects and Data Types Data Objects Data object is a named memory that is structured according to a particular data type. The VALUE addition defines the initial value for data object data_obj. Each ABAP data object has a set of attributes (field length. number of decimal places) which it acquires from its data type. The statement defines a data_obj data object of type data_type. They are declared in the declaration part of a program. Global Data Objects: can be accessed from anywhere within the program. avoid using program global data. subroutines) in which they are defined.c. Instance attributes can b addressed in all instance methods. instead use global classes. similar to class instances. Class Level Data Objects: Data declarations in the declaration part of classes either create instance attributes or static attributes. Data objects that have been created using declarative statements are assigned name and can be accessed through this name. while static attributes can be addressed in all methods via their names. The visibility of a data object indicates from where in the program the data object is accessible. In ABAP Objects.n and x) discussed later. DATA data_obj TYPE data_type [LENGTH len] [DECIMALS dec] VALUE val] [READ-ONLY]. Data objects reside in repository. local. 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 data_obj_ref TYPE data_type [LENGTH len] [DECIMALS dec]. LENGTH must be used for incomplete types (p. Data objects have three levels of visibility (aka Context of Data Object): global. The life cycle of global data object is bound to the life cycle of its program in the internal session. 51 . and class.

You declare constants using the CONSTANTS statement. 12356. Constants or Text Symbol. Variables Variables are named data an object that you can declare statically (compile time) using declarative statements or dynamically while a program is running. Constants Constants are data objects whose contents cannot be changed. 52 . They can be addressed using the name of the text symbol. Variables. and RANGES statements. i. data type). internal tables.e. CONSTANT data_obj TYPE data_type VALUE val | {IS INITIAL}. they exist in the program source code. or structures containing internal tables. IS INITIAL is use to set a constant data_obj to its type specific initial value. while the life cycle of a static attribute depends on the life cycle of an internal session. You cannot define constants for XSTRINGS. Literals can be numeric or character. The text pool contains the text elements of the program. number of decimal places. Text Symbols are maintained with Text Element Maintenance (SE32) of the ABAP Workbench. references. the corresponding data objects are generated from the texts stored in the text pool. they have attributes (field length. or “Hello World”. They are therefore referred to as unnamed data objects. without to bother about the logon language of specific user. Like all data objects. For example. Literals Literals are not created by declarative statements. SELECT-OPTIONS. several text pools can be defined in different languages for a program. STATICS. Text Symbols are linked to the translation. but no name. Data objects can be of the form: Literals. Instead. Text Symbols Text symbols are pointers to texts in the text pool of the ABAP program. PARAMETERS. They allow you to store changeable data under a particular name within the memory area of a program. you can use text symbols in places where you want to display texts from the program on the user interface. When the program starts.The life cycle of an instance attribute depends on the lifecycle of an object. CLASS-DATA. You declare variables using the DATA.

There are total 10 built-in elementary data types: • Fixed Length Elementary Data Types The “Length” column indicates the minimum and maximum number of bytes or characters that a data object can occupy. Data type determines how the data is stored in the memory. You can also define your own elementary data types in ABAP using the TYPES statement. You base these on the predefined data types. c. There are eight fixed length and two variable length elementary data types. 53 . otherwise you cannot use them to declare data types and data objects. n and x data types means that these data types are incomplete or generic and it is required to use the LENGTH addition to specify their length. and t are not generic and complete. In ABAP we have the following data types. specifying length in this is forbidden. The difference between variable length data types and fixed length data types is that the length and the memory space required by data objects of variable length data types can change dynamically during runtime. Here txt data object is an instance of data type c with initial value “Hello World”. you don’t need to specify LENGTH when declare a data object or data type. The TYPE keyword defines the data type for data object as: DATA txt TYPE c LENGTH 12 VALUE ‘Hello World’. This determines all of the technical attributes of the new data type. The other types i. f. In fact. and tells the ABAP statement how to handle it.Data Types Data types specify the attributes of data objects. Data types do not occupy memory. Data objects that are declared using one of these eight data types are referred to as static data objects because the utilized memory space is statically (during declaration). Elementary Data Types These are data types of fixed or variable length that are not made up of other types. The interval is specified in length column for p. d.

Complex Data Types allow you to manage and work with semantically related datasets under a common name. There is nor built-in complex data types. Complex data types can be structured types or table types. 54 .65535 characters 1 . A complex data type must be constructed from existing types.Data Type Length Standard Length Initial Value Meaning Numeric Data Types i f p 4 bytes 8 bytes 1-16 bytes 1 .65535 characters 8 characters 6 characters 0 0 0 Integer Floating point Packed number Text Field (Alpha numeric) Numeric Text Field (Numeric characters) Date Field (Format: YYYYMMDD) Time Field (Format: HHMMSS)) Hexadecimal field 8bytes Character Data Types c n d t 1 character 1 character ‘….’ '0 … 0' ‘00000000' '000000' Hexadecimal (Byte) Data Type x • 1-65535 bytes 1 byte x'00 …00' Variable Length Elementary Data Types Length Standard Length Initial Value Meaning Data Type Character Data Types string xstring Character Strings Byte Strings Complex Data Types Complex data types are made up of other data types.

There are types of data references (references to data objects) and object references (references to instances of classes). 55 .Reference Data Types Reference types describe data objects (reference variables) that contain references to other objects.

The above line says that txt is a data object having same properties as that of msg. The TYPES keyword is used to define an independent data types. For example the following line is executed without any errors. This shows that the properties like type and length is bound to msg and you can’t use the TYPE addition to msg to define data objects of type msg. DATA txt TYPE msg VALUE ‘Welcome’. That is a type defined only for that particular data object and can’t be used for other data objects. The TYPES keyword creates data type and does not allocate memory space. Now these properties i. LIKE refers to predefined data objects.e. similar to classes that can be used for template for objects. As a result.Defining Data Types There are two ways to define data types in ABAP: • • Bound Data Type Independent Data Type Bound Data Type The data statement DATA creates a bound data type. Independent Data Types Independent data types act as a template for data objects. DATA msg TYPE c LENGTH 20 VALUE ‘Hello’. LIKE similar to TYPE also allocates memory space. You will get an error saying that type msg is unknown. 56 . If we try the following declarative statement. For this reason ABAP provides an independent data types.e. The above statement declares msg data object of type c with length of 20 characters. DATA txt LIKE msg VALUE ‘Welcome’. this would consume a lot of memory. But the problem with this method is we are creating data objects even for the purpose of defining data types i. The LIKE keyword is used to solve the above problem. The syntax of TYPES is almost identical to the DATA statement but without data object specific additions like length and value etc. type and length is just associated or bound with data object msg.

To declare data objects of type text: DATA txt1 TYPE text VALUE ‘Welcome’. Use LIKE addition whenever your declaration is directly liked to a data object. • 57 .The TYPES statement for an independent character-like data type text of length 20 would be as follows: TYPES text TYPE c LENGTH 20. Examples of this include auxiliary variables in procedures that must have the same type as interface parameters or their components. In all other cases. DATA txt2 TYPE text VALUE ‘to ABAP’. that txt1 and txt2 are of type text which in turn of type c and having length of 20. This keeps your program valid even if the data type of the data objects changes. This means. With so many different ways to declare data types. you should use the TYPE addition to directly reference appropriate independent data types. the question arises as to when you should use which option? • • It is good programming style to create a self-defined data type only as an independent type.

It is having 8-bytes of size. The default value is 0. DATA number TYPE p DECIMALS 2 VALUE 23. while the exponent specifies the position of the decimal point. The number of decimal places is defined during declaration of data type or data object using the DECIMALS addition after TYPE. f is a complete type.sign. The default value is 0. DATA no TYPE decfloat16 VALUE 12. • Data Type decfloat16: decfloat16 is complete type. a 16-digit mantissa and the exponent. The default value is 0. DATA result TYPE f. It is decimal floating point number with 16 decimal places. It is decimal floating point numbers of this type are represented internally with 34 decimal places.Elementary Data Types Usage Numeric Data Types • Data Type i: i is a complete type. It is having 16-bytes of size. DATA no TYPE decfloat34 VALUE 23. • Data Type f: f is a data type for binary floating point numbers. dimensions or weights etc. It is having 8-bytes of size. having size of 4-bytes. • Data Type decfloat34: decfloat34 is complete type. DATA count TYPE i VALUE 0. • Data Type p: p is incomplete type. It is packed numbers in the Binary Coded Decimals (BCD) format with fixed number of decimal places. The default value is 0. It is consists of three components: the +/. The type p is useful for monetary amounts. used for integers. With SAP NetWeaver 2007 new data type decfloat16 and decfloat34 are introduced to replace the f and p data types. The default value is 0. 58 . Character Data Types • Data Type c: c is a data type that can be used for any character string of fixed length. Mantissa contains the digits of the number. Often used for index or count variables. c is incomplete data type for this purpose you must specify the length property for this data type.

The sy-uzeit system field provides the current time. DATA hex TYPE x LENGTH 3. Data objects of this type can only contain numbers. DATA now TYPE t. HHMMSS. postal_code = ‘25000’.O Box numbers etc. • 59 . DATA today TYPE d. Other operations utilize the character nature. d is a complete type. today = sy-datum. but these numbers can not be directly used to carry out calculations. but not a numeric data type. DATA postal_code TYPE n LENGTH 5. Typical use areas can be ZIP codes. now = sy-uzeit. • Data Type n: Type n is a special case of type c for numeric characters. hex = ‘F3456AB’. n is also incomplete data type. the time is regarded as a number that corresponds to the number of seconds that have been passed since midnight 000000. Phone Numbers. The sy-datum system field provides the system date. now = now + 3600. txt_line = ‘ABAP programming is fun!”. If data object of type d is used in the position of operands where a numerical value is expected. P. today = today + 2. . If data object of type d is used in the position of operands where a numerical value is expected. Other operations utilize the character nature. It is complete data type. the date is regarded as a number that corresponds to the number of days that have been passed since 00010101.DATA txt _line TYPE c LENGTH 72. YYYYMMDD. • Data Type x: x is a data type used for storing byte strings of fixed length. and then one hour is added to the now data object. • Data Type t: t is a data type for time information in the format. Type x data objects can generally be used for byte-like content where the fixed length is important. It is incomplete data type. after the calculation. Data Type d: d is data type for date information in the format. it assign the date of day after tomorrow.

• Data Type string: Type string is a data type that can be used for any characters strings of variable length. 60 . however you can use the VALUE addition to initialize a string data object. The LENGTH and VALUE and addition is not allowed with xstring data type. DATA txt_str TYPE string. DATA txt_xstr TYPE xstring. The LENGTH addition is not allowed with string data type. • Data Type xstring: xstring is a data type that can be used for any byte string of variable length.

There are Flat. The colon and the commas indicate that we are dealing with several DATA and TYPES statements. The data object of a structured data type is called structure. TYPES: BEGIN OF structure_name. struct_comp2 TYPE|LIKE …. 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. The components of the structure can be elementary data types. struct_comp2 TYPE …. a structure. A flat structure only references elementary types. Structured Data Type Structured data type is consists of a sequence of other data types.Complex Data Types Complex data types can be structured types or table types. but not a 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 structure_name. A deep structure references at least one table type. ……… ……… struct_compn TYPE… END OF structure_name. struct_comp1 TYPE …. ……… ……… struct_compn TYPE|LIKE … END OF structure_name. A nested structure references at least one further structure. an internal table or a reference data type. The units that make up a structured type are called structure components (fields). All the statements that lie in-between 61 . struct_comp1 TYPE|LIKE …. The addition of BEGIN OF and END OF statements define the beginning and end of a structure called structure_name. nested and deep structures.

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

For the street. You can integrate the components of a structure into another structure using the INCLUDE statement as: DATA BEGIN OF struct_1.The program produces the following out put. The substructure city_struct consists of two components zipcode and name.) and we declare the street component with type street_struct. For the address. we declare a structure address_struct as a data object (everything we discussed for DATA also holds true for CLASS-DATA. for declaration of static attributes. …… INCLUDE STRUCTURE struct_2 AS name 63 . we created a separate structured type street_struct with components name and no.

64 . The components of struct_2 will be transferred as components into the struct_1 structure. The INCLUDE statement is not an addition to the TYPES or DATA statements. TYPES BEGIN OF struct_1. …… TYPES END OF struct_1. …… INCLUDE TYPE struct_2 AS name [RENAMING WITH SUFFIX suffix].[RENAMING WITH SUFFIX suffix]. Instead. it interrupts the chained statement that must be restarted afterwards. …… DATA END OF struct_1. The RENAMING addition can be used to avoid naming conflicts. or individually by their component names. They can either be addressed commonly under the name name.

All the components are allocated at the same level. An internal table consists of a dynamic sequence of lines of the same data type (it can be think of an arrays in Java or C#. The table type 65 .Net). The data objects of table types are internal tables. internal tables are internally managed by references.The program produces the following out put. This type of structure definition avoids complex nested structures with long name chains. Naming conflicts between the name components are avoided by the use of different endings. Internal tables are dynamic data objects like strings. Table Types Table types represent the second complex data type.

This table category is suited whenever the key accesses represent the central operation on the table entries. The following syntax can be used to declare the internal tables. STANDARD Table: is managed internally by a table index. With a key access. line type is fixed during declaration. The data_type and data_object represent the line type. because the table is accessed via a binary search. Example below demonstrates the usage of internal table. reference types. HASHED Table: is managed internally by a hash algorithm. The key of a standard table is always non-unique. structures and even other internal tables. independent of the number of table entries. This table category is suited best whenever the individual entries can be accessed using the index. elementary types. the response time is directly dependent on the number of table entries. TYPES The keywords STANDARD. Hashed tables can be accessed only via the table key. The internal table can contain any number of lines of the specified line type. DATA tab_name TYPE|LIKE STANDARD|SORTED|HASHED TABLE OF data_type|data_object WITH [NON-]UNIQUE KEY col1…coln. too. The key of hashed tables is always unique. The key of sorted tables can be unique or non-unique. You can use any line type. the response time is logarithmically dependent on the number of table entries. but not the number of lines. the table category and a table key. This table category is suited whenever the table must already be sorted when it is filled. With a key access. tab_name TYPE STANDARD|SORTED|HASHED TABLE OF data_type WITH [NON-]UNIQUE KEY col1…coln. They are always sorted by the table key and can be accessed via the table index or the table key. The response time is constant. An internal table has a unique or non-unique table key that can be defined by listing its components.describes the line type. Thus. SORTED and HASHED define the table category. The table key is required for the identification of table rows. 66 . SORTED Table: is managed internally by means of a table index. Access is possible via table index or table key.

After executing the loop will display five message boxes as: 67 .

Reference Data Types Reference types can contain a reference to other data objects or to instances of classes. The sy-index is a system field (System fields are filled according to the context by system runtime) gets the particular record number. It acts like Loop Iteration Counter. DEFAULT KEY is build from all columns of the internal table that have a character-type type (c. 68 . DATA ref_variable TYPE |LIKE REF TO data_type|data_object. Depending on the type of object that is referenced. n.Example above declares a standard table array whose line type is elementary data type i and whose key consists of the DEFAULT KEY. The APPEND statement appends a new line to the end of the indexed internal table. Those data objects are referred to as reference variables. xstring). t. we speak of data reference variables or object reference variables that can either contain data references or object references. The following syntax can be used to declare the reference data types. d. x. string.

The first two statements create the reference variable for data reference. CREATE DATA ref_variable TYPE data_type. you need a reference variable and the following statement: CREATE DATA ref_variable TYPE |LIKE data_type|data_object. The object component selector (->) can be used to access the components of the reference variable. The statements create a reference variable in the internal session of the current ABAP program. DATA obj_ref TYPE REF TO class|interface.TYPES ref_variable TYPE REF TO data_type. After the statement. To create a data object dynamically during a program. 69 . Example below demonstrates the usage of reference variable and object references. All of the data objects that you define in the declaration part of a program using statements such as DATA are created statically. the data reference in the data reference variable points to the object. TYPES obj_ref TYPE REF TO class|interface. The dereferencing operator (->*) can be used to access the entire data objects that is referenced. The following statements allow you to place a data reference to an existing data object in a reference variable: GET REFERENCE OF data_object INTO ref_variable. Next two statements create an object reference for class or interface. and already exist when you start the program.

The GET REFERENCE OF statement gets the reference of obj_ref and places it into the data_ref1 reference variable. while data_ref1 and data_ref2 are reference variables to obj_ref and i respectively. CREATE OBJECT statement allocates the reference obj_ref which enable us to access its attribute var. The declaration section introduces the obj_ref is an object reference to cls class.The program produces the following results. 70 .

After execution it is clear that both obj_ref and data_ref2 are pointing to same memory location. Generic Type any. this table type is also generic type. n. string. Thus reference types and dynamic data objects (strings and internal tables) are deep data types. p. x simple Types Comprised All data types c.s). On next line through dereferencing operator (->*) we access the var attribute of obj_ref (data_ref1 is pointing to obj_ref) and assign to data_ref2. By generic we mean that the data type is determined during runtime. You can assign a data object with a type from the second column to a formal parameter r field symbol (Field symbols are placeholders or symbolic names for other data objects. p . t. t.CREATE DATA statement creates a data object data_ref2 dynamically. 71 . string. p. d. and flat structures containing character like components c and string (text like types) x and xstring (byte like types) All table types Sorted tables Hashed tables Standard and Sorted tables Standard tables i (b. data clike csequence xsequence any table sorted table hashed table index table standard table. while the second column describes the types they comprise. All data types in which content of their data objects are references that point to working data in different locations of the memory are referred to as deep data types. n. xstring.s). and flat structures containing character like components If table type is defined using the TYPES statement or if it is defined in the ABAP Dictionary without specifying a key. Generic Data Types The generic data types allow the dynamic programming. d. x. f (numeric types) Corresponding built-in types with generic lengths and decimal places c. Flat and Deep Data Types All data types in which the content of their data objects represents actual working data are referred to as flat data types. table numeric c. f. Field symbols are similar to dereferenced pointers in C) that is typed with a generic type from the first column. Table below lists the predefined generic types in the first column. n. i (b. Thus all elementary data types of fixed length are flat data types.

for assignments between reference variables. For assignment between dynamic data objects (strings and internal tables).In assignment between deep data objects. 72 .e. the referenced object is copied and a new reference is created. The memory requirement for deep data objects is combination of a constant requirement for the reference (8 bytes) and a dynamic requirement for actual objects. reference semantics applies i. but not the referenced objects. value semantics applies i.e. only the references are copied.

Character string: Fields of type CHAR may have a maximum length of only 255 in tables. based on this structured type a physical database table is generated in the database. Table below provides an overview of all built-in data types of the ABAP Dictionary and their counterparts in ABAP programs. Data types of the ABAP Dictionary play the same role as the global types that are declared using the TYPES statement in classes and interfaces. Client: Client fields always have three places. The difference between the data types is based on the fact that the built-in data types of the ABAP Dictionary must be compatible with the external data types of the database tables supported by the AS ABAP. defining an input help (F4 help) and attaching a field help (F1 help) to a screen field are supported. ABAP Dictionary contains many more built-in types than the ABAP programming language. If longer character fields are to be used in tables. you reference a data type from the ABAP Dictionary. indexes. structures. you must choose data type LCHR. first a structured type is created in the ABAP Dictionary. When defining tables. Dictionary Type ACCP Description Posting Period: The length is set to 6 places for this data type. so the template of this data type has the form ‘____. Currency key: Fields of this type are referenced by fields of type CURR.ABAP Dictionary ABAP Dictionary is a central global storage for data definitions (metadata) of user defined types (data elements i. views and domains that can be accessed by all repository objects.e. provided this is permitted by the package check. a point is inserted between the year and month. you must declare data objects in an ABAP program. ABAP Type n CHAR CLNT CUKY c c c 73 . The ABAP Dictionary also provides a number of services that support program development. setting and releasing locks.__’. The length is set to 5 places for this data type. table). and these types also have different names. For example. In input and output. The ABAP Dictionary 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. Data types of the ABAP Dictionary enable a type-specific transfer of values between dynpros and ABAP programs. There are no restrictions on the length of such fields in structures. To use data from database tables. If an ABAP program. elementary types. The format is YYYYMM. the elementary components of that data type are converted into the built-in data types of the ABAP programming language.

Counter or amount field: with decimal point. The language key is displayed at the user interface with 2 places. The maximum length for this data type is 31 places. but has to be declared with a minimum length of 256. Date: The length is set to 8 places for this data type. and commas separating thousands. A DEC field has a maximum length of 31 places. Precession: Accuracy of a QUAN field. but is only stored with 1 place in the database. Equivalent to an amount field DEC. A field of this type must refer to a field of type CUKY (reference field). Language key: This data type always has length 1. sign. The length is set to 2 places for this data type. Numeric text: Long character field in which only numbers can be entered. The maximum length for this data type is 31 places. The length is set to 3 places for this data type. A field of this type must always refer to units field with UNIT format (reference field). If the length field is not filled correctly. this length field must be filled with the length actually required. The length is set to 10 places for this data type. Floating point number: The length (including decimal places) is set to 16 places for this data type. The length of this field is limited to a maximum of 255 places. Character string of any length: but has to be declared with a minimum of 256 characters. Quantity. If there is an INSERT or UPDATE in ABAP programs. If there is an INSERT or UPDATE in ABAP programs. this may lead to a data loss in the LRAW field! Fields of this type cannot be used in the WHERE condition of a SELECT statement. this length field must be filled with the length actually required. p d p f b s i c c x n s p 74 . 2-byte integer: between -32767 and 32767. Long byte string: of any length. If the length field is not filled correctly.CURR DATS DEC FLTP INT1 INT2 INT4 LANG LCHAR LRAW NUMC PREC QUAN Currency field: Equivalent to an amount field DEC. The output template can be defined with the user profile. 4-byte integer: between -2147483647 bis 2147483647. The length is set to 5 places for this data type. the database interface enters the length which was actually used in the length field. Fields of this type should only be used for length fields. With INSERT or UPDATE on the long field. this may lead to a data loss in the LCHR field! Fields of this type cannot be used in the WHERE condition of a SELECT statement. 1-byte integer: between 0 and 255.

Byte string: Fields of type RAW may have only a RAW maximum length of 255 in tables. String SSTRING fields of this type can be used in indexes and in the WHERE condition of a SELECT statement. You cannot attach search helps to components of this type. Short character string: In the Dictionary the number of characters can be specified for this type (1-255). Instead you must reference types of the ABAP Dictionary that are created on the basis of those data types. x xstring string string t c You can not directly reference the built-in data types of the ABAP Dictionary in an ABAP program.__. Time: The length is set to 6 places for this data type. The TIMS format is hhmmss. 75 . Type b and s behave like type i. 0 to 255. Variable byte string: In the Dictionary a length can be specified for this type (at least 256 characters). Note the type b and s can’t be directly specified in ABAP. The template for input and output has the form ‘__.__’.e. As default RAWSTRING for the output length 132 characters are proposed. however they are internally assigned when dictionary types INT1 and INT2 are referenced. but value ranges are more limited i. you should select data type LRAW. You cannot attach search helps to components of this type. You cannot use them in table keys. The length of this data type is set to 2 or 3 places. As STRING default for the output length 132 characters are proposed. Unit: Fields of this type are referenced by fields of type UNIT QUAN. If longer raw fields are required in tables. Variable character string: In the Dictionary a length can be specified for this type (at least 256 characters).

76 . It can be called either by selecting Create  Dictionary Object  ……. To define elementary 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. select Create  Dictionary Object  Data Element from the context menu of package. Creating Elementary Data Type An elementary type is defined by the built-in data type. 1.The ABAP Dictionary Tool can be used to define ABAP Dictionary types. from the context menu of package in Object Navigator or by entering transaction code SE11.

Next confirm the Prompt for transportable Workbench request dialog. Enter the name for data element. On the Field Label tab you can maintain text information for the data element.2. 77 . Select NUMC from data type and enter length of 8. Heading is used as a column header when you output the contents of fields as a list in the Data Browser. Keywords of different lengths (Short. The Further Characteristics tab maintains help (F1) and input help (F4). 4. 3. Click Save button. select Predefined Type on Data Type tab. Medium and Long) for identifying screen fields. 5. The field labels are used to display a Dynpro screen field. Confirm the Maintain field label. 6. The Create Object Directory Entry dialog will pop up save it. This will open the Dictionary: Maintain Data Element window.

The following code shows the usage of our newly created ABAP Dictionary type Z_DIC_TYPE. Now you can see that new entry with the name Dictionary Objects is added to the tree under the Z_MYPACKAGE.7. 9. 78 . To activate choose the Activate function from toolbar. 8.

10. On executing 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. Fields 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. 1. Enter SE11 to open the ABAP Dictionary: Initial Screen. 2. Select object type Domain, enter the name of Domain Z_DOM and choose create button.

79

3. The maintenance screen for domains appears. Enter an explanatory short text in the field Short text. 4. On the Data 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). Note that some data types have a fixed length. For example, the data type CLNT (client) always has 3 places. If you enter an invalid number of places for such a data type, the system corrects this automatically after issuing a warning.

5. If only certain input values are valid for the domain, you can enter them in the Value range tab page as fixed values. If fixed values are defined for a domain, these are used in the input check in screen templates. You can define fixed value intervals either by entering upper and lower limits or by specifying single values. It is only possible to define fixed values for domains of data types CHAR, NUMC, DEC, INT1, INT2 and INT4.

80

6. Save the domain. Confirm the Create Object Directory Entry and Transportable Workbench request. 7. The Domain entry is now visible in Object Navigator tree. Activate it.

8. Next to create the elementary type based to our newly created domain Z_DOM. Select Data Type, enter the name of data type Z_DOMAIN_TYPE and choose create button.

81

9. Select Data element on next dialog and confirm.

10. On Dictionary: Maintain Data Element window, enter the short text and domain Z_DOM and save it.

82

11. Confirm the Create Object Directory Entry, Maintain field label and Transportable Workbench request. 12. The data element entry is now visible in Object Navigator tree. Activate it.

13. The following code shows the usage of our newly created ABAP Dictionary type Z_DOM_TYPE_USAGE

83

14. On executing 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. 1. Select Create  Dictionary Object  Structure from the context menu of package, and enter structure name zstruct_type. 2. In Maintain Structure window enter the short description for zstruct_type.

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

84

interface or generic reference (ANY. choose . By choosing you can switch to the screen for entering references to existing types. CHECK and ACTIVATE. On Entry help/check tab. Length Decimal Places columns and Short Description. The following code shows the usage of our newly created zstruct_type. this reference table must contain a field with the format for the currency key (CUKY) data type or unit of measure (UNIT) data type. DATA or OBJECT) in the Component Type column the RType field is automatically set. If Data Type is QUAN or CURR then in Currency / Quantity tab page. Then press SAVE.If you want to add components by entering the data type and length directly choose this will enable the Data Type. if you want to assign a search help to a structure field that points to a data element. If you enter a class. a blue arrow appears in the Data Type column. you must specify the reference table. this will enable the RType and Component Type columns. 5. 85 . 4. If you enter a reference type already defined in the Dictionary as a reference type.

86 . On executing the above code.6. 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. you can select EditIncludeInsert when creating the structure. In the example below a predefined structure SYST whose elements are the data types of the system fields is included in the zstruct_type. Inserting an Include To include the components of existing structures into new structure at highest hierarchy level. it produces the following output.

4. 3. A line with . 2. Press continue button. A dialog box appears. 87 . the optional group name (with group name.INCLUDE in the Component column and the name of the structure is inserted into Component type column. enter the structure name SYST. Click to Expend Include button to see the fields of SYST structure. Place the cursor under the line in which you want to insert the include and choose EditIncludeInsert.1. you can access the fields in the include together in ABAP program) or a three-place suffix (suffix can be used to avoid name collisions between fields of the include and fields already in the table).

88 .

use the following statement: MOVE source TO destination. To assign the value of a data object source to a variable destination. Nested structures are completely dissolved in this process. Assignment Operation Assignment operation determines how to move the data into the data objects. as follows: MOVE source_struct-<ci> TO destination_struct-<ci>. Or the equivalent statement destination = source. one for each pair of fields with identical names. it is broken down into a set of MOVE statements. One alternative method is to use several MOVE statements but ABAP provides a special statement for this: MOVE-CORRESPONDING source_struct TO destination_struct. The following example shows that the components of a structure are assigned to the components of two other structures that have the same names. The MOVE statement and assignment operator (=) can be used to perform the assignment operation on the data objects. ABAP provides several special types of assignments.Operations in ABAP Here we will look into the basic operations that we can carry out on data objects. Assigning Structures by Components: To assign individual components of a structure to the components of another structure. 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. When it is executed. In addition to the general type of assignment using Move or the assignment operator (=). 89 .

90 .

this holds true for numeric data in data objects of numeric data types whose code can not be used for a direct presentation. formatting is carried out according to type-dependent predefined rules that can also depend on user-specific values or regional settings. WRITE source TO destination format_options. This statement formats the content of an elementary data object source and assigns it to a flat character –like data object. 91 . In particular. Prior to displaying the contents of those data objects. Following table illustrate the different formatting options. If no format_options additions are specified.The above program produces the following output. ABAP provides WRITE TO assignment statement that explicitly carries out this. they must be converted into character-like data that can be output so that the user understands them. destination. Formatted Assignment: The internal representation of data in data objects is usually not suited for a direct output of the values to the user.

If a field contains only zeros. <d> defines the number of digits after the decimal point. data types in ABAP Dictionary can be linked with specific function modules (Conversion Routines or Conversion Exits). Separators as defined in user’s master record. Conversion routines are used for formatting content for output and for converting input into internal formats. No separators. The leading sign is not displayed on the screen. For type C and N fields. The following code demonstrates the use of WRITE TO statement. Format according to currency <c> in table TCURX. Lastly. These routines are automatically executed when you use the WRITE TO statement. Output is right-justified. Separators as defined in user’s master record. Separators as defined in user’s master record.For All Data Types Option LEFT-JUSTIFIED CENTERED RIGHT-JUSTIFIED NO-ZERO For Numeric Fields NO-SIGN DECIMALS <d> EXPONENT <e> ROUND <r> CURRENCY <c> For Date Fields DD/MM/YY MM/DD/YY DD/MM/YYYY MM/DD/YYYY DDMMYY MMDDYY YYMMDD Function Output is left-justified. Type P fields are multiplied by 10**(-r) and then rounded. In type F fields. A conversion routine can be assigned to a domain in the ABAP Dictionary. Output is centered. Separators as defined in user’s master record. No separators. these are replaced by blanks. the exponent is defined in <e>. leading zeros are replaced automatically. 92 . No separators.

93 .The above code produces the following output.

But it must be noted that a conversion requires a substantial amount of extra computing time. All lines of an internal table are deleted while the reference variable points to null reference. If this is detected during the syntax check. This means their data types match in all technical properties. CLEAR data_obj. In this case. It is pointless to allow conversions between data types d and t or between elementary fields and internal tables. In structured types. This means that a conversion rule between the data types is defined in ABAP. no assignment is possible. between which conversion doesn’t make sense. the content of data object is reset to initial value discussed in data types section. 94 . ABAP contains conversion rules between all those types with the exception of types d and t. an exception will be raised.The CLEAR statement reset variables to their type-specific initial value. otherwise. The technical properties of table types are the table category. The structure components are initialized in accordance with their data type. Incompatibility and Inconvertibility: If source and destination data objects are neither compatible nor convertible. a syntax error occurs. the technical properties are defined by the composition of substructures and elementary data types. 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. That is depending on the elementary data type. Convertibility (Type Conversion): The source and destination data objects are not compatible but convertible. the content of source is first converted according to the conversion rule before it is transferred into the target field destination. 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. • • Type Conversions In ABAP. line type and table key. The three cases determine the execution of the assignment operation: • Compatibility: The source and destination data objects are compatible. During copy process the content of source is transferred byte by byte into the target field destination. Following are the conversion rules for different data types: Elementary Data Types There are 10 built-in elementary types. The technical properties of an elementary data types are length and number of decimal places.

target fields of type x are filled with hexadecimal 0 on the right-hand side. the value of the source field is converted into the internal representation of the target field. Byte-Like to Numeric: During the conversion of byte-like data objects to numeric data objects. the content of the source field must represent a number in an appropriate notation (mathematical. If the target field is not long enough. the transferred characters determine the length. the content of the source field must contain values in hexadecimal notation. Then. If necessary. the value is either rounded or truncated. while the scientific notation consists of a mantissa and an exponent. 95 . Numeric to Text-Type: During the conversion of numeric data objects to texttype data objects. the characters are transferred as left-aligned. its internal representation is transferred without further conversion. Byte-Like to Byte-Like: During the conversion between byte-like data objects. target fields of type c are filled with space characters on the right-hand side. or the right-hand side is truncated. The value of the number is converted into the internal representation of the target field. this number is converted into the data types of the target fields. depending on the data type. either in commercial or in scientific notation. In a commercial notion. Each character of the source field determines the contents of a half-byte of the target field. and f.• • • • • • • • • Text-Type to Text-Type: During the conversion between text-type data objects of data type c and string. Numeric to Numeric: During the conversion between numeric data objects. For target fields of the string type. Here you should note that closing spaces are transferred for source fields of the string type. If necessary. commercial or scientific). If necessary the value can be rounded. Text-Type to Numeric: During the conversion of text-type data objects to numeric data objects of data types i. Numeric to Byte-Like: During conversion of numeric to byte-like data objects. the value of the source field is represented in the target field as a character string. the bytes are transferred as left-aligned. the plus/minus sign is placed after the number. not for those of type c. the transferred bytes determine the length. Byte-Like to Text-Type: During the conversion of byte-like data objects to texttype data objects. the final four bytes of the source field are interpreted as an internal representation of a data object of type i. The following example demonstrates the elementary data types conversion. the value of the source field is first converted to i. Text-Type to Byte-Like: During the conversion of text-type data objects to bytelike data objects of data type x and string. For target fields of the xstring type. the values of the bytes of the source field are represented in hexadecimal notation in the target field. p. or the right-hand side is truncated.

96 .

When a plain number is entered. every conversion worked as: When a character is entered the conversion is failed and an exception is caught. 97 .

In nested structures. d TYPE T. the elementary components on the lowest nesting depth are taken into account when forming fragments in nested structures.Structured Data Types There are no conversion rules for structures that contain internal tables or strings (deep structures). Surplus components are either truncated or they are filled with type-specific initial values. A fragment is a grouping of structure components of the same or similar data types. 98 . Note: UFV splits a structure into fragments. Flat structures of different lengths whose initial sections have the same UFV across the length of the shorter structure can be assigned without conversion in the length of shorter structure. The conversion rules between flat incompatible structures state the following: • • Flat structures whose Unicode Fragment Views (UFV) are identical can be assigned without prior conversion. c TYPE D. a(2) TYPE C. BEGIN OF struc. b(4) TYPE N.

For example. i Alignment gaps are bytes that are inserted in front of components so that the required alignment can be attained. If the structure is not completely character-like. The conversion rules between flat structures and elementary fields state the following: • • If the structure is purely character-like. X. Fragment 1: a. The system normally aligns fields and structures automatically when you declare them. C. F. C. and the structure must begin with a character-like fragment that is at least as long as the elementary field. X. The following example demonstrates the structured type conversion.e TYPE f(2) TYPE g(4) TYPE h(8) TYPE i(8) TYPE END OF struc. c. it is treated like a data object of type c during the conversion. the address of a type i field must be divisible by 4 and the address of a type f field by 8. g Fragment 5: Alignment gap between g and h Fragment 6: h. The assignment occurs exclusively between this fragment and the elementary field. b. 99 . Components with alignment requirements must begin at address that can be divided by a specific number. d Fragment 2: Alignment gap between d and e Fragment 3: e Fragment 4: f. the elementary field must be of type c.

In each one.The above code produces the following output. only the result for the first three components is as if they had been 100 . This example defines two different structures. After assignment of struct_1 to struct_2. the first three components have the same data type. struct_1 and struct_2.

Arithmetic Operations In arithmetic operations. the class of the target field must be the predefined empty class OBJECT. Internal tables are convertible if their line types are convertible. the class of the source field must be the predefined empty class OBJECT. Built-in functions are predefined functions with a numeric return value. Built-in functions are further divided into numeric.e numeric functions are overloaded. Reference Types Class and Interface variables are pointers to objects. Numeric functions accept arguments of any type of numeric data i. the class of the source field must implement the interface of the target field. p. decfloat16 and decfloat34 or byte-like (x) and character-like (c. The convertibility of internal tables does not depend on the number of lines. The description functions return properties of their argument 101 .transferred component by component. floating point and description functions. When you assign a class reference to an interface reference. When you assign an interface reference to a class reference. t. n) data objects whose contents can be interpreted as numeric on the basis of conversion rules. If two interface references are incompatible. Numeric data objects are data objects of type i. The conversion rules between reference types state the following: • • • • If the two class references are incompatible. The numeric operands can be numeric data objects or built-in functions. f. d. the interface of the target field must contain the interface of the source field as a component. You cannot convert them into structures or elementary fields. 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 Internal tables can only be converted into other internal tables. Floating point functions accept only arguments of floating point data and returns floating point value. numeric operands are linked to each other via arithmetic operators. 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. All the remaining positions of struct_1 are omitted.

DIV n. asin( x ). sinh( x ). n FROM m. tan( x) cosh( x ). ** n. charlen determines the length of characters in terms of bytes. Operator + * / DIV MOD ** Meaning Addition Subtraction Multiplication Division Integer division Remainder Exponent p p p p p p p = = = = = = = Usage n m m m m m m + m. Exponential function with base e (e=2. The following table provides the list of arithmetic operators. Function Numeric Functions abs( x ) sign( x ) ceil( x ) floor( x ) trunc( x ) frac( x ) Floating Point Functions acos( x ). Square root (only possible for positive numbers). Returns the smallest integer value not smaller than the argument. atan( x ) . Returns the +/.for example. – n. Returns the fraction part of an argument. tanh( x ) exp( x ) log( x ) log10( x ) sqrt( x ) Meaning / Result Returns an absolute value of an argument. Hyperbolic functions. sin( x ).7182818285). Statement ADD n TO SUBTRACT MULTIPLY DIVIDE m m. Returns the integer part of an argument. Logarithm with base 10. cos( x ). The following table summarizes the numeric and floating point built in functions. m BY n. ABAP also provides a self -explanatory statement for four basic arithmetic operations but we won’t elaborate on these statements any further. 102 . / n. BY n. strlen defines the number of characters of data object and lines determine the number of lines in an internal table. MOD n. Trigonometric functions. Natural logarithm with base e. Returns the largest integer value not larger than the argument. ------- The following example shows the usage of arithmetic operators and built-in functions. * n.sign of an argument.

103 .

it is interpreted as “true”. ABAP provides generic relational operators for all data types. ABAP does not contain a Boolean data type to accept these values. Logical Operations A logical operation returns true or false. 104 . In majority of logical operations.The above code produces the following output. The following table summarizes these operators. on the other hand. the contents of two operands are compared with each other by using a relational operator. logical linking and negating operators and specific relational operators for certain data types. The “false” value. is represented by a space character. The missing Boolean data type is replaced with data objects of type c and length 1. If the data object contains an “ X”.

Operands of type c and string are compared lexicographically and by differentiating between uppercase and lowercase letters.Operator Meaning Usage Statement EQ NE LT LE GT GE ----------------------------- Generic Relation Operators = Equal to <> Not equal to < Less than <= Less than or equal to > Greater than >= Greater than or equal to Logical Linking and Negating Operators ( c < n ) AND ( n Combine two logical AND > f ) expression ( c < n ) OR ( n > Combine two logical OR f ) expression Negate the result of NOT NOT ( c < n ) logical expression String Comparison Operators CO 'BD ' CO 'ABCD ' Contains Only CN 'ABC12' CN 'ABCD ' Contains Not only CA 'ABcde' CA 'Bd ' Contains Any NA 'ABAB ' NA 'AB ' contains Not Any CS 'ABcde' CS 'bC ' Contains String NS 'ABcde' NS 'ce ' contains No String CP 'ABcde' CP '*#b*' Contains Pattern NP 'ABcde' NP '*b*' contains No Pattern Bit Sequences Comparison Operators (2nd operand must have type X) O ‘a’ O <x> bits are One Z ‘d’ Z <x> bits are Zero M ‘a’ M <x> bits are Mixed Numeric fields (i. p) are compared with each other with regard to their numeric values. If operands have type d or t and contain a valid date or time. t. string. xstring) are compared on the basis of their byte values. Character-like fields (c. Operands of type n are compared on the basis of the represented numeric values. d. The previous type conversion rules also apply to operands of logical operators with little modifications. Bytelike fields (x. f. the later date or time is greater than the earlier one. If one operand is date field type d or a time field of type t and the other 105 . n) are generally compared with each other from left to right.

ref IS BOUND. while the content of an operand of type xstring is converted to string. to increase the processing speed by arranging logical expressions in such a way that comparisons that often return a ‘”false” are placed at the beginning of an AND sequence. the text field is converted into a string. Field symbols are placeholders for existing data objects. the same rule applies to x and xstring. flag IS INITIAL. which. If one of the operands has a byte-like type and the other operand has a character-like type c or string. Logical Expressions with Predicates ABAP provides the following predicates for logical expressions. Note: ABAP processes logical expressions from the left to right. If two internal tables contain the same number of lines. the date and time fields are also regarded as being character-like. For example. It the system detects that one of the partial expressions is fulfilled or not fulfilled no other comparisons checks are carried out for this partial expression. For example. Incompatible structures can be compared with each other if their Unicode fragment views are identical in the length of the shorter structure. For example. the contents of both operands are converted to data type p. Therefore. Two reference variables are equal when they point to the same object. 106 . must be of type c. It is recommended that you use compatible operands. IS [NOT] BOUND: check whether a reference variable points to an object. IS [NOT] INITIAL: check whether the value of a field is initial. If one of the operands is a text field of type c and the other operand is a text string of type string. If the other operand is character-like. the content of an operand type x is converted to c. number BETWEEN 3 AND 7. string. If one of the operands has data type n and the other has data type c. Two compatible structures are identical if all their components are identical. the system converts date or time field into the numeric type. in turn. For example. [NOT] BETWEEN: check whether the value of a field lies within a particular range.operand is a numeric field. IS [NOT] ASSIGNED: check. they are compared with each other line by line and component by component. whether a memory area is assigned to a field symbol <fs>. x or xstring. A prerequisite for comparing internal tables is that its line type can be compared. Structures can be compared with elementary fields if they contain only character-like and flat and its length matches at least the length of the elementary field. <fs> IS NOT ASSIGNED.

standard which represents a logical condition. GT. option. “same as the column type of the database table. low . The row type of a selection table is a structure that consists of four components: sign.IS [NOT] SUPPLIED: check whether an actual parameter is bound to a formal parameter of a procedure. “I for inclusive and E for exclusive. and high. “the selection criterion is linked. NE. “the selection criterion is linked. The following statement is used to declare a selection table in the program that is linked to the f column of a database table. This predicate can only be used in function modules and methods. Specify the “for a range selection. Specify the “for a range selection. NP to which lower limit to which upper limit 107 . LE. sel_tab-sign = ‘I’. EQ. LT. [NOT] IN selection_tbl: Evaluates the conditions in a selection table. sel_tab-high = 7. “Selection operator. A selection table is an internal table with standard table type. For example. sel_tab-low = 3. or to an internal f field in the program. p1 IS SUPPLIED. “same as the column type of the database table. SELECT-OPTIONS sel_tab FOR f. CP and sel_tab-option = ‘EQ’.

....... . ABAP provides Selection or Branching control structures and looping control structures. The statement block that is located after the first true logical expression is executed. 108 . IF Control Structure The IF control structure is used to execute only one statement block on the basis of logical expression. If none of the logical expressions is true... the statement block after the ELSE statement is executed.......Control Structures Control structures decompose a processing block (method etc.... The concept of ABAP control structures is similar to those of other programming languages... it is recommended to always close the IF control structure with an ELSE statement. Selection / Branching Control Structures ABAP has two types of selection structures i.... statement_block2 .. it may result in no statement block being executed.... starting with the IF statement. IF log_exp1.) into statement blocks and control the program flow within the processing block. statement_blockn ENDIF.e... However. IF control structure and CASE control structure. The logical expressions log_exp are checked from top to bottom... Listing below shows an example of IF control structure. If the ELSE statement is not specified... Following is the general syntax of IF control structure..... [ELSE]... statement_block1 [ELSEIF log_exp2]..

109 .

CASE Selection Structure The CASE selection structure is a multi-way branch control statement. CASE data_obj. statement_block1 WHEN opernad4 [OR operand5] [OR operand6 ……]]. Following is the general syntax of CASE control structure. WHEN operand1 [OR operand2] [OR operand3 ……]].The above code produces the following output. 110 .

.... If the WHEN OTHERS statement is not specified..... it is recommended to always close the CASE control structure with WHEN OTHERS statement..statement_block2 . whether the contents of the operand operand agree with the contents of one of the operands... …... ... WHEN OTHERS. and processes the statement block following the first agreement. 111 .. the statement block after WHEN OTHERS statement is executed.. operand2. starting with the first WHEN statement. However....... The system checks from top to bottom........ Listing below shows an example of CASE control structure... operand1... statement_blockn ENDCASE..... it may result in no statement block being executed... If no agreement is found.

112 .The above code produces the following output.

Code below shows an example of DO loop. including the current loop pass. DO Loop DO loop executes the block of statements several times unconditionally. If n is 0 or negative. If no additions are specified. ABAP provides DO. you must ensure that the loop contains at least one EXIT or STOP statement to avoid endless loops. the system does not process the loop. WHILE. n can be literal or a variable. statement_block ENDDO. 113 . The system field SY-INDEX contains the number of loop passes.Loops / Iterative Control Structures Loops enable to execute a statement block several times. In nested loop you can access the index of an outer loop from within the inner loop by using the auxiliary variable. the statement block is repeated until it reaches a termination statement such as EXIT or STOP. DO [n TIMES]. If you do not use the TIMES option. LOOP AT and SELECT loop. Following is the syntax of DO loop. The TIMES addition restricts the number of loop passes to n.

114 .

The statement block in the loop is repeatedly executed as long as the logical expression log_exp is true. 115 . statement_block ENDWHILE.The above listing produces the following output. or until the loop is left using a statement such as EXIT. Code below shows an example of WHILE loop. Here as well. WHILE Loop WHILE loop allows a block of code to be executed while a specified condition is true. sy-index is set to the current loop index in each pass. WHILE log_exp. Following is the syntax of WHILE loop.

116 .The above listing produces the following output. LOOP AT Loop LOOP AT is special type of loop which can be used to read lines from internal table sequentially. Following is the syntax of LOOP AT loop.

the table line can be evaluated or modified using <fs>.. To limit the rows in the output the conditions given below can be used: .. or until the loop is left using a statement such as EXIT. statement_block ENDLOOP. A field symbol can point to any data object. The LOOP statement sets system field sy-tabix to table index of the current table line for standard tables and sorted tables and to 0 for hashed tables. This addition is only possible. They do not physically reserve space for a field. after every loop pass while the sy-subrc remains unchanged. Instead. • If FROM index1 is specified. but point to its contents. There are four alternatives to influence the output result as: .. The data object to which a field symbol points is assigned to it after it has been declared in the program. the data reference variable dref points to the table line the memory after the statement. Instead. If you specify INTO wa (Work area). • • • • Note: Field symbol (fs) is placeholder or symbolic name for other fields. no values will be transported. the field symbol is bound to the table line in memory after the assignment. [FROM index1] [TO index2] [WHERE log_exp].. {INTO wa} | {ASSIGNING <fs>} | {REFERENCE INTO dref} | {TRANSPORTING NO FIELDS} . To restrict the number of lines use the conditions addition. The table line can be evaluated or modified using dref->… If you specify TRNASPORTING NO FIELDS. If you specify ASSIGNING <fs> (Field Symbol). lines starting from table index index1 will be accepted. If you specify REFERENC INTO dref.. if the addition WHERE is used simultaneously in the conditions. no values will be transported either. For index1 data object of type i is expected.LOOP AT internal_tab result [conditions]. The data type of the data object must be compatible with the line type of the internal table. The output result determines when and where the line contents are read. You must assign a field to each field symbol before you can address the latter in programs. the contents of the line are transported to data object wa. If value of index1 is 117 . you only fill the corresponding system fields.. Field symbols are similar to dereferenced pointers in C. The statement block between LOOP and ENDLOOP is executed once for each line. The loop continues to run until all the table lines that meet condition have been read or. In turn.

If value of index2 is smaller or equal to 0. the loop is not passed through. then it will be set to 1. lines after table index index2 will be accepted. Code below shows an example of LOOP AT loop. If index2 is smaller than index1 then the loop is not passed as well. 118 . TO index2 is only possible with standard and sorted tables.• • smaller or equal to 0. If the value is larger than the number of table rows. WHERE log_exp is possible with all table types. First operand of any comparison will be component of an internal table. If the value is larger than the number of table rows. FROM index1 is only possible with standard and sorted tables. For index2 data object of type i is expected. then the loop will not be passed. If TO index2 is specified. If WHERE log_exp is specified. the value will be set to the number of rows. lines fulfilling the log_exp will be accepted.

119 .

. SELECT result FROM dbtab|dbview INTO [CORRESPONDING FIELDS OF] work_area|(dobj1. The conditions addition restricts the number of lines.The above listing produces the following output. The result defines whether the resulting set consists of multiple rows (table-like structure) or a single row (flat structure). statement_block ENDSELECT. SELECT Loop The SELECT loop reads several entries of a database table in succession.dobj2. Following is the syntax of SELECT loop. 120 . It specifies the columns to be read and defines their names in the resulting set...)]| INTO|APPENDING [CORRESPONDING FIELDS OF] TABLE itab WHERE conditions].

We can end the loop using the statement such as EXIT. If the last row was assigned or if the result set is empty. sy-dbcnt is set to 0. 121 . The SELECT statement sets sy-subrc to 0 for every pass by value to an ABAP data object and to 4 if the result set is empty. The following listing shows an example of SELECT loop. the SELECT statement sets sy-dbcnt to the number of rows that were transferred. the SELECT statement assigns a row to the data objects specified in INTO addition. then SELECT branches to ENDSELECT. After every value that is transferred to an ABAP data object. If the result set is empty.For every loop pass.

122 .

the following out put is produced. 123 .After selecting “New York” on the selection screen.

Secondly.that is. 124 . that is. the angle brackets are part of the syntax. there is no difference in ABAP whether you reference the field symbol or the field itself. The TYPE addition allows you to specify the type of a field symbol.Field Symbols Field symbols are placeholders or symbolic names for other fields. They identify field symbols in the program code. All operations programmed with field symbols are applied to the field assigned to it. A field symbol can point to any data object. After successful assignment. Field symbols allow working generically with data objects. The data object to which a field symbol points is assigned to ( ASSIGN) it after it has been declared in the program. it does not reference a memory area. but point to its contents. They do not physically reserve space for a field. After its declaration. a field symbol is initial . When you assign a data object. For field symbols. the field symbol inherits its technical attributes. The FIELD-SYMBOLS statement is used to declare the field symbols. If you do not specify any additions. Field symbols are similar to dereferenced pointers in C (*ptr). we can use field symbols for the casting of data objects. The following listing demonstrates the field symbols. The data type of the assigned data object becomes the actual data type of the field symbol. Field symbols can also be compared to a data reference variable that is dereferenced with ->*. we can program operations without knowing the data objects with which the program will actually work at runtime. the field symbol <FS> can have data objects of any type assigned to it. We can declare field symbol as: FIELD-SYMBOLS <FS> [TYPE type|LIKE dobj].

The above code produces the following code. 125 .

Static Assignment and Subfield Addressing If the name of the data object that is being assigned to the field symbol is already known when the program is created it is referred as static assignment. During static assignment not only we can assign entire data objects to a field symbol. but also we can assign subfields of byte or character type data objects which we specify using the offset and length specifications. After executing the above code the following out put is produced. 126 . Listing below demonstrate the use of subfield addressing. The syntax is: ASSIGN dobj[+offset][(length)] TO <fs>.

As a result of using the above statement. sy-subrc is set to 0. Here both the name of the class and the name of the attribute are given in the character type fields attr_name and cls_name. In the example in listing below in main method we dynamically access the attribute attr of the class lcl_cls. if no data object with the right name is found there is no assignment to the field symbol and sy-subrc is set to the value 4. After dynamic assignment. If the assignment is successful. the data object whose name is contained in the name field in brackets is assigned to the field symbol <fs>.Dynamic Assignment If the name of the data object that we want to assign to a field symbol is not known until runtime. we can use the following variant of the ASSIGN statement: ASSIGN (name) TO <fs>. we must always check sy-subrc before we access the field symbol. 127 .

Component Assignment To dynamically address the components of structure. use the following variant of ASSIGN statement.The above code produces the following output. 128 .

this specifies the number of the component.ASSIGN COMPONENT comp OF STRUCTURE struct TO <fs>. 129 . After the loop the component col3 of struct is specified by its name and assigned to <f3>. Note. expressions such as <f1>-col1 are syntactically incorrect. In the DO loop the components of struct are specified by their numbers and assigned one by one to <f3>. If comp is a data object of the type c or string. <f2> points to the field comp. In the example below the field symbol <f1> points to the structure struct. If the comp has a different type and if the content is a number. its content is interpreted as the name of the component.

The above code produces the following output. 130 .

Following is the syntax for increment assignment. Without specifying RANGE. A memory area is assigned to the field symbol that is exactly as long as the data object dobj and is offset inc times this length of dobj. range is a data object that comprises the subareas. 131 . starting from the two-character component comp1. ASSIGN dobj INCREMENT inc TO <fs> [RANGE range]. we can only access the memory area within dobj itself. Here. With RANGE. The example in listing below shows how within a character-type structure txt. we can specify the area within which an assignment is possible. subfields of the component comp2 are accessed that are just as long.Increment Assignment It is possible within a structure to incrementally access subfields of the structure.

132 .The above code produces the following output.

The addition CASTING allows to assign data objects to field symbols whose type is not compatible with the typing of the field symbol. Without explicit casting with the addition CASTING. The listing given below the content of the character-type system field sy-datum is interpreted as a structure. the following form of the ASSIGN statement can be used: ASSIGN dobj TO <fs> CASTING. a cast can be performed on any data types. p or x (Implicit Type Specification). This means that the assigned memory area can be handled assuming a particular type. the field symbol always takes over the type of the specified data object. The assigned memory area is cast to the type of the field symbol. If the field symbol is typed either fully or with one of the built-in generic ABAP types c. n. 133 .Casting Type in Assignment When we assign data objects to field symbols. which must then be compatible with the typing of the field symbol.

we can use the following form of ASSIGN statement. which allows an entirely dynamic casting. The TYPE HANDLE addition specify a reference to a type object of the Run Time Type Services (RTTS). It can preserve or specialize the generic typing but it can not overwrite an already known technical property of the field symbol. this then specifies the data type dynamically. rather than completely (Explicit Type Specification). Behind TYPE. Listing below shows an example in which the numerical content of a text field is interpreted once as a date and once as a number value. where the data type of the field symbol determines the conversion rule. The explicit type specification is forbidden for a fully typed field symbol. The specified data type must be compatible with the generic typing of the field symbol. If the field symbol is typed generically. ASSIGN f TO <fs> CASTING TYPE typ|(nemae) | LIKE dobj | TYPE HANDLE handler. 134 . because such a type object can be created through the definition of a new data type. we can specify a name of a data object enclosed in round brackets. The interpretation occurs when the field symbol is assigned to an integer field.The above coding produces the following output.

135 .The above coding produces the following output.

the CLEAR <fs> statement doesn’t mean that the field symbol will be initialized.Note: We can use the <fs> IS ASSIGNED to check whether a data object is assigned to a field symbol. but rather the memory area that was assigned to the field symbol. 136 . While we can us the UNASSIGN <fs> statement to ensure that no more data objects are assigned to a field symbol. The expression will be true if the field symbol <fs> points to a data object. On the other hand.

Internal Tables
The data objects of table types are internal tables. Internal tables allow storing a variable amount of data of a fixed structure in the memory and enable to efficiently use this data. In ABAP, internal tables fulfill the function of arrays. We can use internal tables whenever we want to process a dataset with a fixed structure within a program. A particularly important use for internal tables is for storing and formatting data from a database table within a program. We can use internal tables to perform table calculations on subsets of database tables. For example, you can read a certain part of a database table into an internal table. From the internal table, you can then calculate totals or generate a ranked list. Like all elements in the ABAP type concept, internal tables can exist both as data types and as data objects. Internal tables are implicitly managed by the runtime environment. ABAP contains a set of special, highly optimized statements that we can use when working with internal tables. The following syntax can be used to declare the internal tables. DATA tab_name TYPE|LIKE STANDARD|SORTED|HASHED TABLE OF data_type|data_object WITH [NON-]UNIQUE KEY col1… coln [INITIAL SIZE n]. TYPES tab_name TYPE STANDARD|SORTED|HASHED TABLE OF data_type WITH [NON-]UNIQUE KEY col1…coln [INITIAL SIZE n]. Internal tables are stored in individual blocks in the memory. The [ INITIAL SIZE n] addition enables to specify initially required number of table lines n. It is recommended that specify initial memory requirement only when the number of entries in table is already known. 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: Row/Line Type, Table Category and Table Key.

Row/Line Type
The line type of an internal table can be any data type. The data type of an internal table is normally a structure. Each component of the structure is a column in the internal table. However, the line type may also be elementary or another internal table.

Table Category

137

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 doesn’t affect an access to entire table, as it occurs for instance in assignment and comparisons. There are three categories of internal tables.

STANDARD Table: is managed internally by a table index. Access is possible via table index or table key. With a key access, the response time is directly dependent on the number of table entries. The key of a standard table is always non-unique. This table category is suited best whenever the individual entries can be accessed using the index. A table index numbers the lines from 1 to the existing number of lines. The system field sy-tabix is always filled with the index of the line that is addressed. SORTED Table: is managed internally by means of a table index, too. They are always sorted by the table key and can be accessed via the table index or the table key. With a key access, the response time is logarithmically dependent on the number of table entries, because the table is accessed via a binary search. The key of sorted tables can be unique or non-unique. This table category is suited whenever the table must already be sorted when it is filled. The system field sytabix is always filled with the index of the line that is addressed. HASHED Table: is managed internally by a hash algorithm. Hashed tables can be accessed only via the table key. The response time is constant, independent of the number of table entries. The key of hashed tables is always unique. This table category is suited whenever the key accesses represent the central operation on the table entries.

Which 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 program? • Standard tables are the most appropriate type if you are going to address the individual table entries using the index. Index access is the quickest possible access. You should fill a standard table by appending lines (APPEND statement), and read, modify and delete entries by specifying the index (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 key access, standard tables are particularly useful if you can fill and process the table in separate steps. For example, you could fill the table by appending entries, and then sort it. If you use the binary search option with key access, the response time is logarithmically proportional to the number of table entries. We should avoid using large standard tables of more than 100 lines because of the linear search process. Sorted tables are useful if both a fast key access and an index access are necessary and if the lines should already be sorted during the filling of the table. You fill sorted tables using the INSERT statement. Entries are inserted according to the sort sequence defined through the table key. Any illegal entries are recognized as soon as you try to add them to the table. The response time for key access is logarithmically proportional to the number of table entries, since the system 138

always uses a binary search. Sorted tables are particularly useful for partially sequential processing in a LOOP if you specify the beginning of the table key in the WHERE condition. Hashed tables are the most appropriate type for any table where the main operation is key access. You cannot access a hashed table using its index. The response time for key access remains constant, regardless of the number of table entries. Like database tables, hashed tables always have a unique key. Hashed 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.

Table Key
The table key identifies table rows. There are two kinds of key for internal tables - the standard key or default key and a user-defined key. The key should be UNIQUE or NONUNIQUE. For all table categories, we can specify one of the following key definitions during the declaration: • • • If a table has a structured line type, its default key consists of all of its nonnumerical (i,f,p) columns/components that are not references or themselves internal tables. If a table has an elementary line type, the default key is the entire line (pseudocomponent table_line, the entire line of the internal table is interpreted as the only component.). If a table has an internal table line type, the default key is empty.

The user-defined key can contain any columns/components of the internal table that are not references or themselves internal tables. Internal tables with a user-defined key are called key tables. When you define the key, the sequence of the key fields is significant. You should remember this, for example, if you intend to sort the table according to the key.

Working with Internal Tables
When working with internal tables, we must distinguish between the access to single lines and the access to the entire table.

Processing Single Lines
When working with single table lines, we must distinguish between the operators that are possible for all table types, and those that are only possible with index tables. Index tables (standard and sorted tables) have an internal index, making linear access possible. Hashed tables have no linear index. Consequently, only key access is possible. The operations that are permitted for all table types do not use indexes.

139

The statements used to access lines of any type of table differ from those used to access index tables mainly through the TABLE addition following the corresponding keyword. For example, you would use MODIFY to change lines in index tables, but MODIFY TABLE to change lines in any type of table. There are three ways to access a single table entry: Access Using a Work Area, Access Using Field Symbols and Access via Data References. Access Using a Work Area: When we access individual table entries using a work area, we are not working directly with the data in the table. Instead, we work with another data object as a work area. The work area is an interface to the entries in the internal table, and must be convertible into the line type of the internal table. When we read data from a table record, the data you are reading overwrites the current contents of the work area. You can then use this data in the program. When you write data to the internal table, this must first be placed in the work area. The system then transfers it from the work area to the appropriate table entry. Access Using Field Symbols: When we access an internal table using a field symbol , we do not need to copy the data into a work area. We 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. Once you have assigned the entry to the field symbol, working with the field symbol has exactly the same effect as accessing the corresponding line directly. Access via Data References: When we access an internal table using a data reference, we do not need to copy the data into a work area. We 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. Once we have assigned the entry to the field symbol, working with the dereferenced data reference has exactly the same effect as accessing the corresponding line directly. Inserting Rows To fill an internal table with lines, we must us the INSERT statement as: INSERT {wa|INITIAL LINE|LINES OF tab_name [FROM idx1] [TO idx2]} INTO {TABLE itab_name | itab_name [index idx]} [ASSIGNING <fs> [CASTING] | REFERENCE INTO dref]. The wa represents the work area, a new line is generated and filled with the contents of wa. wa must be compatible with the line type of the internal table when you insert the lines or work area using the table key. The INITIAL LINE statement represents a new line in which each component contains the type-specific initial value. The LINES OF tab_name [from idex1] [TO idx2] specify the internal table from where the lines are inserted one after another according to the same rules as for the insertion of a work area. The line types of both itab_name and tab_name must be compatible. If

140

tab_name is an index table, you can specify FROM idx1 and TO idx2 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 key. If we use the addition INDEX, the table index is used for the specification. The INDEX option can only be used for index tables. • • • For standard tables, each new line is appended as the last line in the internal table regardless of the table key and the table index of the following lines is increased by one. For sorted tables, each new line is inserted into the sort order of the internal table according to its key values. If the internal table does not have a unique key, duplicate entries are inserted before the existing line. For hashed tables, each new line is inserted into the internal table by the hash administration according to its key values.

The additions ASSIGNING <fs> [CASTING] | REFERENCE INTO dref can only be used when inserting single lines. If they are inserted successfully, the inserted line is assigned to a field symbol <fs> or a reference is set to the inserted line in the reference variable. On successful execution the system field sy-subrc is set to 0 or to 4 on failure. Example below demonstrates the use of the INSERT statement.
REPORT z_itb_insert.

CLASS example DEFINITION. PUBLIC SECTION. CLASS-METHODS main. ENDCLASS. CLASS example IMPLEMENTATION. METHOD main. "declare line types DATA: int TYPE i, dref TYPE REF TO i. "declare internal tables DATA: int_tab LIKE STANDARD TABLE OF int, ref_tab LIKE HASHED TABLE OF dref WITH UNIQUE KEY table_line. DO 5 TIMES. "insert table index in standard table "and set the reference of inserted line "into dref reference variable INSERT sy-index INTO int_tab INDEX 1 REFERENCE INTO dref.

141

"now insert the references to lines "in hashed table using the table key INSERT dref INTO TABLE ref_tab. ENDDO. "print out the contents of standard table WRITE 'Contnets of Standard Table'. "output blank line SKIP. LOOP AT int_tab INTO int. WRITE: int, space. ENDLOOP. SKIP 2. "print out the contents of hashed table "using derefernce operator WRITE 'Contnets of Hashed Table'. SKIP. LOOP AT ref_tab INTO dref. WRITE: dref->*, space. ENDLOOP. ENDMETHOD. ENDCLASS. START-OF-SELECTION. example=>main( ).

The above coding produces the following output.

In the following example a structure is used as a line type.
REPORT z_itb_insert02.

CLASS example DEFINITION. PUBLIC SECTION. CLASS-METHODS main. ENDCLASS.

142

line-name = 'Ajmal'. line-name = 'Asghar'.00'. DATA itab LIKE SORTED TABLE OF line WITH UNIQUE KEY id. 'Name'. line-weight.00'. ENDLOOP. id TYPE name TYPE age TYPE weight TYPE END OF line. i. line-weight = '76. WRITE: ' ' ' ID'. INSERT line INTO TABLE itab. p DECIMALS 2.00'. INSERT line INTO TABLE itab. line-age = 10. example=>main( ). line-weight = '67. line-age = 18. line-id = 4.23'.00'. i. line-age. line-age = 20. line-age = 16. 143 . line-weight = '80. line-id = 2. line-name. c LENGTH 10. Weight'. line-weight = '82. line-name = 'Hamad'. METHOD main. ENDMETHOD. INSERT line INTO TABLE itab. INSERT line INTO TABLE itab. WRITE: / line-id. line-name = 'Shumila'. SKIP 1. line-age = 15. line-id = 1. ENDCLASS. line-name = 'Salim'. INSERT line INTO TABLE itab. line-id = 5. line-weight = '34.CLASS example IMPLEMENTATION. line-id = 3. DATA: BEGIN OF line. START-OF-SELECTION. Age'. LOOP AT itab INTO line.

INSERT LINES OF itab INTO TABLE jtab. WRITE: / '---------------------------------'. DATA itab LIKE STANDARD TABLE OF row. PUBLIC SECTION. The example below creates two internal tables with the same line type but different table types. ' '. row-col2 = 'BCS'. INSERT row INTO TABLE itab. Then. DATA jtab LIKE SORTED TABLE OF row WITH NON-UNIQUE KEY col1 col2. METHOD main. CLASS example IMPLEMENTATION. LOOP AT jtab INTO row. Each is filled with three lines. DATA: BEGIN OF row. REPORT z_itb_insert03. col1 TYPE c LENGTH 10. row-col2 = 'MS-IT'. CLASS-METHODS main. row-col1 = 'Ajmal'. row-col1 = 'Asghar'. row-col2 = 'FA'. col2 TYPE c LENGTH 10. INSERT row INTO TABLE itab. END OF row. CLASS example DEFINITION.The above listing produces the following output. WRITE: / sy-tabix. ' Col2'. ' Col1'. WRITE: 'Table Index'. row-col1 = 'Saleem'. ENDCLASS. INSERT row INTO TABLE itab. 144 . itab is sorted into sorted table jtab.

example=>main( ). Inserting Aggregated Rows The COLLECT statement is specifically used for totaling numeric values that belong to unique keys. The statement inserts the contents of a work area wa either as single row into an internal table itab or adds the values of its numeric components to the corresponding values of existing rows with the same key. f). the COLLECT statement does not append a new line. its use for standard tables is error-prone and obsolete. The wa must be compatible with the row type of itab and all components that are not part of the table key must have a numeric data type ( i. In contrast. START-OF-SELECTION.row-col1. If an entry with the same key already exists. ENDCLASS. CLASS-METHODS main. The example below demonstrates COLLECT statement. the system checks whether there is already a table entry that matches the key. The above listing produces the following output. ENDCLASS. If there is no corresponding entry already in the table. Following is the syntax of the COLLECT statement. row-col2. but adds the contents of the numeric fields in the work area to the contents of the numeric fields in the existing entry. ENDLOOP. CLASS example DEFINITION. p. COLLECT wa INTO itab [ASSIGNING <fs> [CASTING] | REFERENCE INTO dref]. the COLLECT statement has the same effect as inserting the new line. PUBLIC SECTION. When the line is inserted. ENDMETHOD. REPORT z_itb_collect01. The COLLECT statement is primarily used for hashed tables. 145 .

line-col2. The example fills a sorted table. line-col3 = 5. the first line of itab is modified. DATA: BEGIN OF line. METHOD main. COLLECT line INTO itab. col1 TYPE c LENGTH 3. WRITE / '------------------------------'. The following diagram shows the three steps: 146 . LOOP AT itab INTO line. col2 TYPE n LENGTH 2.CLASS example IMPLEMENTATION. sy-tabix. DATA itab LIKE SORTED TABLE OF line WITH NON-UNIQUE KEY col1 col2. COLLECT line INTO itab. line-col2 = '34'. col3 TYPE i. COLLECT line INTO itab. line-col3. END OF line. line-col1 = 'def'. line-col3 = 7. WRITE: / line-col1. ENDMETHOD. example=>main( ). START-OF-SELECTION. line-col2 = '12'. sy-tabix. line-col1 = 'abc'. sy-tabix. line-col1 = 'abc'. WRITE: 'sy-tabix: '. ENDCLASS. line-col2 = '12'. WRITE: / 'sy-tabix: '. The first two COLLECT statements work like normal insertion statements. ENDLOOP. WRITE: / 'sy-tabix: '. line-col3 = 3. In the third COLLECT statement.

LOOP AT seats_tab INTO seats. WRITE: 'Airline Code'. ' Occupied Seats in Economy Class'. seatsocc TYPE sflight-seatsocc. ENDSELECT. connid TYPE sflight-connid.In the example below compressed insertion of data from the database table sflight into the internal table seats_tab. SELECT carrid connid seatsocc FROM sflight INTO seats. DATA: BEGIN OF seats. END OF seats. CLASS example IMPLEMENTATION. DATA seats_tab LIKE HASHED TABLE OF seats WITH UNIQUE KEY carrid connid. PUBLIC SECTION. REPORT z_itb_collect02. METHOD main. COLLECT seats INTO seats_tab. carrid TYPE sflight-carrid. The rows in which the key components carrid and connid are identical are compressed by adding the number of occupied seats to numeric component seatsocc. SKIP.'. ENDCLASS. CLASS example DEFINITION. ' Fligt Connection No. CLASS-METHODS main. 147 .

'. ' seats-seatsocc. APPEND {wa|INITIAL LINE|LINES OF tab_name [FROM idx1] [TO idx2]} 148 . Following is the syntax of APPEND statement. ' seats-connid.WRITE: / seats-carrid. START-OF-SELECTION. Appending Rows The APPEND statement appends one or more rows to an internal index table (standard and sorted tables) as last row(s). example=>main( ). ENDCLASS. ENDLOOP. ENDMETHOD. The above code produces the following output. '.

line1-col2 = '3'. In standard tables. line2-field1 = 'ABC'. an untreatable exception is triggered. The SORTED BY addition is used to sort the table in a specified way. line1-col2 = '2'. DATA tab2 LIKE TABLE OF line2. This statement provides a convenient way to fill standard tables with lines. line1-col3 = 10. REPORT z_itb_append01. rows are appended only if they correspond to the sort sequence and do not create duplicate entries with unique table key. line2-field2 = tab1. END OF line2. APPEND line2 TO tab2. col1 TYPE c LENGTH 3. col3 TYPE i. CLASS example IMPLEMENTATION. rows are appended directly and without checking the content of the internal table while in sorted tables. METHOD main. PUBLIC SECTION. line1-col1 = 'ghi'. line1-col1 = 'abc'. Otherwise. CLASS example DEFINITION. No rows can be appended in hashed tables. 149 . line1-col2 = '1'. DATA: BEGIN OF line1. the memory space "required for the table is freed up to the initial memory "size INITIAL SIZE REFRESH tab1. where wa must be compatible to the row type of the table. field2 LIKE tab1. It is allowed only if you specify a workarea wa and if you use a standard table. The APPEND statement sets sy-tabix to the table index of the last appended row. col2 TYPE n LENGTH 2. field1 TYPE c LENGTH 1. ENDCLASS. CLASS-METHODS main. DATA: BEGIN OF line2. line1-col3 = 12. APPEND line1 TO tab1. END OF line1.TO itab [SORTED BY comp] [ASSIGNING <fs> [CASTING]|REFERENCE INTO dref]. line1-col3 = 11. DATA tab1 LIKE TABLE OF line1. line1-col1 = 'def'. APPEND line1 TO tab1. "Deletes all rows of the internal table.

SKIP.APPEND line1 TO tab1. line2 is filled and appended to tab2. line2-field2 = tab1. line1-col1. WRITE: ENDLOOP. ENDCLASS. APPEND line2 TO tab2. The example above creates two internal tables tab1 and tab2. 150 . example=>main( ). After clearing tab1 with the REFRESH statement. Following is the output of the above example. line1-col3 = 13. line1-col1 = 'jkl'. ENDLOOP. line2-field1 = 'DEF'. Then. line1 is filled and appended to tab1. ENDMETHOD. START-OF-SELECTION. "note the use of nested loop LOOP AT tab2 INTO line2. WRITE: / 'tab2-field1 = '. line1-col2 = '4'. tab2 has a deep structure because the second component of line2 has the data type of internal table tab1. line1-col3. the same procedure is repeated. / ' '. line1-col2. line2-field1. WRITE / 'tab2-field2 = '. APPEND line1 TO tab1. LOOP AT line2-field2 INTO line1.

col1 TYPE c LENGTH 1.This example below creates two internal tables of the same type. ENDLOOP. DO 3 TIMES. APPEND LINES OF jtab FROM 2 TO 3 TO itab. APPEND line TO itab. START-OF-SELECTION. the last two lines of jtab are appended to itab. line-col1 = sy-index. and jtab with a list of cube numbers. CLASS-METHODS main. WRITE: 'Index'. REPORT z_itb_append02. CLASS example IMPLEMENTATION. line-col1 = sy-index. ENDMETHOD. Then. DATA: itab LIKE TABLE OF line. In the DO loop. itab and jtab. example=>main( ). ENDCLASS. ENDDO. ' Sqr/Cube'. METHOD main. ENDCLASS. line-col2 = sy-index ** 2. WRITE: / line-col1. line-col2. APPEND line TO jtab. LOOP AT itab INTO line. itab is filled with a list of square numbers. END OF line. PUBLIC SECTION. CLASS example DEFINITION. The above listing produces the following output. line-col2 = sy-index ** 3. jtab LIKE itab. 151 . DATA: BEGIN OF line. col2 TYPE i.

CLASS example IMPLEMENTATION. ' Col3'. line-col3 = 57. METHOD main. col3 TYPE i. The line with the smallest value for the field COL2 is deleted from the table. line-col2 = 23. line-col1 = 12. since the number of lines that can be appended is fixed to 2 through the INITIAL SIZE addition. line-col3 = 56. REPORT z_itb_append03. APPEND line TO itab SORTED BY col2. APPEND line TO itab SORTED BY col2. line-col3 = 55. APPEND line TO itab SORTED BY col2. line-col2 = 22. ENDCLASS. DATA itab LIKE TABLE OF line INITIAL SIZE 2. CLASS example DEFINITION. Col1'. col1 TYPE i. line-col1 = 11. col2 TYPE i. DATA: BEGIN OF line. CLASS-METHODS main. Col2'. 152 . END OF line.The program below inserts three lines into the internal table itab using the APPEND statement and the SORTED BY addition. LOOP AT itab INTO line. line-col2 = 24. line-col1 = 13. PUBLIC SECTION. WRITE: ' ' SKIP.

ENDLOOP. Reading Rows To read the contents of individual rows from an internal table. Here the standard table is searched using linear search. The values of the search key can be specified either implicitly in a work area wa after FROM. START-OF-SELECTION. The syntax for READ statement is as follows: READ TABLE itab {FROM wa|WITH TABLE KEY comp1=dobj1 … compn=dobjn}| {WITH KEY comp1=dobj1 … compn=dobjn [BINARY SEARCH]}| {INDEX idx} INTO {wa[COMPARING comp1 … compn|TRANSPORTING comp1 … compn]|ASSIGNING <fs> [CASTING]|REFERENCE INTO dref}| {TRANSPORTING NO FIELDS}. If the addition BINARY SEARCH is specified. or by explicitly listing the components of the table key after TABLE KEY. It can be specified for sorted tables. example=>main( ). The dobj data object in TABLE KEY must be compatible with the line type of the internal table. 153 . ENDMETHOD. Following is the output of the above program. line-col2. sorted table is searched using binary search and hashed tables are searched based on hash algorithm. line-col3. the search is binary instead of linear for standard table. ENDCLASS.WRITE: / line-col1. The work area wa must be a data object that is compatible with the line type of the internal table. If we don’t use the TABLE addition before KEY. we can use the READ TABLE statement. we can use any component comp of the internal table as search keys (free key).

"sets the line components to initail values 154 . because itab is an index table. METHOD main. The program below fills a sorted table with a list of square numbers. If the addition TRANSPORTING is specified. COMPARING must be specified before TRANSPORTING. In standard tables and sorted tables.but has no effect on sorted tables. a data object of type i is expected. the statement READ TABLE only checks whether the line that is being searched for exists. PUBLIC SECTION. END OF line. The addition COMPARING compares the specified components comp1 … compn in a found line before they are transported with the corresponding components of the work area. only the specified components comp1 … compn in the found line are assigned to the corresponding components of the work area. col1 TYPE i. DATA itab LIKE SORTED TABLE OF line WITH UNIQUE KEY col1. and SY-TABIX is 3. CLASS example IMPLEMENTATION. For idx. The content of the found line is assigned to the work area wa. ENDCLASS. line-col1 = sy-index. ENDDO. line-col2 = sy-index ** 2. no line is read and sy-subrc is set to 4. and fills the system field sy-subrc and sy-tabix. If the value of idx is smaller than or equal to 0. The READ statement reads the line of the table in which the key field col1 has the same value as in the work area and copies it into the work area. INSERT line INTO TABLE itab. DO 4 TIMES. or greater than the number of rows in the table. The addition BINARY SEARCH is not permitted for hashed tables. The system can then no longer access the content of the found fields. DATA: BEGIN OF line. When the addition TRANSPORTING NO FIELDS is used. Only the contents of col2 are copied into the work area LINE. REPORT z_itb_read01. CLASS-METHODS main. SY-SUBRC is zero. col2 TYPE i. CLASS example DEFINITION. the table index of the row to be read can be specified explicitly in idx.

START-OF-SELECTION. line-col2.CLEAR line. LOOP AT itab INTO line. example=>main( ). ENDMETHOD. CLEAR line. REPORT z_itb_read02. WRITE: / line-col1. READ TABLE itab WITH TABLE KEY col1 = 3 INTO line TRANSPORTING col2. SKIP. PUBLIC SECTION. 155 . WRITE /'---------------------------'. WRITE: ' line-col1'. The example below reads the first ten lines of the internal table sflight_tab using the index. WRITE /'---------------------------'. ' line-col2'. The above program produces the following output. WRITE: ' line-col1'. ENDCLASS. WRITE: / line-col1. line-col2. ' line-col2'. CLASS example DEFINITION. SKIP. ENDLOOP. CLASS-METHODS main. WRITE 'Value read with key = 3'.

sflight_wa-fldate. START-OF-SELECTION. IF sy-subrc <> 0. ENDCLASS. 156 . Following is the output. example=>main( ). ENDDO. WRITE: / '-------------------------------------------------------------------------------'. sflight_wa-currency. ' Currency'. "sflight is a flight details table in "abap dictionary DATA sflight_tab TYPE SORTED TABLE OF sflight WITH NON-UNIQUE KEY seatsocc. "declare line work area. ' '. WRITE: 'AirlineID'. READ TABLE sflight_tab INDEX sy-index INTO sflight_wa. EXIT. ELSE. CLASS example IMPLEMENTATION. WRITE: / sflight_wa-carrid. sflight_wa-price. DO 10 TIMES. ' Flight Date'. ' Type'. ' Con No'.' Fare'. ENDIF.ENDCLASS. '. METHOD main. SELECT * FROM sflight INTO TABLE sflight_tab WHERE carrid = 'LH' AND connid = '400'. ' sflight_wa-connid. sflight_wa-planetype. ' '. ENDMETHOD. ' '. that will hold "one row at a time DATA sflight_wa LIKE LINE OF sflight_tab.

CLASS example DEFINITION.In the third example the READ statement uses a WHILE loop to read all lines of the table sflight_tab one after the other using the table index in the work area sflight_wa. ' Flight Date'. Using the COMPARING addition. 157 . ' Occupied Seats'. ENDCLASS. sflight_wa-seatsocc = 0. WRITE: / '-------------------------------------------------------'. DATA subrc TYPE sy-subrc. DATA sflight_tab TYPE SORTED TABLE OF sflight WITH UNIQUE KEY carrid connid fldate. WHILE subrc = 0. CLASS example IMPLEMENTATION. METHOD main. REPORT z_itb_read03. ' Con No'. all flights are selected in which no seats have yet been booked. subrc = sy-subrc. PUBLIC SECTION. SELECT * FROM sflight INTO TABLE sflight_tab WHERE carrid = 'LH'. WRITE: 'AirlineID'. DATA sflight_wa LIKE LINE OF sflight_tab. CLASS-METHODS main.

sflight_wa-connid. WRITE: / sflight_wa-carrid. example=>main( ). ' '. WHEN 4 OR 8. CASE sy-subrc. sflight_wa-seatsocc COLOR = 6. "COLOR addition change the background color of "output of the current WRITE statement WRITE: / sflight_wa-carrid. ' '. sflight_wa-connid. subrc = 0. ' '. subrc = sy-subrc. ENDWHILE. WHEN 0. WHEN 2. EXIT. ENDMETHOD. sflight_wa-seatsocc COLOR = 5. 158 . sflight_wa-fldate. ' '.READ TABLE sflight_tab INDEX sy-index INTO sflight_wa COMPARING seatsocc TRANSPORTING carrid connid fldate seatsocc. ' '. ' '. ENDCLASS. START-OF-SELECTION. ENDCASE. Following is the screen shot of the output. sflight_wa-fldate.

CLASS-METHODS main. REPORT z_itb_read04. PUBLIC SECTION. METHOD main. 159 . This also changes the corresponding table field. The program then assigns the value 100 to component col2 of <FS>. The READ statement reads the line of the table in which the key field col1 has the value 2 and assigns it to the field symbol <FS>.The program below fills a hashed table with a list of square numbers. ENDCLASS. CLASS example DEFINITION. CLASS example IMPLEMENTATION.

WRITE: / line-col1 COLOR 5. IF line-col2 = 100. INSERT line INTO TABLE itab. DO 4 TIMES. ENDMETHOD. line-col2. ENDCLASS. LOOP AT itab INTO line. LOOP AT itab INTO line. FIELD-SYMBOLS <fs> LIKE LINE OF itab. example=>main( ). line-col2 COLOR 5. 160 . line-col2. SKIP. WRITE /'------------------------'. READ TABLE itab WITH TABLE KEY col1 = 2 ASSIGNING <fs>. ENDIF. WRITE: / line-col1. WRITE: / line-col1. <fs>-col2 = 100. col2 TYPE i. line-col2 = sy-index ** 2. END OF line. ENDLOOP. ' line-col2'. START-OF-SELECTION. ENDDO. ENDLOOP. WRITE: ' line-col1'. col1 TYPE i. line-col1 = sy-index. ELSE. DATA itab LIKE HASHED TABLE OF line WITH UNIQUE KEY col1.DATA: BEGIN OF line. Following is the output of the above example.

Following is produce after execution. ENDCLASS. IF sy-subrc = 0. CLASS example DEFINITION. "Parameters are components of a selection screen that "are assigned a global elementary data object in program "and an input field on the selection screen. DATA scarr_tab TYPE SORTED TABLE OF scarr WITH UNIQUE KEY carrid. CLASS-METHODS main. example=>main( ). ENDMETHOD. METHOD main. "scarr table stores airline details SELECT * FROM scarr INTO TABLE scarr_tab. CLASS example IMPLEMENTATION. READ TABLE scarr_tab WITH TABLE KEY carrid = p_carrid TRANSPORTING NO FIELDS. DATA idx TYPE i. ENDIF. idx. REPORT z_itb_read05. A special "screen that can be defined without the use of the Screen "Painter by using the statement like PARAMETERS PARAMETERS p_carrid TYPE scarr-carrid. idx = sy-tabix.The following program checks whether a particular line exists in the internal table sflight_carr. ENDCLASS. and assign the table index of the found line in sy-tabix to idx. START-OF-SELECTION. PUBLIC SECTION. WRITE: 'Value find at '. 161 .

If we delete a line before or at the current line. Note.. that is. Once the loop has been completely processed. An endless loop can result. We insert lines behind the current line. The sequence in which the table lines are read depends on the table category. This means that you can divide sequences of entries into groups based on the contents of certain fields. sy-tabix is assigned that value that it had prior to entering the loop. Internal tables are divided into groups according to the sequence of the fields in the line structure. The control levels are formed by sorting the internal table in the sequence of its structure.. it will not be processed in a subsequent loop pass. Tables in which the table key occurs at the start of the table are particularly suitable for control level processing... The first column defines the highest control level and so on. The statements AT and ENDAT define statement blocks that are executed at control breaks. and so on. Statements in the LOOP-ENDLOOP control structure that are not executed within an AT-ENDAT control structure are executed in each pass of the loop. Standard tables and sorted tables are read based on their ascending table index. . The additions AT statements determine the control break at which their statement blocks are executed. by the first field first. Control level processing is allowed within a LOOP AT over an internal table.Use of LOOP AT Loop The LOOP AT loop can be used to read rows from internal table sequentially. The sy-tabix is affected in the subsequent loop pass. The row that has been read is available in the statement block of the loop. these new lines will be processed in the processed in the subsequent loop passes. the internal loop counter is increased by one with each inserted line. REFRESH and SORT and all types of assignments to internal table are not allowed in classes.. LOOP AT itab INTO {wa|ASSIGNING|REFERENCE INTO dref| TRANSPORTING NO FIELDS}. the statement SUM can be specified to add together the numeric components of the control level. In index tables sy-tabix is filled with the index of the current line in each loop pass. If we insert lines in front of the current line. Within these statement blocks. The lines of hashed tables are read either in the sequence in which they were inserted into the table or in the sort sequence if they were sorted with the SORT statement. If we delete a line after the current line. statements such as CLEAR. AT FIRST. ENDAT. then by the second field. Control break is the change from one control level to another in the control level processing. FREE. 162 . the internal loop counter will be decreased accordingly. The control level hierarchy must be known when you create the internal table.

REPORT z_itb_loop. ENDAT..... . ENDAT statement block. you can specify it dynamically as (compi).. the work area LINE is output for each loop pass..... NEW defines the control levels by the beginning of a group of lines with the same content in the content compi and in the components to the left of compi.. You do not have to use all control level statements....ENDLOOP block. ENDAT. is used for control level processing........... AT NEW comp2... END OF defines the control levels by the end of a group of lines with the same content in the content compi and in the components to the left of compi.. All character fields to the right of the current group key are filled with asterisks (*).. ENDAT. The total for all numeric fields is always calculated when the contents of col1 change and when the system is in the last loop pass.. ENDAT. 163 .. FIRST is used to define the control level by the first line of the internal table. If a control level field compi is not known until runtime... AT END OF comp1. CLASS example DEFINITION. PUBLIC SECTION. You should not use control level statements in loops where the line selection is restricted by WHERE or FROM and TO...AT NEW comp1... But you must place the used ones in the above sequence...... Neither should the table be modified during the loop... a restricting condition can only be specified if this selects a consecutive line block of the internal table.. AT END OF comp2. ... Note: After LOOP.... .ENDAT.... .. The first field of the table key. ENDLOOP. The control break takes place when the last line is read... LAST is used to define the control level by the last line of the internal table.. In both NEW and END OF the control breaks take place when the content of the component compi or another component to the left of compi changes... All other fields to the right of the current group key contain their initial value. . AT LAST.. In the program below in the LOOP .. ... The innermost hierarchy level <single line processing> processes the table lines that do not correspond to a control level change... the behavior of control level processing is undefined.. col1... The control break takes place when this line is read. If a work area does not contain the current line in the AT ... <single_line processing> .... Otherwise...

"control breaks when last line is reached AT LAST. col3 TYPE i. "Control breaks when the contents (A. "sum up all numeric fields SUM. line-col1 = 'B'. line-col3 = sy-index * 4. col2 TYPE i. ENDCLASS. line-col2 = sy-index. line-col3 COLOR 6. WRITE: / line-col1 COLOR 6. ULINE. line-col2. 164 . ENDDO. SORT itab BY col1 ASCENDING. CLASS example IMPLEMENTATION. line-col2 COLOR 6. END OF line. col1 TYPE c LENGTH 1. DO 3 TIMES. SKIP 2. METHOD main. DATA itab LIKE HASHED TABLE OF line WITH UNIQUE KEY col1 col2. line-col2 = sy-index. DATA: BEGIN OF line. WRITE: / line-col1. ' "print horizontal line ULINE. COL3'. ULINE. LOOP AT itab INTO line. INSERT line INTO TABLE itab. WRITE: 'COL1'. "sum up all numeric fields individually "for A and B SUM. DO 3 TIMES. line-col3. INSERT line INTO TABLE itab. B) "of col1 change AT END OF col1. ENDDO. ' COL2'. ENDAT. ULINE.CLASS-METHODS main. line-col1 = 'A'. line-col3 = sy-index * 2.

The sequence of the columns in the internal table defines the control level hierarchy. ULINE. CLASS example DEFINITION. Following is the output of the above program. the sort sequence and the control level hierarchy are the same. In this example. the sorted internal table itab is filled with data from the database table sbook using the Open SQL statement SELECT. CLASS-METHODS main. line-col2 COLOR 6. line-col3 COLOR 6. example=>main( ). Since the table key is the entire line. ENDAT. The sequence of the ATENDAT blocks within the LOOP and ENDLOOP statements is important. PUBLIC SECTION. ENDLOOP. ENDMETHOD. START-OF-SELECTION. REPORT z_itb_loop02.WRITE: / line-col1 COLOR 6. CLASS example IMPLEMENTATION. "sbook is the flight booking table 165 . ENDCLASS. ENDCLASS. METHOD main.

AT NEW fldate. carrid TYPE connid TYPE fldate TYPE custtype TYPE class TYPE bookid TYPE END OF line. 'Flight Class:'. line-class. WRITE: / 'Booking ID:'. ENDLOOP. "control breaks when the contents of the "component carrid or another component to "the left of carrid changes. LOOP AT itab INTO line. ENDAT. ENDAT. ENDAT. line-carrid. WRITE / '----------------'. "control breaks when the contents of "component class changes AT END OF class. WRITE: / 'Airline Code:'. ENDCLASS. WRITE / 'List of Bookings'. sbook-connid. ENDAT. line-bookid. AT NEW connid. AT NEW custtype. sbook-custtype. WRITE: / 'Customer Type:'. line-connid. "control breaks when 1st line is read AT FIRST. AT NEW carrid. sbook-bookid.DATA: BEGIN OF line. line-fldate. ENDMETHOD. WRITE: / 'Flight Conn ID:'. ULINE. line-custtype. WRITE: / 'Flight Date:'. ENDAT. sbook-fldate. SELECT carrid connid fldate custtype class bookid FROM sbook INTO CORRESPONDING FIELDS OF TABLE itab WHERE custtype = 'B'. sbook-class. ENDAT. sbook-carrid. 166 . DATA itab LIKE SORTED TABLE OF line WITH UNIQUE KEY table_line.

Following is the output of the above example.. Not only it is used to find the line that you want to change.. Modifying Rows To change the contents of a single line or several lines we can us the following statement: MODIFY {TABLE itab|itab INDEX idx FROM wa [TRANSPORTING comp1 comp2 .START-OF-SELECTION. in sorted table binary search is applied. which must be compatible with the line type of the internal table. The system searches for the relevant lines as follows: In standard table linear search is used. The system searches the internal table for the line whose table key corresponds to the key fields in <wa>.] ASSIGNING <fs> [CASTING]|REFERENCE INTO dref}| {itab FROM wa TRANSPORTING comp1 comp2 . but it also contains the new contents. The work area <wa>. WHERE log_exp}. plays a double role in this statement. example=>main( ).. The following example uses the TABLE addition.. while in hashed table the entry is found using the hash algorithm of the internal table. 167 .

CLASS example IMPLEMENTATION. WRITE: / scarr_wa-carrid. PUBLIC SECTION. ENDMETHOD. WRITE / '------------------'. ENDCLASS. TYPE c LENGTH 3. DATA scarr_tab TYPE SORTED TABLE OF scarr WITH UNIQUE KEY carrid. SKIP.'. ULINE. CLASS-METHODS main. airline_code = 'AA'. WRITE 'AFTER MODIFICATION. ENDCLASS.REPORT z_itb_modify01. scarr_wa-carrname. 168 . "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_wa-currcode = 'EUR'. METHOD main. SELECT * FROM scarr INTO TABLE scarr_tab. CLASS example DEFINITION. ' Currency'. WRITE / 'BEFORE MODIFICATION. "read again that specific line READ TABLE scarr_tab INTO scarr_wa WITH TABLE KEY carrid = airline_code. ' '. ' '. WRITE: 'Airline ID '. scarr_wa-carrname.'. DATA: scarr_wa airline_code TYPE scarr. ' Name'. scarr_wa-currcode. WRITE: / scarr_wa-carrid. READ TABLE scarr_tab INTO scarr_wa WITH TABLE KEY carrid = airline_code. scarr_wa-currcode. MODIFY TABLE scarr_tab FROM scarr_wa TRANSPORTING currcode. WRITE / '------------------'.

START-OF-SELECTION. example=>main( ).

The following example changes the currency to EURO using the index access.
REPORT z_itb_modify02.

CLASS example DEFINITION. PUBLIC SECTION. CLASS-METHODS main. ENDCLASS. CLASS example IMPLEMENTATION. METHOD main. DATA scarr_tab TYPE SORTED TABLE OF scarr WITH UNIQUE KEY carrid. DATA: scarr_wa idx airline_code TYPE scarr, TYPE sy-tabix, TYPE c LENGTH 3.

SELECT * FROM scarr INTO TABLE scarr_tab. airline_code = 'AA'. READ TABLE scarr_tab INTO scarr_wa WITH TABLE KEY carrid = airline_code. WRITE: 'Airline ID ', ' Name', ' Currency'. ULINE. WRITE / 'BEFORE MODIFICATION.'. WRITE / '------------------'. WRITE: / scarr_wa-carrid, ' ', scarr_wa-carrname, scarr_wa-currcode. SKIP. WRITE 'AFTER MODIFICATION.'. WRITE / '------------------'. idx = sy-tabix. scarr_wa-currcode = 'EUR'. MODIFY scarr_tab INDEX idx FROM scarr_wa TRANSPORTING currcode. READ TABLE scarr_tab INTO scarr_wa WITH TABLE KEY carrid = airline_code. WRITE: / scarr_wa-carrid, ' ', scarr_wa-carrname, scarr_wa-currcode.

169

ENDMETHOD. ENDCLASS. START-OF-SELECTION. example=>main( ).

Following is the output of the above two examples.

Deleting Rows To delete a line(s) of an internal table we can use the DELETE statement. The syntax follows as: DELETE {{TABLE itab FROM wa|WITH TABLE KEY comp1=dobj1 … compn=dobjn}|itab [INDEX idx]}}| {itab [FROM idx1] [TO idx2] [WHERE log_exp]}| {ADJACENT DUPLICATES FROM itab [COMPARING comp1 …|ALL FIELDS]}. With variant TABLE we have to specify the line by using the table key. In standard and sorted table we can specify the line to be deleted by its table index idx. idx expects a data object of the type i. Within 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 index idx1 onwards are included. When addition TO is added only the table rows up to table index idx2 are included. If idx2 is less than idx1, no rows are deleted. We can specify any logical expression log_exp after WHERE, for which the first operand of each individual comparison is a component of the internal table. With additions ADJACENT DUPLICATES, the statement DELETE deletes all lines in certain groups of lines, except 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 key fields. If the addition COMPARING is specified, the groups are determined either by the content

170

of the specified components comp1 comp2 ... 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 key field column id has the contents of 307.
REPORT z_itb_delete01.

CLASS example DEFINITION. PUBLIC SECTION. CLASS-METHODS main. ENDCLASS. CLASS example IMPLEMENTATION. METHOD main. DATA: BEGIN OF line, id TYPE i, name TYPE c LENGTH 20, END OF line. DATA itab LIKE HASHED TABLE OF line WITH UNIQUE KEY id. line-id = 100. line-name = 'Asghar'. INSERT line INTO TABLE itab. line-id = 200. line-name = 'Safdar'. INSERT line INTO TABLE itab. line-id = 305. line-name = 'Zeeshan'. INSERT line INTO TABLE itab. line-id = 307. line-name = 'Safdar'. INSERT line INTO TABLE itab. WRITE: ' ID', ' Name'. ULINE. WRITE 'Before Delete'. WRITE / '-------------'. LOOP AT itab INTO line. WRITE: / line-id, line-name. ENDLOOP. DELETE TABLE itab WITH TABLE KEY id = 307. SKIP. WRITE / 'After Delete'. WRITE / '------------'. LOOP AT itab INTO LINE. WRITE: / LINE-ID, LINE-name. ENDLOOP. ENDMETHOD. ENDCLASS.

171

START-OF-SELECTION. example=>main( ).

Following is the output of above program.

The next program fills a hashed table with a list of square numbers. The DELETE statement deletes the lines of the table where the content of field col2 is greater than 1 and the content of field col1 is less than 4.
REPORT z_itb_delete02.

CLASS example DEFINITION. PUBLIC SECTION. CLASS-METHODS main. ENDCLASS. CLASS example IMPLEMENTATION. METHOD main. DATA: BEGIN OF line, col1 TYPE i, col2 TYPE i, END OF line. DATA itab LIKE HASHED TABLE OF line WITH UNIQUE KEY col1. DO 4 TIMES. line-col1 = sy-index. line-col2 = sy-index ** 2. INSERT line INTO TABLE itab. ENDDO. WRITE: ' ' ULINE. No.', Square'.

172

WRITE 'Before Delete'. WRITE / '-------------'. LOOP AT itab INTO line. WRITE: / line-col1, line-col2. ENDLOOP. DELETE itab WHERE ( col2 > 1 ) AND ( col1 < 4 ). WRITE / 'After Delete'. WRITE / '-------------'. LOOP AT itab INTO line. WRITE: / line-col1, line-col2. ENDLOOP. ENDMETHOD. ENDCLASS. START-OF-SELECTION. example=>main( ).

The above program produces the following output.

The example below creates and fills a standard table. Here, the first DELETE statement deletes the second line from itab 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 col1 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 key field col2 are the same as on the second line. Although the contents of the default key are the same for the first and the fifth line, the fifth line is not deleted because it is not adjacent to the first line.
REPORT z_itb_delete03.

CLASS example DEFINITION. "static methods PUBLIC SECTION. CLASS-METHODS: main,

173

make_list. "static attributes PRIVATE SECTION. CLASS-DATA: BEGIN OF line, col1 TYPE i, col2 TYPE c, END OF line. CLASS-DATA pos TYPE i. CLASS-DATA itab LIKE STANDARD TABLE OF line WITH NON-UNIQUE KEY col2. ENDCLASS. CLASS example IMPLEMENTATION. METHOD make_list. SKIP TO LINE 1. LOOP AT itab INTO line. "AT position the output according to pos WRITE: AT /pos line-col1, line-col2. ENDLOOP. ENDMETHOD. METHOD main. line-col1 line-col1 line-col1 line-col1 line-col1 line-col1 line-col1 pos = 0. CALL METHOD make_list. DELETE ADJACENT DUPLICATES FROM itab COMPARING ALL FIELDS. pos = 15. CALL METHOD make_list. DELETE ADJACENT DUPLICATES FROM itab COMPARING col1. pos = 30. CALL METHOD make_list. DELETE ADJACENT DUPLICATES FROM itab. pos = 45. CALL METHOD make_list. ENDMETHOD. ENDCLASS. = = = = = = = 1. 1. 1. 2. 3. 4. 5. line-col2 line-col2 line-col2 line-col2 line-col2 line-col2 line-col2 = = = = = = = 'A'. 'A'. 'B'. 'B'. 'B'. 'B'. 'A'. APPEND APPEND APPEND APPEND APPEND APPEND APPEND line line line line line line line TO TO TO TO TO TO TO itab. itab. itab. itab. itab. itab. itab.

174

If the internal table has no header line. Processing Entire Internal Tables When we access the entire internal table. If so. CLEAR itab. though the entire memory area occupied by the table rows is released. 175 . meaning that it deletes all rows of the internal table. The memory space required for the table is freed up to the initial memory size INITIAL SIZE. we address the body of the table as a single data object. FREE itab. you should always use CLEAR instead of REFRESH. an internal table itab is filled and then initialized with REFRESH. REFRESH acts like CLEAR. the memory is released. The CLEAR statement deletes all the rows and all the memory required. Following is the output of above coding. Therefore. except the initial memory requirement is released. In the program.START-OF-SELECTION. The REFRESH statement sets an internal table to its initial value. REFRESH and FREE statements. The following operations on the body of an internal table are relevant: Initialization We can initialize internal tables with the CLEAR. The IF statement uses the expression itab IS INITIAL to find out whether itab is empty. For table with header line we must place two brackets ([ ]) after the table name as: CLEAR itab[]. and the initial memory area remains unoccupied. REFRESH itab. example=>main( ). FREE has the same effect as the REFRESH statement.

line-col2 = 'B'. Following is the output. WRITE 'ITAB is empty'. DATA itab LIKE TABLE OF line. line-col1 = 'A'. we can use internal tables as operands in a MOVE statement. REFRESH itab. Or the equivalent statement. col2. FREE itab. ENDMETHOD. DATA: BEGIN OF line. END OF line. CLASS-METHODS main. ENDIF. example=>main( ).REPORT z_itb_init01. START-OF-SELECTION. PUBLIC SECTION. APPEND line TO itab. ENDCLASS. col1. METHOD main. Assignment Like other data objects. 176 . CLASS example IMPLEMENTATION. itab2 = itab1. IF itab IS INITIAL. MOVE itab1 TO itab2. CLASS example DEFINITION. ENDCLASS.

line-col2 = 'B'. WRITE: / line-col1. col2(1) TYPE c. DATA: itab1 LIKE TABLE OF line WITH HEADER LINE. When using internal tables with header lines. WRITe: 'Col1'. But it must be noted that tables with header line is not supported in OO context. END OF line. itab1 has a header line. 177 . LOOP AT itab2 INTO line. REPORT z_itb_asgn01. These statements assign the entire contents of table itab1 to table itab2. Following is the output of the above code. DATA: BEGIN OF line. its entire contents are assigned to itab2. ' '. ENDLOOP.Both operands must either be compatible or convertible. col1(1) TYPE c. the header line and the body of the table have the same name. START-OF-SELECTION. Note the brackets in the statement. we must place two brackets ( [ ]) after the table name. line-col1 = 'A'. After filling itab1 line by line using the APPEND statement. itab2 = itab1[]. ' ULINE. including the data in any nested internal tables. line-col2. The example creates two standard tables itab1 and itab2 with the line type of the structure line. The original contents of the target table are overwritten. itab2 LIKE TABLE OF line. If we want to address the body of the table in an assignment. APPEND line TO itab1. Col2'.

LOOP AT ftab INTO fl. DATA: ftab TYPE SORTED TABLE OF WITH NON-UNIQUE itab TYPE HASHED TABLE OF WITH UNIQUE KEY fl TYPE f. START-OF-SELECTION. REPORT z_itb_asgn02. It is therefore possible to assign the contents of itab to ftab. ENDLOOP. ENDDO. WRITE: 'Contents of itab'. ENDMETHOD. f KEY table_line. ENDLOOP. example=>main( ). CLASS example IMPLEMENTATION. are convertible. the contents are automatically sorted by the key of ftab. and therefore the entire tables. CLASS example DEFINITION. INSERT sy-index INTO TABLE itab.In the following example ftab is a sorted table with line type f and a non-unique key. ENDCLASS. WRITE: / fl. CLASS-METHODS main. itab is a hashed table with line type i and a unique key. Following is the output. ftab = itab. ENDCLASS. The line types. SKIP. WRITE: / fl. WRITE: / 'Contents of ftab after Assignment'. METHOD main. When you assign the unsorted table itab to the sorted table ftab. DO 3 TIMES. 178 . PUBLIC SECTION. i table_line. LOOP AT itab INTO fl.

CLASS-METHODS main. For table with header line we must place two brackets ([ ]) after the table name. the comparison stops when it reaches the first pair of components that are unequal. they are compared recursively. After appending the same line to jtab. another line is appended to itab and the third logical expressions tests whether jtab is less than or equal to itab.Comparison We can use internal tables as operands in logical expressions as: itab1 <operator> itab2. ENDCLASS. another line is appended to jtab. If components of the table lines are themselves internal tables. CLASS example IMPLEMENTATION. in the last logical expression. <=. >=. LE. REPORT z_itb_compar01. the second logical expression tests whether both tables are equal. itab is less than jtab. Its contents are unequal to the contents of the last line of itab. Then. The first table field whose contents are different in itab and jtab is col1 in the last line of the table: 30 in itab and 50 in jtab. and returns the corresponding result. >. DATA: BEGIN OF line. <. GE). itab and jtab. =. LT. component by component. The <operator> can be any relational operator (EQ. <>. The next logical expressions test whether itab is not equal to jtab. If you are testing internal tables for anything other than equality. If two internal tables contain the same number of lines. Then. METHOD main. 179 . they are compared line by line. NE. itab is filled with 3 lines and copied to jtab. Next. another line is appended to itab and the first logical expression tests whether itab is greater than jtab. PUBLIC SECTION. GT. Therefore. CLASS example DEFINITION. This example creates two standard tables.

ENDIF.col1 TYPE i. ENDIF. line-col2 = sy-index ** 2. ENDIF. IF itab = jtab. 180 . line-col2 = 80. col2 TYPE i. ENDCLASS. line-col1 = 10. IF itab < jtab. line-col1 = sy-index. ENDDO. Following is the output of the above code. DO 3 TIMES. APPEND line TO jtab. jtab LIKE TABLE OF line. ENDMETHOD. jtab = itab. APPEND line TO itab. START-OF-SELECTION. line-col2 = 20. APPEND line TO itab. WRITE / 'jtab is less than or equal to itab'. END OF line. example=>main( ). APPEND line TO itab. ENDIF. WRITE / 'itab is not equal to jtab'. DATA: itab LIKE TABLE OF line. WRITE / 'itab is equal to jtab'. WRITE / 'itab is less than jtab'. IF jtab <= itab. line-col2 = 60. IF itab > jtab. ENDIF. line-col1 = 50. WRITE / 'itab is greater than jtab'. IF itab <> jtab. line-col1 = 30. APPEND line TO jtab.

Sorting The standard and hashed tables can be sorted by using the SORT statement. If AS TEXT is not specified..). The program below demonstrates sorting. CLASS-DATA: BEGIN OF line. The addition AS TEXT specified that text-type components are sorted according to the locale (defines language-dependent and country-dependent characteristics of characters. text-type components are sorted according to the encoding in the code page of the current text environment. a locale and a system codepage. make_list. that are specified after it. PUBLIC SECTION. If neither of the additions is entered. Following is the syntax of SORT statement. SORT itab [STABLE] { { [ASCENDING|DESCENDING] [AS TEXT] [BY {comp1 [ASCENDING|DESCENDING] [AS TEXT]} {comp2 [ASCENDING|DESCENDING] [AS TEXT]} .. Using SORT for sorted tables is syntactically prohibited. PRIVATE SECTION.. CLASS-METHODS: main. REPORT z_itb_sort01. STABLE is used to perform stable sorting. which means that the relative sequence of lines that does not change in the sort key remains unchanged in the sort. The addition ASCENDING or DESCENDING can be used to specify the sort direction explicitly as ascending or descending. 181 . With the addition BY compi. ] }. the table is not sorted according to the table key. CLASS example DEFINITION. such as the sort sequence or uppercase/lowercase conversion) of the current text environment (part of the runtime environment of an ABAP program and is made up of a language. but instead according to the components comp1 comp2.. the table is sorted in ascending order.

'Name' COLOR 5. CLASS example IMPLEMENTATION. c LENGTH 10. APPEND line TO itab. METHOD make_list. line-land = 'USA'. line-land = 'F'. line-weight = '75. 182 . SORT itab. ' Weight' COLOR 5.land TYPE name TYPE age TYPE weight TYPE END OF line.00'. ENDMETHOD. line-weight = '95. line-name = 'Hans'. line-land = 'GB'.00'. line-weight = '80. line-age = 18. SKIP. WRITE / 'Without sorting' COLOR 6. line-name = 'Karl'. WRITE: / line-land COLOR 7. CLASS-DATA itab LIKE STANDARD TABLE OF line WITH NON-UNIQUE KEY land. line-age = 20.00'. line-weight COLOR 7. line-land = 'G'. APPEND line TO itab. line-weight = '50. line-name = 'Howard'. line-age = 30. c LENGTH 3. ' Age' COLOR 5. ENDCLASS. i. WRITE 'With sorting' COLOR 6. line-name COLOR 7. WRITE: 'Land' COLOR 5. APPEND line TO itab. METHOD main. ENDLOOP. CALL METHOD make_list. line-weight = '60. APPEND line TO itab. line-name = 'Michele'. line-age = 40. ULINE. line-name = 'Jenny'. line-age = 60. line-age COLOR 7.00'. LOOP AT itab INTO line. line-land = 'G'. p DECIMALS 2. APPEND line TO itab.00'.

it is sorted alphabetically by the TEXT field. Second. example=>main( ). CALL METHOD make_list. we have taken the results from a German text environment. ENDMETHOD. First. WRITE 'Sorting by land and weight' COLOR 6. it is sorted binarily by the XTEXT field. SORT itab DESCENDING BY land weight ASCENDING. In the following example the table is sorted three times. Following is the output of the above example.CALL METHOD make_list. START-OF-SELECTION. Third. Since there is no directly corresponding case in English. WRITE 'Stable sorting' COLOR 6. SORT itab STABLE. it is sorted binarily by the TEXT field. CALL METHOD make_list. ENDCLASS. 183 .

WRITE / 'Sorted binarily by text field' COLOR 6. INSERT line INTO TABLE itab. SKIP. CONVERT TEXT line-text INTO SORTABLE CODE line-xtext. CONVERT TEXT line-text INTO SORTABLE CODE line-xtext. ENDLOOP. line-text = 'Umer'. INSERT line INTO TABLE itab. METHOD main. LOOP AT itab INTO line. END OF line. CONVERT TEXT line-text INTO SORTABLE CODE line-xtext. line-text = 'Omer'. ENDMETHOD. CLASS-DATA itab LIKE HASHED TABLE OF line WITH UNIQUE KEY text. WRITE / 'Sorted binarily by xtext field' COLOR 6. CLASS-METHODS: main. itab. make_list. "convertes a text to a "result is assigned to CONVERT TEXT line-text INSERT line INTO TABLE sortable byte sequence and the xtext INTO SORTABLE CODE line-xtext. CLASS example DEFINITION. line-text = 'Imer'. SORT itab. SORT itab BY xtext. METHOD make_list. WRITE / line-text COLOR 7. CLASS example IMPLEMENTATION. PRIVATE SECTION.REPORT z_itb_sort02. xtext TYPE x LENGTH 160. CALL METHOD make_list. INSERT line INTO TABLE itab. line-text = 'Ömer'. PUBLIC SECTION. CLASS-DATA: BEGIN OF line. text TYPE c LENGTH 6. 184 . ENDCLASS. CALL METHOD make_list.

SORT itab AS TEXT. CALL METHOD make_list.WRITE / 'Sorted alphabetically by text field' COLOR 6. ENDMETHOD. 185 . ENDCLASS. Following is the output. START-OF-SELECTION. example=>main( ).

The Class Builder then generates the corresponding statements in the class pool of the class. The global class should be prefixed with cl_ . Classes in turn are used to create instance (objects). The global classes of an AS ABAP form its class library. We should use local classes for objects that are only required in one program. The Class 186 . and they are implemented in its implementation part. For local classes we must enter the relevant statements for the required program in the ABAP Editor. Classes in ABAP Objects can be declared either globally or locally. The ABAP Objects streamlined the existing ABAP syntax using the concept of syntax cleansing that is many outdated and obsolete language constructs are forbidden in ABAP Objects. A class is the pattern or template for an object much like a data type is the template for a data object. Creating Classes Both global and local classes are always declared in the declaration part of the program. Global classes can only created in class pools program type using the Class Builder tool (SE24) of the ABAP Workbench. except type groups and interface pools. which are allowed outside of classes only for reasons of compatibility. The Class Builder hides the class pool behind user interface. by selecting Goto…Section in Class Builder which enables to edit the code of a global class in the ABAP Editor. Local class hides a global class of the same name. The only code to enter for the global classes is the implementation of the methods. we can use the keyboard instead of the mouse. while for global classes we must use the Class Builder (SE24) and fill the relevant input templates of the Class Builder with data. Classes also behave like data types that are distinguished into global data types in the ABAP Dictionary and local data types in any program. Local Classes A local class is only visible in the program in which it is defined. ABAP Objects represents the part of the ABAP programming language that allows for OOP on the basis of classes. We should define global classes whenever we need objects of the same type in different programs. provided that no limitation by the package of the class exists. Global Classes A global class is visible and can be used in every program of the same AS ABAP. However. The name of local class should be prefixed with lcl_. Local classes can be defined in any ABAP program.Classes and Objects Object Oriented Programming is based on the encapsulation of data and its associated functionality in classes.

. Attributes Attributes are internal data fields within a class that can have any ABAP data type... each class definition always consists of a declaration part and an implementation part. we can simply enter the attributes and their properties in the Attributes tab of Class Builder.... With global classes... The implementation part contains the code for the class components methods and events.. 187 .. the ABAP Unit tool could be used. The state of an object is determined by the contents of its attributes.. ENDCLASS... the Class Builder displays the empty class as shown below: Following are the different components of a class. CLASS myclass IMPLEMENTATION... ... ENDCLASS.. static attributes are declared with CLASS-DATA and constant attributes are declared with CONSTANTS keyword..... Declaration and Implementation Part In terms of syntax..... The constant in Class Builder can be created by specifying Constant in the Level column of the Attributes tab and enter initial value in the Initial Column.. Once we have created a global class........ In local classes instance attributes are declared using the DATA statement. In declaration part we define various class components (Attributes.. In global classes.Builder contains a small testing environment that can be used to test functionality of the methods of a global class but for extensive tests..... we usually wouldn’t see this structure directly. . Methods and Events).... . The basic structure of a class is as follows: CLASS myclass DEFINITION.

They can access all of the attributes of a class. With events. There does not have to be a handler method registered for every event. The private attributes of a class can only be changed by methods in the same class. In the Class Builder. The link between the trigger and the handler is not established until runtime. we must enter the methods and their properties in the Methods tab. any number of event handler methods can be called. This allows them to change the data content of an object. the handler determines the events to which it wants to react. When an event is triggered. Events Objects or classes can use events to trigger event handler methods in other objects or classes. The events of a class can be triggered in the methods of the same class using the RAISE EVENT statement. one method can be called by any number of users. Instance methods are declared using the METHODS keyword while the static methods are declared with CLASS-METHODS. In a normal method call. They also have a parameter interface. Methods are implemented with keywords METHOD meth_name. 188 . In a normal method call. The link between trigger and handler is established dynamically in a program using the SET HANDLER statement. and receive values back from them. Instance events are declared using the EVENTS keyword while the static methods are declared with CLASS-EVENTS. the calling program determines the methods that it wants to call. Methods can be called by using the CALL METHOD statement. These methods must exist.Methods Methods are procedures in a class that define the behavior of an object. with which users can supply them with values when calling them. … ENDMETHOHD.

Visibility Sections Each 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... Following example demonstrate the basic structure of a local class. CLASS lcl_employee DEFINITION. Protected Section All components of protected section can be accessed by the methods of the subclasses and the methods of class.. Public Section All components of public section can be accessed by all external users...... the methods of subclasses and by the methods of the class. PUBLIC SECTION .. They represent the interface between the class and its subclasses. These components represent the interface between the class and the external world. PUBLIC SECTION... They are not part of the interfaces of the class.... 189 .. Private Section Components in this section can only be used within the methods of the class.In global classes.... ENDCLASS. Following is the syntax used to separate the declaration part of class into three visibility sections: CLASS myclass DEFINITION.. events are declared on the Events tab of Class Builder.. PROTECTED SECTION .. REPORT z_oop_class01. "Instance methods declared in public "section visibilty METHODS set_employee.. PRIVATE SECTION ..

pay = '30000. id = 'A001'. METHOD get_employee. ENDMETHOD. PRIVATE SECTION. ENDCLASS. id. METHOD main. pay. name. SKIP. "static method CLASS-METHODS main. ENDCLASS. address. ENDCLASS. "emp_obj is a reference variable which will be "pointing to lcl_employee reference type "or class DATA emp_obj TYPE REF TO lcl_employee. DATA address TYPE string. WRITE: / 'Address: '. "Instance methods implementation METHOD set_employee. ENDMETHOD. address = 'Peshawar. DATA name TYPE string. "Instance attributes declared in "private section visibilty DATA id TYPE c LENGTH 5. WRITE: / 'Pay '.0'. WRITE: / 'Name: '. CLASS lcl_demo DEFINITION. CLASS lcl_employee IMPLEMENTATION. PUBLIC SECTION. "instanitate employee object and assign the object "reference to the refercne varibale emp_obj 190 . DATA pay TYPE f. WRITE: / 'ID: '. name = 'Muhammad Asghar Khan'.METHODS get_employee. CLASS lcl_demo IMPLEMENTATION. Pakistan'. WRITE 'Employee Details'.

ENDCLASS. "the instance component selector operator is used "to call instance methods emp_obj->set_employee( ). ENDMETHOD. START-OF-SELECTION. or Private for each component in the visibility column.CREATE OBJECT emp_obj. Protected. emp_obj->get_employee( ). Following is the output of the above example. 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 Public. "the static component selector operator is used to "call static method lcl_demo=>main( ). 191 .

if we want to write programming code. Formal parameters are local data objects that are declared in the method’s parameter interface rather then in the body of the method. However. The following properties can be defined for a formal parameter: • • • Parameter Type Kind of Parameter Passing Parameter Typing 192 . in the same way as that of a local class in the ABAP Editor. we can display the interface during implementation of global classes. Parameter Interfaces 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 Class Builder. Protected Section or Private Section to enter the complete declaration part of global class. here we discuss the finer points of methods in ABAP Objects. formal parameters can be used via their names in operand positions. Within a method.However. The parameter interface of a method comprises formal parameters. Methods Revisited We have already defined and called methods earlier. No further details of the parameter interface are required in the implementation section between METHOD and ENDMETHOD. The actual parameters are used to initialize the formal parameters. Actual parameters are placed in the parameter list of the method invocation. we can select Goto Public Section.

We can define the following parameters: Parameter Type • Input Parameters: Input parameters are defined after the IMPORTING addition to the METHODS or CLASS-METHODS statement. In other words. or are declared by selecting Importing in the Type column on the Parameters tab page in the Class Builder. The following example demonstrates the use of input parameters. When a method is called. Input parameters for which pass by value are defined are not passed to the actual parameter when the procedure is exited. we can not use the same method names with different parameter interfaces. These values originate outside of the method and they are imported into it. 193 . even when we redefine methods in subclasses.• Supply Type of Parameter We should note that methods in ABAP Objects can not be overloaded. Input parameters for which pass by reference are defined can not be overwritten in the method. The input parameters contain values that are passed into the method from the calling program. the value of the assigned actual parameter (parameter passed from calling statement) is assigned to the input parameter.

CREATE OBJECT obj. ENDCLASS. obj->sub( no1 = number1 no2 = number2 ). sum = no1 + no2. METHODS add IMPORTING no1 TYPE no2 TYPE METHODS sub IMPORTING no1 TYPE no2 TYPE METHODS div IMPORTING no1 TYPE no2 TYPE CLASS-METHODS main. s = no2 + no1. PUBLIC SECTION. i i. obj->add( no1 = number1 no2 = number2 ). CLASS lcl_example DEFINITION. METHOD div. PARAMETERS: number1 TYPE i. WRITE: / 'Subtraction ='. s LEFT-JUSTIFIED. CLASS lcl_example IMPLEMENTATION. WRITE: / 'Division ='. sum LEFT-JUSTIFIED. ENDMETHOD. DATA obj TYPE REF TO lcl_example. METHOD sub.REPORT z_oop_methd01. ENDMETHOD. METHOD add. DATA sum TYPE i VALUE 0. METHOD main. ENDMETHOD. i i. number2 TYPE i. i i. WRITE: / 'Sum ='. d LEFT-JUSTIFIED. d = no2 DIV no1. DATA s TYPE i VALUE 0. DATA d TYPE i VALUE 0. 194 .

REPORT z_oop_methd02. PARAMETERS: number1 TYPE i. After executing the above code we get the following output. lcl_example=>main( ). • Output Parameters: Output parameters are specified after the EXPORTING addition to the METHODS or CLASS-METHODS statement. 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. operand TYPE c. Output parameters can be overwritten in the method. the output parameter is passed to the actual parameter. START-OF-SELECTION. or are declared by selecting Exporting in the Type column on the Parameters tab page in the Class Builder. These values originate within method and they are exported out of it. Following example demonstrate the use of output parameters. 195 .obj->div( no1 = number1 no2 = number2 ). If the method is exited without errors using ENDMETHOD or RETURN. When a method is called. The output parameters contain values returned from the method. ENDCLASS. CLASS lcl_example DEFINITION. PUBLIC SECTION. number2 TYPE i. ENDMETHOD.

ELSEIF op = '/'. METHOD perform_arithmetic. rslt = no1 + no2. ELSEIF op = '-'. MESSAGE 'Invalid Operator' TYPE 'I'. ELSE. "here EXPORTING specifies that the parameters "will travel out from the program and at the "same time these will be importing to the method obj->perform_arithmetic( EXPORTING no1 = number1 no2 = number2 op = operand "means this parameter 196 . ENDIF. METHODS perform_arithmetic "means the parameters will travel "in from program into method during "calling where these will act as exporting IMPORTING no1 TYPE i no2 TYPE i op TYPE c "means the parameter will travel "out from the method into the "program at calling where it will "acts as importing EXPORTING rslt TYPE i. DATA result TYPE i. rslt = no1 * no2. rslt = no1 DIV no2. CLASS lcl_example IMPLEMENTATION. ENDMETHOD. CREATE OBJECT obj. METHOD main. rslt = no2 . ELSEIF op = '*'.no1. DATA obj TYPE REF TO lcl_example.CLASS-METHODS main. IF op = '+'. ENDCLASS.

Following is the output. lcl_example=>main( ). WRITE: 'Result = '. I/O parameters can be overwritten in the method. I/O parameters contain values that are passed into the method. they are passed into it. ENDMETHOD. changed by the code within the method and then returned. START-OF-SELECTION. These values originate outside the method. 197 . • Input / Output Parameters: I/O parameters are specified after the CHANGING addition to the METHODS or CLASS-METHODS statement or are declared by selecting Changing in the Type column on the Parameters tab page in the Class Builder. and passed back. the I/O parameter is passed to the actual parameter. ENDCLASS."will travel in from method "into program where it is "acting as exporting IMPORTING rslt = result ). result. the value of the assigned actual parameter (parameter passed from calling statement) is assigned to the I/O parameter. and if the method is exited without errors using ENDMETHOD or RETURN. When a method is called.

198 . PUBLIC SECTION. ENDMETHOD. rslt = no1 DIV no2. MESSAGE 'Invalid Operator' TYPE 'I'. rslt = no1 * no2. METHOD perform_arithmetic. operand TYPE c. DATA obj TYPE REF TO lcl_example. IF op = '+'. rslt = no2 . METHODS perform_arithmetic CHANGING no1 TYPE i no2 TYPE i op TYPE c rslt TYPE i. rslt = no1 + no2. REPORT z_oop_methd03. DATA result TYPE i. ELSEIF op = '-'. ELSE. ENDCLASS.The previous example is repeated with the use of I/O parameters. number2 TYPE i. CLASS-METHODS main. METHOD main. CREATE OBJECT obj. CLASS lcl_example IMPLEMENTATION. PARAMETERS: number1 TYPE i. result. ELSEIF op = '*'. ENDIF. ENDMETHOD.no1. WRITE: 'Result = '. obj->perform_arithmetic( CHANGING no1 = number1 no2 = number2 op = operand rslt = result ). ELSEIF op = '/'. CLASS lcl_example DEFINITION.

A return value is handled in the same way that an output parameter is handled in the method. lcl_example=>main( ). in addition to the return value. START-OF-SELECTION. REPORT z_oop_methd04. ENDCLASS. The return value is then used in these operations. which. • Return Value: A method can have only one return value. CLASS-METHODS main. Following is the output of the above code listing. This return value can be declared after the RETURNING addition to the METHODS or CLASS-METHODS statement. for which pass by value must be declared. METHODS factorial IMPORTING n TYPE i RETURNING "value addition specify that "fact will be passed by value value(fact) TYPE i. can have only input parameters. a method with a return value is a functional method. CLASS lcl_math IMPLEMENTATION. or by selecting Returning in the Type column on the Parameter tab page in the class builder. 199 .ENDCLASS. A functional method can be used in operand operations. CLASS lcl_math DEFINITION. PUBLIC SECTION. however. The following example shows the use of return value.

ELSE. fact = 1. rslt = obj->factorial( 3 ). ENDMETHOD. WRITE: 'Factorial of 4 = '. ENDCLASS. DO n TIMES. ENDMETHOD. rslt = obj->factorial( 1 ). DATA rslt TYPE i. rslt RIGHT-JUSTIFIED. rslt = obj->factorial( 7 ). ENDDO. rslt RIGHT-JUSTIFIED. rslt RIGHT-JUSTIFIED.METHOD factorial. lcl_math=>main( ). ENDIF. RETURN. CREATE OBJECT obj. 200 . DATA obj TYPE REF TO lcl_math. IF n = 0. METHOD main. WRITE: / 'Factorial of 11 = '. fact = fact * sy-index. START-OF-SELECTION. WRITE: / 'Factorial of 10 = '.

Following is the output produced by above listing. A parameter that is received but not changed by the method is an input parameter. The syntax of pass by value is shown below using the example of the return value fact: 201 . In case of input parameters and I/O parameters. a local data object is created as a copy of the actual parameter for each formal parameter when the method is called. When we declare a parameter. Figure below shows how parameters are passed and received from the method. A parameter that is output but is not received is an output parameter or a return value. I/O parameters and return values if the method is exited without errors using ENDMETHOD or RETURN. Kind of Parameter Passing The formal parameter is passed either ass pass by value or pass by reference. A parameter that is received changed and output is an I/O parameter. • Pass by Value: With pass by value. The value of the formal parameter is only assigned to output parameters. the value of the actual parameter is assigned to this data object. we must select the type that matches the behavior of that parameter exactly.

ENDCLASS. The example in listing below shows the usage of by value and by reference parameters. o If you add lines to an internal table or extend a string that is defined as an output parameter that is passed by reference. and changes to formal parameters have a direct effect on the actual parameter. which is used unless a different type is specified. Thus pass by reference is the default transfer type. meth_byref IMPORTING reference(idx) TYPE i. we define the kind of parameter passing by selecting the Pass by value check box on the Parameters tab page or leaving this blank. METHODS: meth_byval IMPORTING value(idx) TYPE i. 202 . PUBLIC SECTION. REPORT z_oop_methd05. CLASS lcl_example DEFINITION. DATA msg TYPE string. METHOD main. Pass by reference always perform better than pass by value because no data object has to be created when a procedure is called and no data transport takes place. both in the syntax and in the Class Builder. CLASS lcl_example IMPLEMENTATION.… RETURNING VALUE(fact) … • Pass by Reference: With pass by reference. The method thus uses the actual parameter itself. you must initialize the parameter before the first access. 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 Do not execute read access to an output parameter that is passed by reference because its initial value is not defined. Following is the syntax of pass by reference using the example of input parameter ipara: … IMPORTING REFERENCE(ipara) … In the Class Builder. regardless of the parameter type. 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. PRIVATE SECTION. CLASS-METHODS main.

obj->meth_byref( EXPORTING idx = sy-index ).DATA obj TYPE REF TO lcl_example. WRITE: / '======================='. ENDMETHOD. Following is the output of the above example. lcl_example=>main( ). SKIP. CONCATENATE 'meth_byref: ' msg INTO msg. DO 3 TIMES. CREATE OBJECT obj. obj->meth_byval( EXPORTING idx = sy-index ). msg = idx. WRITE: / msg. ENDDO. CONCATENATE 'meth_byval: ' msg INTO msg. METHOD meth_byref. ENDDO. METHOD meth_byval. ENDMETHOD. DO 3 TIMES. 203 . WRITE: 'Calling method by Rseference'. ENDCLASS. WRITE: / msg. WRITE: / '============================'. msg = idx. ENDMETHOD. START-OF-SELECTION. WRITE: 'Calling method by Value'.

or Like) and Reference type columns accordingly on the Parameters tab page in order to specify the type. Type Ref To.Parameter Typing Typing means that to assign a type to a formal parameter. 204 . The syntax used for this purpose is a TYPE or LIKE addition. which must be specified after each formal parameter. For example: METHODS my_meth EXPORTING param TYPE data_type … In Class Builder. fill the Typing (Type.

For generic typing. CLASS-METHODS main. obj->meth1( EXPORTING ipar = '10. str = ipar. With protected methods. The main difference between typing and data declaration is that a formal parameter is assigned its actual data type only when it is linked to an actual parameter when a method is called. METHOD meth1. use generic types line numeric. All technical properties of the actual parameter are then passed to the formal parameter. METHODS meth1 IMPORTING ipar TYPE any. 205 . global types from the ABAP Dictionary or types from the public visibility section of a global class for public methods.4' ). Internal table types are also generic if the table key is not fully defined. CREATE OBJECT obj. WRITE: 'Value of in string format = '. simple and xsequence instead of any. METHOD main. If we need to use a generic type. Following example demonstrate the usage of generic typing. ENDMETHOD. ……). additional types from the protected visibility section of the class can also be used. ENDCLASS. any table. use TYPE to refer to a complete data type or LIKE to refer to a data object. DATA obj TYPE REF TO lcl_example. CLASS lcl_example DEFINITION. we should always be as specific as possible. while types from the private visibility section and local types from the class pool can be used for private method types only. str RIGHT-JUSTIFIED. data. For complete typing. its data type must match the typing (technical properties must be compatible) of the formal parameter. PUBLIC SECTION. we can specify built-in ABAP types. DATA: str TYPE string. num TYPE i. flt TYPE f. CLASS lcl_example IMPLEMENTATION. In order for an actual parameter to be passed.The type must be accessible to all users of the method. we can use the built-in generic types (any. The typing of a formal parameter may be complete or generic. REPORT z_oop_methd06.

using the example of I/O parameter: METHODS my_meth CHANGING cpare type data_type OPTIONAL … Or METHODS my_meth CHANGING cpare type data_type DEFAULT data_object … An optional formal parameter for which no actual parameter is specified is initialized in accordance with its type. SKIP. this rule can be avoided by declaring the parameter as optional. Supply Type of Parameter For every formal parameter that awaits a value (Input parameters and I/O parameters). For input parameters and I/O parameters. The assignment of actual parameters to output parameters and return values is always optional. an actual parameter must be specified when the method is called. num = ipar. WRITE: / 'Value of in integer format = '. ENDCLASS.SKIP. START-OF-SELECTION. num LEFT-JUSTIFIED. flt LEFT-JUSTIFIED. With addition DEFAULT the value and type of an appropriately specified replacement parameter data_object are copied. 206 . lcl_example=>main( ). Following is the output. The syntax is shown below. flt = ipar. ENDMETHOD. WRITE: / 'Value of in float format = '.

CREATE OBJECT obj.In the Class Builder. PRIVATE SECTION. with the exception of those for which a different entry is actually required each time the method is called. CLASS lcl_example IMPLEMENTATION. ENDMETHOD. The following program demonstrates the use of DEFAULT parameter. ELSE. iname. METHODS print IMPORTING iname TYPE string iclass TYPE string DEFAULT '10th'. for which type-specific auxiliary variables often have to be created. METHOD print. or by entering a value in the Default value column. METHOD main. obj->print( EXPORTING iname = 'Jamil' iclass = '5th' ). ENDCLASS. WRITE: / 'Your class is: '. WRITE: / 'Your class is: '. Otherwise. SKIP. iclass COLOR 6. PUBLIC SECTION. WRITE: 'Your name is: '. It is recommended that to make all formal parameters optional. DATA obj TYPE REF TO lcl_example. REPORT z_oop_methd07. we can make a formal parameter optional by selecting the Optional column. we will force the callers to specify unnecessary actual parameters. IF iclass IS NOT SUPPLIED. iclass. ENDIF. CLASS-METHODS main. 207 . CLASS lcl_example DEFINITION.

obj->print( EXPORTING iname = 'Khadija' ). START-OF-SELECTION. ENDMETHOD. Method Calls Static Method Calls Statically method can be invoked as component of a class (static) or an object. Following is the output produced by the above listing. obj->print( EXPORTING iname = 'Mudasair' iclass = '2nd' ). ENDCLASS. lcl_example=>main( ).obj->print( EXPORTING iname = 'Asghar Khan' ). Or Class_name=>my_math( ). 208 . obj->my_math( ). To call an instance method we have to use the instance component selector (->) and for static method calls we have to use the static component selector (=>).

The equal sign is not an assignment operator in this case. However. my_math( ipara1 = dobj1 ipara2 = dobj2 … ). its function is to bind actual parameters to formal parameters.If a method has several non-optional input parameters. we receive values from output parameters defined with EXPORTING. the statement is as follows. we supply the input parameters defined with IMPORTING. 209 . Instead. Functional Method Calls A functional method can have any number of input parameters and only one return value that is passed by value. this statement is hardly used in practice. RECEIVING rpara = dobj ). When the statement is executed the method is called and the return value is used as an operand. If actual parameters are to be assigned to any formal parameters. we assign the actual parameters to the I/O parameters defined with CHANGING. With CHANGING. With EXPORTING. In following example two functional methods get_area and get_volume are implemented. here a data object is explicitly assigned to each input parameter. With IMPORTING. the syntax is as follows: my_meth( EXPORTING ipara1 = dobj1 ipara2 = dobj2 … IMPORTING opara1 = dobj1 opara2 = dobj2 … CHANGING cpara1 = dobj1 cpara2 = dobj2 … ). The functional methods are intended to be used in operand position. The functional equivalent for the above statement is as follows: dobj = my_meth( ipara1 = dobj1 ipara2 = dobj2 … ). To call the function method the RECEVING addition can be used to receive the return value as: my_meth( EXPORTING ipara1 = dobj1 ipara2 = dobj2 ….

PARAMETERS: p_radius TYPE i. obj->height = p_height. ENDMETHOD. ENDCLASS. p_height TYPE i. DATA: obj TYPE REF TO lcl_cylinder. volume = obj->get_volume( ). CLASS lcl_example DEFINITION.REPORT z_oop_methd08. volume TYPE string. volume. METHOD get_area. DATA: radius TYPE f. METHOD get_volume. CLASS lcl_cylinder DEFINITION.14159'. obj->radius = p_radius. CREATE OBJECT obj. ENDMETHOD. CONSTANTS pi TYPE f VALUE '3. CLASS lcl_cylinder IMPLEMENTATION. CLASS lcl_example IMPLEMENTATION. CLASS-METHODS main. PUBLIC SECTION. height TYPE f. WRITE: 'Volumene: '. r_area = pi * me->radius ** 2. IF sy-subrc = 0. r_volume = me->get_area( ) * me->height. CALL SELECTION-SCREEN 100 STARTING AT 50 10. get_volume RETURNING value(r_volume) TYPE f. SELECTION-SCREEN END OF SCREEN 100. 210 . ENDCLASS. METHODS: get_area RETURNING value(r_area) TYPE f. PUBLIC SECTION. ENDCLASS. METHOD main. SELECTION-SCREEN BEGIN OF SCREEN 100.

The method to be called can be specified by dynamic token specifications in various forms. 211 . Following is the output of above code. The dynamic method call can be in the form of as: CALL METHOD { (meth)_name | obj->(meth_name) | (class_name)=>( meth_name) | class=>(meth_name) | (class_name)=>meth_name} [PARAMETER-TABLE ptab]. ENDMETHOD. ENDCLASS.ENDIF. START-OF-SELECTION. Dynamic Method Call To call a method dynamically we must use the language element CALL METHOD. lcl_example=>main( ). The syntax for the dynamic token specification is usually such that instead of the static syntax. a bracketed identifier is given that contains the actual syntax: … (identifier) … Dynamic method call is also known as Dynamic Invoke.

abap is the predefined type group "the table type abap_func_parmbind_tab belongs to "the type group abap TYPE-POOLS abap. 212 . CLASS lcl_example IMPLEMENTATION. abap_parmbind. IMPORTING.The PARAMETER-TABLE is used to assign actual parameters to all formal parameters of a dynamically called method. CHANGING. 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). METHOD main. RECEIVING). VALUE of type REF TO data as a pointer to an appropriate actual parameter. p_value TYPE string DEFAULT 'C:\WINDOWS'. During execution of the CALL METHOD statement. CLASS lcl_example DEFINITION. PUBLIC SECTION. REF TO cx_root. p_out TYPE string DEFAULT 'RESULT'. Listing in the following example demonstrates the dynamic method call. ENDCLASS. The table columns are: • • • NAME of type c and length 30 for the name of the respective formal parameter in uppercase letters. p_in TYPE string DEFAULT 'DIRECTORY'. CLASS-METHODS main. p_meth TYPE string DEFAULT 'DIRECTORY_EXIST'. "TYPE-POOLS declares the data types and constants "of type group. this table must contain exactly one row for every nonoptional formal parameter and can contain exactly one row for every optional formal parameter. REPORT z_oop_methd09. KIND of type c of length 1 for the kind of the formal parameter (EXPORTING. "CL_GUI_FRONTEND_SERVICES class of the class library "contains methods for processing files PARAMETERS: p_class TYPE string DEFAULT 'CL_GUI_FRONTEND_SERVICES'. DATA: out_value parameter parameters error TYPE TYPE TYPE TYPE string. For ptab. abap_parmbind_tab.

"cl_abap_objectdescr is a global class.msg TYPE string. CATCH cx_sy_dyn_call_error INTO error. TRY. 213 . START-OF-SELECTION. MESSAGE msg TYPE 'I'. ENDMETHOD. parameter-kind = cl_abap_objectdescr=>returning. Following is the output of the above example. GET REFERENCE OF out_value INTO parameter-value. CONCATENATE 'Return Value: ' out_value INTO msg. parameter-name = p_out. provides "Runtime Type Services parameter-kind = cl_abap_objectdescr=>exporting. ENDTRY. lcl_example=>main( ). INSERT parameter INTO TABLE parameters. "set tabl components parameter-name = p_in. CALL METHOD (p_class)=>(p_meth) PARAMETER-TABLE parameters. INSERT parameter INTO TABLE parameters. ENDCLASS. GET REFERENCE OF p_value INTO parameter-value. MESSAGE error TYPE 'I' DISPLAY LIKE 'E'.

. CLASS lcl_example DEFINITION. DATA attr TYPE c LENGTH 20.. In classes with private instantiation. The syntax that controls the instantiation of a class is as follows: CLASS myclass DEFINITION CREATE PUBLIC|PROTECTED|PRIVAE.. Classes with protected instantiation allow the creation of objects in methods of subclasses.. If we don’t specify any value. the class can be publicly instantiated by default. ENDCLASS. REPORT z_oop_class02.. 214 . it is only the class itself that can create objects. where the CREATE OBJECT statement can be executed for that class. ENDCLASS... Publicly instantiated class allows any user to create objects. .Class Instantiation The addition CREATE defines the context in which class can be instantiated that is. In the following example the demo class is declared with private instantiation.. PUBLIC SECTION. CLASS lcl_demo DEFINITION CREATE PRIVATE.

METHOD main. METHODS show_speed. The handling of several objects via an internal table demonstrates the synthesis from the 4GL language ABAP and the OO language elements of ABAP Objects. CREATE OBJECT obj. Other OO languages such as Java do not provide any direct language elements that would solve the task shown here. obj->attr. START-OF-SELECTION. CLASS zcl_vehicle DEFINITION. obj->attr = 'ABAP Objects'. METHODS accelerate IMPORTING delta TYPE i. REPORT y_oop_minst. CLASS lcl_example IMPLEMENTATION. 215 . DATA obj TYPE REF TO lcl_demo.PUBLIC SECTION. ENDCLASS. On compilation the above code produces the following error. ENDCLASS. ENDMETHOD. PUBLIC SECTION. CLASS-METHODS main. Multiple Instantiation The example below shows how to manage any number of objects for the same class. PRIVATE SECTION. WRITE: 'Value of attr = '. lcl_example=>main( ).

CLASS lcl_demo IMPLEMENTATION. METHOD show_speed. speed = sy-index * 10. CREATE OBJECT vehicle. i. LOOP AT i_vtab INTO vehicle. PUBLIC SECTION. DATA: vehicle i_vtab n speed TYPE TYPE TYPE TYPE REF TO zcl_vehicle. CLASS zcl_vehicle IMPLEMENTATION. vehicle->show_speed( ). CLASS lcl_demo DEFINITION. output = speed. TABLE OF REF TO zcl_vehicle. i VALUE 5. ENDCLASS. METHOD accelerate. ENDMETHOD. ENDLOOP. speed = speed + delta. ENDCLASS. APPEND vehicle TO i_vtab. METHOD main. MESSAGE output TYPE 'I'. ENDMETHOD. CLASS-METHODS main. ENDCLASS. DO n TIMES. vehicle->accelerate( delta = speed ). ENDDO. 216 . ENDMETHOD.DATA speed TYPE i. ENDCLASS. DATA output TYPE string.

lcl_demo=>main( ). DATA speed TYPE i.START-OF-SELECTION. PRIVATE SECTION. CLASS lcl_vehicle DEFINITION CREATE PRIVATE. METHODS: accelerate IMPORTING delta TYPE i. Example below demonstrates the factory method. CLASS lcl_demo DEFINITION. and is often used to refer to any method whose main purpose is creation of objects. ENDCLASS. CLASS-METHODS create RETURNING value(ref) TYPE REF TO lcl_vehicle. The return value must "be passed by value with VALUE. 217 . show_speed. PUBLIC SECTION. "RETURNING defines a formal parameter ref "as a return value. Following is the output of above listing. Object Creation in a Factory Method Factory method is an OO design pattern. REPORT z_oop_facmthd.

The static type of me is "the class in which the instance method is "implemented me->speed = me->speed + delta. "me is an implicitly created local "reference variable. DATA output TYPE string. DATA veh_obj TYPE REF TO lcl_vehicle. ENDCLASS. CLASS lcl_vehicle IMPLEMENTATION. CREATE OBJECT ref. CLASS-METHODS main. METHOD show_speed. MESSAGE output TYPE 'I'. METHOD accelerate. ENDMETHOD. ENDMETHOD. METHOD main. ENDMETHOD. Following is the out put produced by the above code. 218 . output = me->speed. ENDMETHOD. "create the object and assign it to "veh_obj reference veh_obj = lcl_vehicle=>create( ). veh_obj->accelerate( delta = 100 ). which points to the "instance in which the method is currently "being executed. lcl_demo=>main( ). ENDCLASS. METHOD create. veh_obj->show_speed( ). START-OF-SELECTION. CLASS lcl_demo IMPLEMENTATION.PUBLIC SECTION. ENDCLASS.

. A class that grants friendship is not automatically a friend of its friends.... Following is the syntax. . 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. ENDCLASS. 219 . CLASS myclass DEFINITION CREATE PRIVAE FRIENDS c1... To do this we can use the concept of friendship between classes....... The friend of a super class is not automatically the friend of its subclasses... Inheritors of friends also become friends....... ... ENDCLASS.Friends Classes (Suspending Encapsulation) An external user can only access the public components of a class.. A friendship should be used when a class is used as a container of data.. however... storing the services of classes in specific service class (agents) and in test classes of ABAP Unit. Granted friendship is a one-side process. ........ classes must cooperate very closely so that they need to access the protected and private components of each other. However... in some cases. CLASS c1 DEFINITION. The FRIENDS must be specified as the last after the other additions.. the granting of friendship can not be inherited.

ENDMETHOD. PRIVATE SECTION. me->speed = me->speed + delta. PUBLIC SECTION. METHOD accelerate. 220 . METHOD create. METHODS: accelerate IMPORTING delta TYPE i. PUBLIC SECTION. ENDCLASS. CLASS lcl_vehicle IMPLEMENTATION. CLASS lcl_vehicle_agent DEFINITION DEFERRED. CLASS-METHODS create RETURNING value(ref) TYPE REF TO lcl_vehicle. PUBLIC SECTION. REPORT z_oop_friend. CLASS lcl_vehicle DEFINITION CREATE PRIVATE FRIENDS lcl_vehicle_agent. METHOD show_speed. CREATE OBJECT ref. ENDCLASS. ENDCLASS. CLASS-METHODS main. CLASS lcl_vehicle_agent IMPLEMENTATION. show_speed. DATA speed TYPE i.In listing below the lcl_vehicle_agent is service class which must be declared as a friend of lcl_vehicle class. CLASS lcl_example DEFINITION. CLASS lcl_vehicle_agent DEFINITION. ENDMETHOD. DATA output TYPE string. ENDCLASS.

those objects are deleted as well. ENDCLASS. The GC is called periodically by the ABAP runtime environment. METHOD main. If no reference variable points to the objects found in this process. ENDMETHOD. its references are traced by the GC. CLASS lcl_example IMPLEMENTATION. Following is the output of the above listing. '. if an object that is no longer referenced contains attributes of the reference variable type. 221 . WRITE: 'Vehicle Speed is: ENDMETHOD.output = me->speed. This means. This is because. The garbage collector or GC of the ABAP runtime environment is responsible for the delectation of objects. If we don’t publish the local class. If they are no longer needed. ENDCLASS. The GC deletes objects that are no longer referenced by reference variables. DATA veh_obj TYPE REF TO lcl_vehicle. If a local class is referred to within a class and the local class hasn’t been declared yet. lcl_example=>main( ). veh_obj = lcl_vehicle_agent=>create( ). Garbage Collection Objects occupy space in the main memory. It traces reference variables of deleted objects. the ABAP compiler compiles a program in one single process. START-OF-SELECTION. veh_obj->show_speed( ). they can and should be deleted. output. the FRIENDS addition would cause a syntax error due to an unknown class. it must be made known using local CLASS DEFINITION DEFERRED statement. veh_obj->accelerate( delta = 100 ).

Instance Constructor Instance Constructor is a predefined method of class called constructor. the methods of an object can be registered as event handlers or objects are managed or used by framework that can not be accessed directly. CLASS lcl_myclass IMPLEMENTATION. Constructors are used to put an object into a defined initial status. Other mechanisms that can cause references to objects to disappear are for example. As with all components of classes. event handlers must be deregistered and special methods of the frameworks must be called. This method is automatically executed once. METHODS constructor [IMPORTING I TYPE tye … ] ………………… ENDCLASS. the actual visibility is determined by where the class can be instantiated. always release unused objects for the GC and use Memory Inspector too to check if the garbage collection was successful. PUBLIC SECTIONS. METHOD constructor. Thus. we distinguish between instance constructors and static constructors. we should note that many references to objects can exists – that keep the objects alive. The syntax for instance constructor of local classes is: CLASS lcl_myclass DEFINITION CREATE PUBLIC|PROTECTED|PRIVATE. or a reference variable is a local variable of a method that is deleted when the method ends. The parameter interface of an instance constructor is limited to input parameters (IMPORTING). because the instance constructor is exclusively used to define an object status and is not supposed to provide any other behavior. memory leaks can occurs which may result in memory bottlenecks. Thus. Constructors A constructor is a special method that is executed automatically by the runtime environment. the original reference in the target variable is lost. It must be declared and implemented like a usual method. ………… 222 . immediately after the creation of an object of the class. Otherwise. To delete these kinds of references.We can explicitly initialize references to objects using the CLEAR statement. For example. when a reference is assigned. The instance constructor is required to be declared in the public visibility section. particularly if many objects or large objects are used. However. which is defined using the CREATE addition of CLASS DEFINITION. On the other hand. instance constructor serves to initialize individual instances.

PUBLIC SECTION. The following example shows the use of the instance constructor. If an exception occurs in an instance constructor. Each non-optional input parameter i must be linked to an actual parameter a via the = sign after EXPORTING. DATA: color TYPE string. ENDMETHOD. ENDCLASS. speed TYPE i. accelerate IMPORTING delta TYPE i. METHODS: constructor IMPORTING icolor TYPE string. ENDCLASS. show_speed. CLASS lcl_vehicle IMPLEMENTATION. and the corresponding reference variable is set to its initial value. me->color = icolor. CLASS lcl_vehicle DEFINITION.ENDMETHOD. we can select the Edit  Create Constructor function or the Constructor from application toolbar. the CREATE OBJECT statement contains an addition: CREATE OBJECT obj_ref EXPORTING i = a. METHOD constructor. To create the constructor for global classes. the created object will be deleted immediately during the execution of the CREATE OBJECT statement. PRIVATE SECTION. REPORT z_oop_inst_construct. To fill the input parameters of the instance constructor with values. "constructor 223 .

CLASS lcl_example IMPLEMENTATION. CREATE OBJECT: red_v EXPORTING icolor = 'Red'. CLASS-METHODS main. red_v->show_speed( ). me->speed = me->speed + delta. ENDCLASS. msg = me->speed. red_v->accelerate( 100 ). blue_v TYPE REF TO lcl_vehicle. 224 . ENDCLASS. lcl_example=>main( ). DATA: red_v TYPE REF TO lcl_vehicle. MESSAGE msg TYPE 'I'. ENDCLASS. green_v EXPORTING icolor = 'Green'. ENDMETHOD. green_v->show_speed( ). ENDMETHOD. START-OF-SELECTION. Following is the output of the above code listing. green_v->accelerate( 300 ). blue_v->accelerate( 200 ). PUBLIC SECTION.METHOD accelerate. METHOD show_speed. green_v TYPE REF TO lcl_vehicle. CONCATENATE me->color ':' msg INTO msg. blue_v EXPORTING icolor = 'Blue'. METHOD main. CLASS lcl_example DEFINITION. ENDMETHOD. DATA msg TYPE string. blue_v->show_speed( ).

ENDCLASS. CLASS lcl_myclass IMPLEMENTATION. This method is automatically executed once for each class in a program before the class is accessed for the first time. REPORT z_oop_static_construct. The static constructor must always be declared in the public visibility section of the class. CLASS lcl_vehicle_agent DEFINITION DEFERRED. To implement the static constructor for global classes we can select the Edit  Create Class Constructor function or the Class Constructor from application toolbar. ……………. CLASS lcl_vehicle DEFINITION CREATE PRIVATE FRIENDS lcl_vehicle_agent. We use the static constructor to apply the Singleton pattern. Following listing implements the static constructor. CLASS-METHOD class_constructor. ENDCLASS. ENDMETHOD. 225 . The static constructor is used to initialize the static attributes of a class. PUBLIC SECTION. METHOD class_constructor. The syntax for the static constructor of local classes is: CLASS lcl_myclass DEFINITION.Static Constructor The static constructor is a predefined method of a class called class_constructor. A static constructor does not have any parameter interface. …………….

ENDCLASS. ENDCLASS. CLASS-METHODS class_constructor. ENDCLASS. ENDMETHOD. CREATE OBJECT ref. MESSAGE msg TYPE 'I'. METHOD show_speed. DATA msg TYPE string. DATA speed TYPE i. PRIVATE SECTION. me->speed = me->speed + delta. CLASS lcl_vehicle_agent IMPLEMENTATION.PUBLIC SECTION. msg = me->speed. METHOD class_constructor. ENDCLASS. CLASS lcl_example IMPLEMENTATION. METHODS: accelerate IMPORTING delta TYPE i. PUBLIC SECTION. CLASS-METHODS main. CLASS lcl_vehicle IMPLEMENTATION. "class_constructor METHOD create. PUBLIC SECTION. METHOD main. CLASS lcl_example DEFINITION. ENDCLASS. ENDMETHOD. CLASS-DATA agent TYPE REF TO lcl_vehicle_agent READ-ONLY. 226 . show_speed. METHODS create RETURNING value(ref) TYPE REF TO lcl_vehicle. ENDMETHOD. ENDMETHOD. CLASS lcl_vehicle_agent DEFINITION CREATE PRIVATE. CREATE OBJECT lcl_vehicle_agent=>agent. METHOD accelerate.

which means it is generally not displayed as a single continues source code. ABAP Objects doesn’t provide any destructors for application development. In fact. For several reasons like performance. They are declared with the CLASS-POOL statement but as it is created with Class Builder (SE24) of ABAP Workbench.DATA: agent TYPE REF TO lcl_vehicle_agent. vehicle = agent->create( ). All the reusable code is programmed here. START-OF-SELECTION. Following is the output of the above example. 227 . for example. vehicle TYPE REF TO lcl_vehicle. ENDCLASS. vehicle->show_speed( ). A class pool is loaded into memory by using the global class. Local Declarations in Class Pool Class pool is a container for exactly one global class and more than one data types and local object types (local classes and interfaces). ENDMETHOD. vehicle->accelerate( 100 ). transaction concept etc. It is obvious that we can create local types. many OOP languages contain these kinds of methods. classes and interfaces in class pool. lcl_example=>main( ). Destructors Destructor is class method which is called when the object is deleted by the garbage collection. agent = lcl_vehicle_agent=>agent. local data and processing blocks other than the methods are not permitted. a public method of global class can be called from another ABAP program or it can be linked with a transaction code. however.

Private. 228 . We can use local classes to modularize a class pool beyond the methods of the global class. The local classes are declared in the same include program as local types. we can use the following special statement: CLASS global_class DEFINITION LOCAL FRIENDS …. If we want to access the protected and private components of global class. then check the checkbox named “Final”. The modularization of a global class through local classes of the class pool is a recommended procedure. To create a local class in a class pool. 1. This takes us to the ABAP Editor for an include program that is integrated in the global declaration part of the class pool. Select the appropriate class type. In class pool local classes play the same roles as the local classes in other ABAP programs. select GotoClasslocal TypesLocal Class implementations or Implementation from the application toolbar. we must also select GotoClass-local TypeLocal Class definitions/Types or Local Types and to implement the local classes. Abstract and Protected) and type of the class (normal ABAP Class). we must declare it as a local friend of the class. select GotoClass-local TypeLocal Class definitions/Types or Local Types from application toolbar in the class builder.. instantiation (like Public. This takes us to the ABAP Editor for an include program that is integrated in the implementation part of the class pool.To create a local type in a class pool. The following example demonstrates the use of local class in global class. Local types defined this way can be referenced only in private visibility section of the global declaration part of the global class. Here we can define program local types using TYPES statement. A pop up window appears asking for short description. 2. To do that. They are not visible from outside. If you don’t want to create any subclass of this class. local_class …… This statement does not have an associated ENDCLASS statement and can be contained in the include for the local class definition. Give a name and press create. Goto transaction SE24.

The transport request our package belongs to is already in the relevant field. Again Confirm it. Create Object Directory Entry dialog appears. Next dialog prompt for transport request.3. assign the package and click save to continue. When you create an object. the corresponding object directory entry is also created. 4. Now you will get the class builder screen. 229 . 5. The Object Directory is a directory of all the Repository Objects that make up the SAP System.

Click on methods tab. 8. 230 . select the Implementation option from application toolbar and enter the following lines of code. To implement the local class in class pool. Give a method name. Enter the following lines of code. level (Instance or Static). 7. protected or private ) and description. save and exit the editor.6. visibility (Public . From application toolbar select Local Types to define local class in the class pool.

9. Double click on method name and you will get an editor to perform the coding. Save and activate the global class. 11. 231 . To consume the global class create report Z_GLBL_CLIENT and enter the following code. Enter the following code. 10.

232 . Following output is produced after executing the above code.12.

. The relationship between a subclass and its superclass should always be expressed as “isa” relationship.. while more general classes are called superclasses. For example a hexagon is-a shape. according to this concept.. global class as a superclass in the Superclass field. 233 . inheritance relationships are represented by an inheritance tree.. Creating Subclasses Inheritance relationship can only be defined when a subclass is declared.. Only a subclass is aware that it is the heir/inheritor of another class. Then enter any non-final.. In object orientation. select Superclass on the Properties tab page. ABAP Objects implements the concept of simple inheritance. Derived or more specific classes are referred to as Subclass.. The root node of the inheritance tree in ABAP Objects is the predefined... All classes in ABAP Objects that do not explicitly inherit from another class are implicit direct subclasses of object. A superclass has no knowledge of any subclasses it may have. and create a hierarchy of classes.. In simple inheritance.. The Undo inheritance and Change inheritance options allow to change the inheritance relationship. ENDCLASS.Inheritance The inheritance mechanism for an OOP language provides options that help to reuse the same or similar parts of a class. inheritance refers to the specialization of classes by deriving subclasses (derived or child classes) from super classes (base class or parent class). When subclasses of explicitly defined classes are created. The syntax for deriving a subclass from a superclass is as follows: CLASS sub_class DEFINITION INHERITING FROM super_class. rather than inheritance of a class. Any non-final class that is visible at this point can be specified for super_class.. each class can have several subclasses but only one superclass. On the other hand the “has-a” relationship also called aggregation or composition is based on usage.. . these inherit the components of their superclasses and can add new components. To create a subclass in the Class Builder.. empty and abstract class object. For example a horse has-a halter..

show_speed. vtype TYPE string. me->vtype = ivtype. which means that any class without an INHERITING addition is automatically a direct subclass of the object root class.For each class that doesn’t have an explicit INHERITING FROM addition. "show_speed ENDCLASS. ENDCLASS. me->speed = me->speed + idelta. CLASS lcl_vehicle DEFINITION. PUBLIC SECTION. DATA: speed TYPE i. "accelerate METHOD show_speed. ENDMETHOD. "lcl_vehicle DEFINITION CLASS lcl_vehicle IMPLEMENTATION. ENDMETHOD. METHOD accelerate. WRITE msg. METHODS: accelerate IMPORTING ivtype TYPE string idelta TYPE i. the system implicitly adds the INHERITING FROM object addition. REPORT z_oop_inheritance. "lcl_vehicle IMPLEMENTATION 234 . PROTECTED SECTION. The example below two classes car and truck are derived from vehicle class. msg = me->speed. CONCATENATE vtype ' is travelling with speed = ' msg INTO msg. DATA msg TYPE string.

ENDCLASS. METHOD main. SKIP. PUBLIC SECTION. truck_ref->load( 'Gur' ). DATA: car_ref TYPE REF TO lcl_car. PROTECTED SECTION. truck_ref->accelerate( EXPORTING ivtype = 'Truck' idelta = 110 ). ENDCLASS. PUBLIC SECTION. CLEAR me->freight. CREATE OBJECT: car_ref. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. car_ref->accelerate( EXPORTING ivtype = 'Car' idelta = 130 ). ENDCLASS. me->freight. ENDMETHOD. DATA freight TYPE string. "lcl_car DEFINITIO CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle. car_ref->show_speed( ). me->freight. WRITE: 'Truck is loaded with'. truck_ref. me->freight = ifreight. CLASS-METHODS main. WRITE: 'Truck is uloaded'. METHOD load.CLASS lcl_car DEFINITION INHERITING FROM lcl_vehicle. "lcl_truck IMPLEMENTATION CLASS lcl_example DEFINITION. SKIP. "unload ENDCLASS. "load METHOD unload. ENDMETHOD. unload. METHODS: load IMPORTING ifreight TYPE string. 235 . "lcl_truck DEFINITIO CLASS lcl_truck IMPLEMENTATION. truck_ref TYPE REF TO lcl_truck.

lcl_car doesn’t require an implementation part. ENDMETHOD. The protected visibility section of a subclass contains all protected components of all superclass. Following is the output of the above code: Visibility Sections in Inheritance The public visibility section of a subclass contains all public components of all superclasses. truck_ref->unload( ). These components can be accessed externally using component selectors. "main ENDCLASS. protected is the same as private. SKIP. plus its own additional protected components. The private visibility section of subclass contains only the subclass’s own private components. but are not visible in the subclass. The lcl_truck class is specialized with an additional attribute for freight and additional methods for loading and unloading. "lcl_example IMPLEMENTATION START-OF-SELECTION. Since speed is declared in the PROTECTED SECTION. 236 . they inherit the attribute and methods of the lcl_vehicle class. These components cannot be accessed externally using component selectors. lcl_example=>main( ). Therefore. The private components are also inherited in principle. The lcl_car and lcl_truck classes both derived from lcl_vehicle. Since lcl_car class objects are the same as that of the lcl_vehicle class.truck_ref->show_speed( ). From an external point of view. These components can only be accessed in the method implementations of the subclass. plus its own additional public components. it is also visible in the subclasses. since no methods have been added.

which hides the previous implementation when the subclass and further subclasses are used. i. Like the methods belonging to the subclass. Every reference that refers to an object of the subclass uses the redefined method. since the main purpose of inheritance is to specialize classes. This ensures that only objects declared in the package interface of the package can be addressed from other transportable packages.A superclass is not aware of any subclasses it may have. The definition of parameter interface is not repeated. Therefore. 237 . A package interface can also contain development elements of a subpackage if they are included in a package interface of the subpackage. this become syntactically incorrect. However. methods are redefined with separate or changed parameter interface). because all this user ever sees is the constant interface (including documentation) and not the implementation itself. However. it is executed in the same way it was implemented in the superclass. which subclasses our class will eventually have other than those we define our self. Method Redefinition When a method is called in the subclass. To limit the subclasses of a class to at least the same package. it is only secure to add private components. If we then subsequently add new components to the public or protected section of our class. the behavior of the method of a superclass may be too general for the more specific purpose of the subclass. while in other instances. The syntax for redefining an instance method in a subclass is as follows: METHODS my_meth REDEFINITION. the implementation must be completely changed. Static methods can not be redefined. In some cases. we can never know as a developer. If we create a non-final class in a class library and release it for use. the implementation of superclass must be enhanced in the subclass. non-final classes should preferably be organized in packages for which the Package Check as Server property is activated.e. an additional implementation is created. Redefining methods means creating a new implementation of the method is a subclass without changing the interface (ABAP Objects doesn’t currently support method overloading. Instance methods can be redefined in subclasses to specialize the behavior of subclass objects. 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 semantics of the method must remain stable for the external user. When a method is redefined in a subclass. a redefined method accesses the private attributes of the subclass. A package interface is a subset of the visible development elements of a package that are visible externally. and any of its subclasses happen to have a component of its own with the same name.

Now we can navigate to the implementation in the same way as with normal methods. PROTECTED SECTION. "lcl_vehicle DEFINITION CLASS lcl_vehicle IMPLEMENTATION. This overrides the hiding of the redefined method. METHOD accelerate. 238 . show_speed. To do so. we must use the UtilitiesSettings function of the Class Builder to select the Display Inherited Components Also entry. PUBLIC SECTION. ENDMETHOD. We can now apply method redefinition to our previous example of inheritance. "show_speed "lcl_vehicle IMPLEMENTATION CLASS lcl_car DEFINITION INHERITING FROM lcl_vehicle. In the implementation of redefined method. we can use the pseudo reference (super->) to access the original method of the direct superclass. DATA msg TYPE string. METHODS: accelerate IMPORTING idelta TYPE i. Then. WRITE msg. CLASS lcl_vehicle DEFINITION. DATA: speed TYPE i. ENDMETHOD. me->speed = me->speed + idelta. msg = me->speed. "accelerate METHOD show_speed.In the Class Builder. REPORT z_oop_methd_redef. we must highlight the method and select the Redefine function. ENDCLASS. we redefine an inherited method by displaying it on the Methods tab. ENDCLASS. PUBLIC SECTION.

CONCATENATE 'Car. METHOD load. ENDMETHOD. PUBLIC SECTION. me->speed = lcl_truck=>max_speed. show_speed REDEFINITION. METHOD accelerate. "show_speed 239 . Speed: ' msg INTO msg RESPECTING BLANKS. DATA msg TYPE string. ENDCLASS. PRIVATE SECTION. msg = me->speed. IF me->speed > lcl_truck=>max_speed. msg = me->speed. WRITE msg. "show_speed ENDCLASS. WRITE msg. ENDMETHOD. "lcl_truck DEFINITIO CLASS lcl_truck IMPLEMENTATION. DATA msg TYPE string. METHOD show_speed. PROTECTED SECTION. unload. CONSTANTS max_speed TYPE i VALUE '80'. Speed: ' msg INTO msg RESPECTING BLANKS. ENDMETHOD. METHODS: accelerate REDEFINITION. ENDIF. "lcl_car DEFINITIO CLASS lcl_car IMPLEMENTATION. ENDCLASS. load IMPORTING ifreight TYPE string. super->accelerate( idelta ). DATA freight TYPE string. CONCATENATE 'Truck with ' me->freight '. "lcl_car IMPLEMENTATION CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle. "accelerate METHOD show_speed.METHODS show_speed REDEFINITION.

ENDCLASS. "lcl_example IMPLEMENTATION START-OF-SELECTION. car_ref->accelerate( 130 ). SKIP. CLEAR me->freight. Following is the out put of above listing. "unload ENDCLASS. me->freight. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. CLASS-METHODS main. PUBLIC SECTION. 240 . CREATE OBJECT: car_ref. DATA: car_ref TYPE REF TO lcl_car. truck_ref->unload( ). car_ref->show_speed( ). ENDMETHOD. METHOD main. "load METHOD unload. truck_ref TYPE REF TO lcl_truck. ENDMETHOD. truck_ref->accelerate( 110 ). truck_ref->load( 'Gur' ). lcl_example=>main( ). truck_ref. SKIP. ENDMETHOD. WRITE: 'Truck is uloaded'. "lcl_truck IMPLEMENTATION CLASS lcl_example DEFINITION.me->freight = ifreight. truck_ref->show_speed( ). "main ENDCLASS.

Concrete methods can call the abstract methods because the names and parameter interfaces are completely known. An abstract method can be defined as: METHODS my_meth ABSTRACT. An abstract method can’t be implemented in its own class. but only in a concrete subclass. Class that's not abstract is called a concrete class. In Class Builder. Abstract class can have both abstract and non-abstract methods.Abstract Classes and Methods An abstract class provides a common definition for a super class that multiple sub classes can share. ……………………… ENDCLASS. Derived class must implement all the abstract methods. The only difference to a real redefinition is that we can not use the pseudo reference (super->) in the method. The syntax for defining an abstract class is: CLASS my_class DEFINITION ABSTRACT. select Abstract in the Instantiation input field on the Properties tab as shown below: We can identify a method as an Abstract in Class Builder Detail View as: 241 . Abstract class can't be instantiated using CREATE OBJECT. The method implementation mechanism is same as we discussed in method redefinition section.

METHODS: accelerate IMPORTING idelta TYPE i. DATA msg TYPE string. ENDMETHOD. "lcl_vehicle DEFINITION CLASS lcl_vehicle IMPLEMENTATION. CONCATENATE 'Car speed is: ' msg INTO msg RESPECTING BLANKS. "lcl_vehicle IMPLEMENTATION CLASS lcl_car DEFINITION INHERITING FROM lcl_vehicle. METHOD show_speed.The previous example can be implemented in abstract class as: REPORT z_oop_abstract_cls. "lcl_car DEFINITIO CLASS lcl_car IMPLEMENTATION. "accelerate ENDCLASS. METHODS show_speed REDEFINITION. "lcl_car IMPLEMENTATION CLASS lcl_truck DEFINITION INHERITING FROM lcl_vehicle. PUBLIC SECTION. PUBLIC SECTION. 242 . ENDCLASS. msg = me->speed. PROTECTED SECTION. METHOD accelerate. ENDCLASS. me->speed = me->speed + idelta. DATA speed TYPE i. WRITE msg. PUBLIC SECTION. show_speed ABSTRACT. CLASS lcl_vehicle DEFINITION ABSTRACT. "show_speed ENDCLASS. ENDMETHOD.

DATA msg TYPE string. ENDMETHOD. speed: ' msg INTO msg RESPECTING BLANKS. unload. METHOD main. CLASS-METHODS main. msg = me->speed. ENDIF. super->accelerate( idelta ). DATA freight TYPE string. DATA: car_ref TYPE REF TO lcl_car. "load METHOD unload. "show_speed METHOD load. WRITE 'Truck is unloaded'. IF me->speed > lcl_truck=>max_speed. show_speed REDEFINITION. METHOD accelerate. WRITE msg. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. PROTECTED SECTION. load IMPORTING freight TYPE string. "lcl_truck IMPLEMENTATION CLASS lcl_example DEFINITION.METHODS: accelerate REDEFINITION. me->speed = lcl_truck=>max_speed. truck_ref->load( 'Potato' ). truck_ref TYPE REF TO lcl_truck. truck_ref. PUBLIC SECTION. SKIP. CREATE OBJECT: car_ref. 243 . "lcl_truck DEFINITIO CLASS lcl_truck IMPLEMENTATION. "accelerate METHOD show_speed. ENDMETHOD. "unload ENDCLASS. ENDCLASS. CONCATENATE 'Truck with ' me->freight '. CLEAR me->freight. CONSTANTS max_speed TYPE i VALUE '80'. ENDMETHOD. car_ref->show_speed( ). me->freight = freight. ENDMETHOD. car_ref->accelerate( 130 ). ENDCLASS. PRIVATE SECTION.

244 . individual instance methods can be declared as final.truck_ref->accelerate( 110 ). The syntax for defining a final class is: CLASS my_class DEFINITION FINAL. ……………………… ENDCLASS. truck_ref->show_speed( ). SKIP. "lcl_example IMPLEMENTATION START-OF-SELECTION. "main ENDCLASS. Final Classes and Methods A class or instance method can be declared as final to protect it from uncontrolled specialization. lcl_example=>main( ). Following is the output of the above code. Methods of a final class are implicitly final and cannot be explicitly declared as final. truck_ref->unload( ). In the Class Builder. The syntax is: METHODS my_meth FINAL. ENDMETHOD. In a non-final class. we can create a final class by selecting the Final checkbox on the Properties tab.

In the Class Builder. Changes to the value are visible in all relevant classes. because static components should occur exactly one in a inheritance path so that the can be shared by all subclasses. A class can be abstract and final at the same time. REPORT z_oop_inhrt_static. but to a path of the inheritance tree. we can identify an instance method as Final in the Detail View. "lcl_myclass1 DEFINITION 245 . Static Attributes and Methods in Inheritance A subclass can access the contents of the public and protected static attributes of all superclasses or a superclass shares it’s public and protected static attributes with all subclasses. If a static attribute is addressed via the class name of a subclass but declared in a superclass. CLASS lcl_myclass1 DEFINITION. static attributes in inheritance are not assigned to a single class. PUBLIC SECTION. A final method can’t be abstract at the same time. Therefore. ENDCLASS. Although we can declare instance components in such a class. but only its static components are usable in this case. or from inside in all affected classes where a static attribute is visible. A static constructor is executed when a class is addressed for the first time. only the static constructor of the superclass is executed. Static methods can’t be redefined in ABAP Objects. Static attributes can be accessed from outside via class component selector (=>) using all class names involved. Listing below shows a simple example. it is not recommended. A final method can’t be redefined in subclasses. CLASS-DATA attr TYPE string.

ENDCLASS. Because a subclass inherits all attributes of its superclasses in inheritance. After execution the following message box is displayed. To avoid naming conflicts. CLASS-METHODS main. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. Constructors in Inheritance Instance constructor is used to set the instance attributes of every single object during instancing process. ENDCLASS. "lcl_example IMPLEMENTATION START-OF-SELECTION.CLASS lcl_myclass2 DEFINITION INHERITING FROM lcl_myclass1. instance constructor deviate from the rule that there are only unique components names along the path of the inheritance tree. ENDMETHOD. MESSAGE lcl_myclass1=>attr TYPE 'I'. "lcl_myclass2 DEFINITIO CLASS lcl_example DEFINITION. PUBLIC SECTION. lcl_example=>main( ). the instance constructors of the individual classes of an inheritance tree must be completely independent of one another. Thus. the following rules apply: 246 . Consequently. the static constructor are is responsible for the static attributes of the class before the class is first accessed. "main ENDCLASS. this automatically begs the question “How can the constructors ensure that the inherited attributes are initialized as well when the subclass is used?” Instance Constructors Every class has a predefined instance constructor named constructor. METHOD main. lcl_myclass2=>attr = 'Static attributes demo'.

It automatically ensures that the instance constructor of the next higher superclass is called.• • Instance constructors of superclasses cannot be redefined in subclasses. The methods of subclasses are not visible in constructors. access to instance attributes only …………………………………………. object. REPORT z_oop_inhrt_constuctr. The only exceptions to this rule are the direct subclasses of the root node. and not the possibly redefined method of the subclass to be instantiated. *which is again divided in three phases if implemented super->constructor EXPORTING …. The execution of a subclass instance constructor can be divided into three phases that are presented in the comment lines of listing below. CLASS lcl_vessel DEFINITION. of the instance constructor of the direct superclass. even if the constructor is not explicitly declared. ENDMETHOD. If an instance constructor calls an instance method of the same class via the implicit self-reference (me). the instance constructor of every subclass must contain a call super->constructor( … ). *Phase-1: Access to static attributes only …………………………………………. METHOD constructor. A subclass must ensure that the instance constructors of all superclasses are executed as well. PUBLIC SECTION. the method is called in the way in which it is implemented in the class of the instance constructor. *Phase-3: Attributes of superclass are correctly *initialized. the implicitly existing implementation of the instance constructor is run. In superclasses in which the instance constructor is not explicitly declared and implemented. For this purpose. Listing below shows the behavior of instance constructors in inheritance using a simple example. 247 . METHODS constructor IMPORTING iname TYPE string. Instance constructors cannot be explicitly called via the constructor ( ) statement. *Phase-2: Execution of super class constructor(s). PROTECTED SECTION.

248 . METHOD constructor. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. DATA: obj_vessel TYPE REF TO lcl_vessel. WRITE: / 'lcl_vessel:constructor. "lcl_motorship IMPLEMENTATION CLASS lcl_example DEFINITION. METHOD main. "lcl_vessel IMPLEMENTATION CLASS lcl_ship DEFINITION INHERITING FROM lcl_vessel. ENDMETHOD. METHOD constructor. "constructor ENDCLASS. obj_ship TYPE REF TO lcl_ship. fuelamount. PUBLIC SECTION. "lcl_vessel DEFINITION CLASS lcl_vessel IMPLEMENTATION. ENDCLASS. name. name '. "constructor ENDCLASS. PRIVATE SECTION. CLASS-METHODS main. ENDCLASS. SKIP. METHODS constructor IMPORTING iname TYPE string ifuelamount TYPE i.DATA name TYPE string. ENDMETHOD. ' fuelamount '. obj_motoship TYPE REF TO lcl_motorship. super->constructor( iname ). ENDCLASS. fuelamount = ifuelamount. CREATE OBJECT obj_vessel EXPORTING iname = 'Ghata Khistay'. WRITE 'Creating Vessel Object' COLOR 5. "lcl_ship DEFINTION CLASS lcl_motorship DEFINITION INHERITING FROM lcl_ship. WRITE: / 'lcl_motorship:constructor. DATA fuelamount TYPE i. ENDCLASS. name='. name. "lcl_motorship DEFINITIO CLASS lcl_motorship IMPLEMENTATION. name = iname. PUBLIC SECTION.

EXPORTING iname = 'Rakotay Khistay' ifuelamount = 400. "main "lcl_example IMPLEMENTATION Following is the output of the above example. CREATE OBJECT obj_ship EXPORTING iname = 'Khistay'. when a subclass is addressed for the first time. SKIP. SKIP. START-OF-SELECTION. CREATE OBJECT obj_motoship ENDMETHOD. When a subclass is addressed for the first time in a program. ENDCLASS. lcl_example=>main( ). Before that.WRITE / 'Creating Ship Object' COLOR 5. the preceding static constructors of the entire inheritance tree must have been run. the next higher superclass is searched whose static constructor has not yet run. Static Constructors Every class has a static constructor named class_constructor. its static constructor is run. Then this static 249 . Because a static constructor should be called only once during the execution of a program. Along an inheritance tree the same rules that apply to the instance constructor also apply to the static constructor. WRITE / 'Creating Motoship Object' COLOR 5. however.

ENDMETHOD. ENDCLASS. CLASS-DATA fuelamount TYPE i. CLASS-METHODS main. note the difference between the output of both examples. fuelamount '. "constructor ENDCLASS.constructor is executed first. "constructor ENDCLASS. we can always assume that the static attributes of the superclasses have been correctly initialized. PUBLIC SECTION. fuelamount. ENDMETHOD. "lcl_motorship DEFINITIO CLASS lcl_motorship IMPLEMENTATION. name = 'Rakotay Khistay'. ENDCLASS. '. the runtime environment automatically ensures that the static constructors are called in the correct order. CLASS-METHODS class_constructor. "lcl_vessel IMPLEMENTATION CLASS lcl_ship DEFINITION INHERITING FROM lcl_vessel. PUBLIC SECTION. REPORT z_oop_inhrt_constuctr_static. CLASS-METHODS class_constructor. PUBLIC SECTION. a static constructor does not have to explicitly call the static constructor of its superclass. CLASS lcl_vessel DEFINITION. ENDCLASS. "lcl_vessel DEFINITION CLASS lcl_vessel IMPLEMENTATION. fuelamount = 100. In contrast to instance constructors. "lcl_ship DEFINTION CLASS lcl_motorship DEFINITION INHERITING FROM lcl_ship. name = 'Ghata Khistay'. WRITE: / 'lcl_vessel:class_constructor. name= '. name='. METHOD class_constructor. ENDCLASS. METHOD class_constructor. Note that the static constructors are parameter less. In a subclass. name. Instead. name. "lcl_example DEFINITION 250 . WRITE: / 'lcl_motorship:class_constructor. CLASS-DATA name TYPE string. The previous example is repeated with the use of static constructors. followed by the constructors of all subclasses up to and including the addressed subclass. "lcl_motorship IMPLEMENTATION CLASS lcl_example DEFINITION.

CREATE OBJECT obj_ship. METHOD main. CREATE OBJECT obj_vessel. WRITE / 'Motoship Class' COLOR 5. ENDMETHOD. where the initialization of the superclass attributes is ensured by calling the superclass constructors. ENDCLASS. this results in three scenarios whose behavior is defined in ABAP Objects as follows: 251 . The additions CREATE PUBLIC|PROTECTED|PRIVATE of the CLASS statement or the corresponding Class Builder settings. obj_ship TYPE REF TO lcl_ship. WRITE 'Vessel Class' COLOR 5. DATA: obj_vessel TYPE REF TO lcl_vessel. "main "lcl_example IMPLEMENTATION Following is the output. SKIP. control for each class who can create an instance of the class or call its instance constructor. respectively. Instantiation in Inheritance The instantiation of subclass means the instantiation of all superclasses in a single object. CREATE OBJECT obj_motorship. SKIP. lcl_example=>main( ). SKIP. In inheritance. START-OF-SELECTION.CLASS lcl_example IMPLEMENTATION. obj_motorship TYPE REF TO lcl_motorship. WRITE / 'Ship Class' COLOR 5.

the subclass cannot be instantiated. and a subclass can’t even instantiate itself because it doesn’t have access to the instance constructor of the superclass. no subclass can be instantiated by external users. CREATE NONE. If the instantiatiability of a subclass can be explicitly specified in one of the three ways. The instantiatiability of a subclass can be explicitly specified in one of the three ways. the subclass has an implicit addition. because only the superclass itself can call its instance constructor. Therefore. 252 . Thus. Superclass with Protected Instantiation: The instance constructor of the superclass is visible in subclasses. The instantiatiability if the subclass cannot be explicitly specified because this would mean a publication oft the superclass constructor in the specified section. Superclass with Private Instantiation: The instance constructor of the superclass is visible only in the superclass. As a friend. Exception from this rule only exist if a privately instantiatable superclass offers its friendship to its subclasses. There are two different scenarios here: o The subclass is not a friend of the superclass.• • • Superclass with Public Instantiation: The instance constructor of the superclass is publicaly visible. a subclass can publish the private constructor of the superclass in the specified section. it inherits the private instantiation of the superclass. 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. The instantiatiability of a subclass can be explicitly specified in one of three ways. o The subclass is a friend of the superclass. If a superclass with private instantiation has been defined in a path of the inheritance tree. a class defined for private instantiation should be marked final to prevent subclasses. if the instantiatiability of the subclass has not been explicitly specified. If the instantiatiability of a subclass is not explicitly it inherits the protected instantiation of the superclass. A subclass can control the visibility of its own instance constructor independently of the superclass.

. The syntax for declaring a local interface is: INTERFACE lif_name. These can point to objects of all classes that contain the respective standalone interface..... which is not possible in abstract classes because static methods can not be redefined. it can be addressed via this interface. CLASS-METHODS . With the exception. all classes that want to use an interface must implement its methods.. The actual functionality of a BAdI is provided only in follow-up systems by implementing the standalone interface in classes.. Because. If a class implements a standalone interface. We can not directly create objects of interfaces similar to abstract classes... we distinguish global and local interfaces in the same way that we do global and local classes. Interfaces are used to achieve a decoupling between a class and a user. A very nice application example of this decoupling is given by the enhancebility of delivered ABAP application programs in customer systems using Business Add-Ins (BAdIs). CLASS-DATA . METHODS . however.. ENDINTERFACE. 253 . Therefore. BAdIs are based on standalone interfaces that are declared in the original system. .. DATA ….. There are specific interface reference variables for this purpose. that we can also define static methods without implementation. Unlike classes... Local interfaces can only be used in the same program. Creating Interfaces The declaration of interfaces hardly varies from the declaration of a class. interfaces don’t need to be divided into different visibility sections because interface components has by default public visibility.... Interface can contain exactly the same components as classes. the same rules apply regarding their usability.Interfaces Interfaces or standalone interfaces are like a 100% abstract superclass that defines the methods a subclass must implement. their objects can be addressed via the same interface reference variable.. any classes can implement the same interface.. Methods of interface are all abstract. The local interface should be prefixed with lif_ ... Global interfaces can be used in any program if the package assignment of the program permits it. Like the subclasses that implement the abstract methods of their abstract superclasses. As with classes..

The Class Builder generates the corresponding ABAP statements in an interface pool. it cannot contain any local type declarations except for the publication of type groups. The global interface should be prefixed with if_ .To create a global interface. an event handler. An interface pool is a container for exactly one global interface. To create components we need to specify the same input as we do for classes. the source code of which can also be edited directly via GotoInterface Section. use the Class Builder just as we would for global classes. In the shown screenshot. Figure below shows the Class Builder for a global interface. except for the assignment to a visibility section. etc. 254 . The Method Type specifies whether the method is a normal method. a constructor. we created the methods ACCELERATE and SHOW_SPPED.

the usage of the interface must be permitted by the package assignment.. ………………………………. The character (!) is escape character that can be written directly before a name in order to distinguish it from an ABAP keyword of the same name in a statement.. The essential requirement for implementing an interface is that the interface is known to the implementing class. Only global interfaces can be integrated in the public visibility section of a class.There is no implementation part of an interface Therefore. ……………………. PUBLIC SECTION. it must be declared globally in the class library or locally in the same program. ENDCLASS. intf2 . Additionally. it is not necessary to add the DEFINITION to INTERFACE. In Class Builder we can do this on the Interfaces tab in the Change Class window. The syntax for integrating the interface is: CLASS lcl_my_class DEFINITION. INTERFACES: intf1. Implementing Interfaces A class can implement one or more interfaces. Therefore. 255 .

this is expressed by the optional addition ALL METHODS ABSTRACT|FINAL. Implementing an interface extends the public interface (section) of the class by the interface components. Other 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. In the INTERFACES statement. Example below demonstrates the usage of interface reference variables. The interface component selector should only be used within classes and interfaces. The interface reference variable only knows its own interface components. we can specify that all methods of the interface should be either abstract or final in the class. 256 . the interface components of an object obj as follows: obj->intf~comp. we can create the object of the class via an interface reference variable as: CREATE OBJECT intf_ref TYPE lcl_cls. intf_ref = lcl_cls. This mechanism is known as upcast.In the Abstract and Final columns. The prefix intf~ is helpful in avoiding the naming conflicts when a class has its own component of the same name like an interface component. however. We might be tempted to address. we must use the reference variables that are declared with a reference to an interface: DATA intf_ref TYPE REF TO lif_interf. To access the interface components of objects. By simply assigning a class reference variable (pointing to an object) to an interface reference variable enable us to access the interface components. In point of fact. If we are only interested in the interface components of a class. this kind of access is not recommended. An interface reference variable intf_ref can point to the objects of all classes implementing the lif_interf interface. this work. Every component comp of an implemented interface intf becomes a full component of the class and is identified within the class via the name … intf~comp … The tilde sign (~) is the interface component selector.

INTERFACE lif_drive_object. PRIVATE SECTION. "lcl_electron DEFINITION CLASS lcl_electron IMPLEMENTATION. CONSTANTS c TYPE i VALUE 300000. CONCATENATE 'Vehicle Speed: ' msg INTO msg. "lcl_electron IMPLEMENTATION CLASS lcl_example DEFINITION. CONCATENATE 'Electron Speed/C: ' msg INTO msg. msg = me->speed_over_c. speed = speed + idelta. METHOD lif_drive_object~accelerate. ENDMETHOD. PRIVATE SECTION. msg = speed. ENDCLASS. "lif_drive_object~accelerate METHOD lif_drive_object~show_speed. "lif_drive_object~show_speed ENDCLASS. INTERFACES: lif_drive_object. ENDMETHOD. ENDINTERFACE. ENDMETHOD. "lif_drive_object CLASS lcl_vehicle DEFINITION. ENDMETHOD. PRIVATE SECTION. DATA msg TYPE string. me->speed_over_c = me->speed_over_c + idelta / c. 257 . PUBLIC SECTION. DATA speed TYPE i. "lcl_vehicle DEFINITION CLASS lcl_vehicle IMPLEMENTATION.REPORT z_interface01. PUBLIC SECTION. WRITE / msg. METHODS: accelerate IMPORTING idelta TYPE i. METHOD lif_drive_object~accelerate. show_speed. "lif_drive_object~accelerate METHOD lif_drive_object~show_speed. "lif_drive_object~show_speed ENDCLASS. INTERFACES: lif_drive_object. DATA msg TYPE string. WRITE / msg. CLASS-METHODS main. ENDCLASS. DATA speed_over_c TYPE p DECIMALS 3. PUBLIC SECTION. "lcl_vehicle IMPLEMENTATION CLASS lcl_electron DEFINITION.

"upcaseting iref = veh_ref. "lcl_example IMPLEMENTATION START-OF-SELECTION. "msg METHOD main. CREATE OBJECT iref TYPE lcl_electron. ENDCLASS. The output of the above code listing is shown below: 258 . lcl_example=>main( ). iref->accelerate( 250000 ). iref LIKE LINE OF if_tab. ENDMETHOD. lcl_example=>show_msg( if_tab ). irf->show_speed( ). CREATE OBJECT veh_ref TYPE lcl_vehicle. veh_ref TYPE REF TO lcl_vehicle. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. APPEND iref TO if_tab. ENDLOOP. DATA: if_tab TYPE tab_intref. ENDMETHOD. SKIP. iref->accelerate( 100 ). APPEND iref TO if_tab. DATA irf LIKE LINE OF itab_iref.TYPES tab_intref TYPE TABLE OF REF TO lif_drive_object. "lcl_example ENDCLASS. CLASS-METHODS show_msg IMPORTING itab_iref TYPE tab_intref. LOOP AT itab_iref INTO irf. METHOD show_msg.

CONSTANTS att TYPE string VALUE 'Constant attribute of interfac e'. Following is the output of the above example. we would have to use the name of an implementing class and the interface component selector: class_name=>intf~comp. PUBLIC SECTION. INTERFACE lif_f1. ENDINTERFACE. "lcl_example IMPLEMENTATION START-OF-SELECTION. "main ENDCLASS. interfaces: lif_f1. ENDMETHOD. PUBLIC SECTION. independently of the instance. intf =>const_attr. we can only use the interface name to access the constants. 259 . "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. "lcl_c1 DEFINITION CLASS lcl_example DEFINITION. lcl_example=>main( ). "if_f1 CLASS lcl_c1 DEFINITION. Example below demonstrates the constants declared in an interface. To access the static components of interfaces.As far as the static components of interface are concerned. The static attributes have different values depending on the class and the static methods can be differently implemented in every class. WRITE lcl_c1=>lif_f1~att. REPORT z_interface02. METHOD main. CLASS-METHODS main. ENDCLASS. ENDCLASS. WRITE lif_f1=>att. SKIP.

INTERFACES: lif_interface1. 260 . Now the interface lif_name integrates additional interfaces (interface1. …) and are composed of its own components plus the components of the integrated interfaces. Consider the example: INTERFACE lif_interface1. INTERFACES: lif_interface1 … ……. In Class Builder we can compose other interface on the Interfaces tab.Composite and Component Interfaces The INTERFACES statement cannot only be used in classes but also in the declaration of an interface. The composition of interfaces can be useful when modeling complex applications... This mechanism allows us to compose several interfaces into one interface. lif_interface2 … ……. ……………… ENDINTERFACE. Note: All component interface of a composite interface are on the same level. interface2. … ………………………………………… ENDINTERFACE. interface2. A nesting of names like intterface3~interface2~interface2 is not possible. Following is the syntax: INTERFACE lif_name. An interface integrated in another interface is called a component interface. INTERFACES: intrface1.. INTERFACE lif_interface2. An interface containing at least one other interface is called composite or nested interface. ENDINTERFACE. INTERFACE lif_interface3.

. METHOD lif_interface3~meth. ENDINTERFACE. ENDCLASS. CLASS lcl_demo DEFINITION. PUBLIC SECTION. all interface components of the interface behave as if their interface had been implemented only once.. ENDINTERFACE. Consider the next example: INTERFACE lif_interface1. INTERFACES lif_interface4.. it only occurs once. In lif_interface3. INTERFACES: lif_interface2. INTERFACE lif_interface3.. even if it was not integrated directly. . In the example above the component interface lif_interface1 of the composite interface lif_interface2 becomes a component interface of lif_interface3. INTERFACE lif_interface2. 261 . . INTERFACES lif_interface1.. lif_interface3.. METHODS meth.. ENDINTERFACE. Because every interface is included exactly once in a composite interface.. METHODS meth. METHOD lif_interface2~meth.ENDINTERFACE. ENDINTERFACE.. METHOD lif_interface1~meth. If a composite interface is implemented in a class. A composite interface contains each component interface exactly once. Although lif_interface1 is integrated in lif_interface3 both directly as a component interface of lif_interface3 and indirectly via lif_interface2.. CLASS lcl_demo IMPLEMENTATION. ENDMETHOD. INTERFACE lif_interface4. naming conflicts cannot occur.. ENDMETHOD. it can be addressed under the name lif_interface1. INTERFACES lif_interface1. METHODS meth.. The way an implemented interface is composed is irrelevant when it is implemented in a class.

. ENDMETHOD. ENDCLASS. because the compiler always ensures for a class as well as in composite interfaces that every component exists only once. we can define an alias name at the level at which the interface is integrated using the INTERFACES statement: ALIASES name FOR intf~comp. the components and the implementation part of the class do not change at all. This can be achieved through upcasting.. In the Class Builder we can enter alias names for classes and for interfaces in the Aliases tab. The interface component selector should not be used for this purpose. the interface components should be accessed using interface reference variable of the type of the appropriate component interface. Alias Names The complete name of a component that is added via an interface to a class or another interface is intf~comp... If the class implements a composite interface. it can be used in a composite interface to make the components of component interfaces as accessible as native components via aliasing. The lif_interface~meth method is implemented only once... For this name. although it occurs in two interfaces . The composition of the interfaces does not play any role. A method meth of the same name is declared in three individual interfaces and thus implemented in three different ways using the interface component selector. however. lif_interface2 or lif_interface3) in addition to lif_interface4 in the declaration part of the lcl_demo.. 262 . If we list one or more of other interfaces (lif_interface1. 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. lif_interface2 and lif_interface3.

"lcl_vehicle DEFINITION CLASS lcl_vehicle IMPLEMENTATION. Listing below shows the usage of alias names. ENDCLASS. ALIASES accelerate FOR lif_drive_object~accelerate. "lif_drive_object~show_speed ENDCLASS. WRITE / msg. CONSTANTS c TYPE i VALUE 300000. PUBLIC SECTION. 263 . INTERFACE lif_drive_object. DATA msg TYPE string. DATA msg TYPE string. speed = speed + idelta. "instead of "METHOD lif_drive_object~accelerate. INTERFACES: lif_drive_object. "lcl_vehicle IMPLEMENTATION CLASS lcl_electron DEFINITION. "lif_drive_object CLASS lcl_vehicle DEFINITION. alias names belong to the namespace of the components of a class and must be assigned to a visibility section just like the other components. "lcl_electron DEFINITION CLASS lcl_electron IMPLEMENTATION. METHOD lif_drive_object~accelerate. CONCATENATE 'Vehicle Speed: ' msg INTO msg. ENDINTERFACE. show_speed. ENDMETHOD. ENDCLASS. 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. PRIVATE SECTION. INTERFACES: lif_drive_object. ENDMETHOD. me->speed_over_c = me->speed_over_c + idelta / c.In classes. msg = speed. DATA speed TYPE i. PRIVATE SECTION. METHOD accelerate. REPORT z_interface03. "lif_drive_object~accelerate METHOD lif_drive_object~show_speed. PUBLIC SECTION. DATA speed_over_c TYPE p DECIMALS 3. ENDMETHOD. "lif_drive_object~accelerate METHOD lif_drive_object~show_speed. METHODS: accelerate IMPORTING idelta TYPE i.

CREATE OBJECT veh_ref. "lcl_example ENDCLASS. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. CLASS-METHODS show_msg IMPORTING itab_iref TYPE tab_intref. APPEND irf_ref TO irf_tab. WRITE / msg. ele_ref TYPE REF TO lcl_electron. veh_ref TYPE REF TO lcl_vehicle. "msg METHOD main. ENDMETHOD. "lif_drive_object~show_speed ENDCLASS. irf_ref->accelerate( 100 ). SKIP. create OBJECT ele_ref.msg = me->speed_over_c. "lcl_electron IMPLEMENTATION CLASS lcl_example DEFINITION. METHOD show_msg. CONCATENATE 'Electron Speed/C: ' msg INTO msg. irf_ref = veh_ref. ENDCLASS. ENDMETHOD. The interface method is implemented in the class via its alias name and called by a user like a direct method of the class. irf_ref LIKE LINE OF irf_tab. DATA: irf_tab TYPE tab_intref. 264 . PUBLIC SECTION. DATA irf LIKE LINE OF itab_iref. irf->show_speed( ). lcl_example=>show_msg( irf_tab ). TYPES tab_intref TYPE TABLE OF REF TO lif_drive_object. lcl_example=>main( ). Following is the output of the above code listing. PRIVATE SECTION. irf_ref = ele_ref. ENDMETHOD. LOOP AT itab_iref INTO irf. ENDLOOP. a class can publish its interface components as class-specific components. Thus using alias names. CLASS-METHODS main. irf_ref->accelerate( 200 ). APPEND irf_ref to irf_tab. "lcl_example IMPLEMENTATION START-OF-SELECTION.

alias names provide the only means of addressing those components that would otherwise not be available in the composite interface. this would not be possible because the name intf2~intf1~m1 is not permitted. INTERFACE intf3. because names can not be concatenated in composite interfaces. INTERFACE intf2. but at the same time. METHODS meth1. ENDINTERFACE. The intf3 interface can use the alias name meth1 in intf2 to address the meth1 component of the intf1 interface in its own ALIASES statement. the access would look as follows: iref->intf1~meth1( ). Without alias names in intf3. Interfaces and Inheritance The usage of inheritance always makes sense when different classes have generalization/specialization relationship. this causes a very tight coupling (dependency) between superclass and subclasses. The advantage of inheritance is that the subclasses reuse all properties already programmed in the superclass.Note. INTERFACES intf1. ALIASES meth1 FOR intf2~meth1. Without alias names in intf2. ENDINTERFACE. 265 . For example: INTERFACE intf1. ALIASES meth1 FOR intf1~meth1. INTERFACES intf2. Now the user of intf3 can accesses the component meth1 in intf1 as: iref->meth1( ). ENDINTERFACE.

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

The actual meaning of the golden rule for the two possible types of reference variables in ABAP Objects is: 267 . The static type is fixed during entire runtime of the program. parameter transfers or via CREATE OBJECT statement as: CREATE OBJECT obj_ref TYPE class. “The static type always more general or equal to the dynamic type”. However. From an object-oriented perspective. The syntax check and the ABAP runtime environment ensure that this rule is never broken.e. The static type of an object reference variable is the type that is specified after the TYPE REF TO addition in declaration as: DATA obj_ref TYPE REF TO class|interface. notice that we haven’t said anything about how these components are implemented. From an object-oriented perspective. it is technically possible for an object reference variable to point to an object that is not an instance of the class type used to define the object reference. the static and dynamic type of an object reference variable will be the same as: CREATE OBJECT obj_ref. this means that we can swap out a given object for another so long as they share the same interface. we can create generic methods. Here. we need to be able to perform type casts and dynamic method calls. The basic concept here is to adopt a component-based architecture where each component clearly defines the services (i. According to the golden rule of reference variables. An object reference variable also has a dynamic type associated with it. In a polymorphic design. Here dynamic type will be similar to static type of obj_ref. These interfaces make it easy for components to be weaved together into larger assemblies. the term is used to describe a language feature that allows you to use instances of classes belonging to the same inheritance hierarchy interchangeably. we are talking about its static type. The reference variable usually receives its dynamic type via assignment. Normally. As long as the components implement the services described in their interface – it really doesn’t matter how they are implemented. This generic approach to programming is often described using the term design by interface. The dynamic type of an object reference variable is the class of the object to which the object reference variable is currently pointing. interface) they provide. whenever we talk about the type of an object reference variable in ABAP Objects. In order to do so.Polymorphism The term polymorphism literally means “many forms”. Type Casting and Dynamic Binding Most of the time.

we are using the TYPE addition to the CREATE OBJECT statement to create an instance of class lcl_lion and assign its reference to the ref_lion object 268 .g. TYPE REF TO lcl_lion.g. For an interface variable. This kind of assignment is not possible without a type cast. ref_animal = ref_lion.g.. the ABAP runtime environment will use the dynamic type information to bind the method call with the implementation provided in the lcl_lion class. The opposite of narrowing cast is widening cast (or downcast) likes this: DATA: ref_animal ref_lion TYPE REF TO lcl_animal. The type cast above is classified as a narrowing cast (or upcast) as we are narrowing the access scope of the referenced lcl_lion object to the components defined in the lcl_animal superclass. An up cast assignment can be performed using the equal sign (=) or the MOVE TO statement. superclass) ones and thus we can only move upwards in the inheritance tree. notice how we are assigning an instance of the lcl_lion subclass to the ref_animal object reference variable (whose static type is the parent class lcl_animal) in the code excerpt below. at runtime. For example. when a method call such as “ref_animal->hungry( )” is called. CREATE OBJECT ref_animal TYPE lcl_lion. the source and target object reference variables must be compatible (e.• • For a class reference variable. CREATE OBJECT ref_lion. In the example above. Therefore. subclass) to equal or more general (e. DATA: ref_animal ref_lion TYPE REF TO lcl_animal. particularly even a subclass of such a class. once the assignment is completed. their static types must belong to the same inheritance hierarchy). the dynamic type can be the same class or one of its subclasses. In this case. In upcast we only assign more specific reference variables (e. the static type is an interface. CREATE OBJECT ref_animal. We can’t perform a type cast using just any class. the static type is a class. the dynamic type of the ref_animal reference variable will be the lcl_lion class. TYPE REF TO lcl_lion. The dynamic type can be any class implementing the interface. ref_lion ?= ref_animal.

METHOD hungry. ENDMETHOD. which can be handed in a TRY control structure. "fasting ENDCLASS. METHOD hungry. "lcl_animal IMPLEMENTATION CLASS lcl_lion IMPLEMENTATION. In downcast a more general reference variable (e. "hungry ENDCLASS.'. 269 .g. METHODS: hungry. "lcl_lion IMPLEMENTATION CLASS lcl_example DEFINITION. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. CLASS lcl_animal DEFINITION. ENDCLASS.. ENDCLASS. ' Run as fast as you can. ULINE AT /26(7). ENDCLASS. ULINE AT /28(6). PUBLIC SECTION. WRITE: / 'Stop running. fasting. ENDMETHOD.reference variable. The assignment is only executed if the golden rule is then fulfilled for the target variable. REPORT z_inherit_down_up_cast01. 'Fasting today. PUBLIC SECTION. "hungry METHOD fasting. METHODS: hungry REDEFINITION. WRITE: / 'A Lion (King of Jungle) is hungry. Lion is on'.g. Listing below shows an example of up cast and down cast in inheritance. "lcl_animal DEFINITION CLASS lcl_lion DEFINITION INHERITING FROM lcl_animal. superclass) is assigned to a more specific reference variable (e. CLASS-METHODS main. we use the casting operator (?= or ?TO in case of MOVE) to perform a widening cast when we assign the ref_animal object reference to ref_lion. ENDMETHOD. PUBLIC SECTION. superclass) and we thus move downward in the inheritance tree. The question mark explicitly shifts the checking of the golden rule from the syntax check to the program runtime. Then. WRITE: / 'An animal is hungry'. otherwise.!' . the exception CX_SY_MOVE_CAST_ERROR is caused. "lcl_lion DEFINITION CLASS lcl_animal IMPLEMENTATION.'.

CALL METHOD ref_lion->fasting( ). ENDTRY. CALL METHOD ref_lion->fasting( ). CREATE OBJECT ref_animal. ENDIF.METHOD main. IF ref_lion IS NOT INITIAL. ENDTRY. TRY. cx_sy_move_cast_error. ENDCLASS. WRITE: / 'Down cast failed 1' COLOR = 6. lcl_lion. ref_animal = ref_lion_temp. "downcast without setting up the proper object reference in the Super reference CLEAR: ref_animal. ref_lion ?= ref_animal. CALL METHOD ref_lion->hungry( ). "upcast (subclass is assigned to superclass) CREATE OBJECT ref_lion_temp. CATCH cx_sy_move_cast_error INTO ref_cast_error. SKIP. ENDIF. CALL METHOD ref_lion->hungry( ). "main "lcl_example IMPLEMENTATION 270 . ref_cast_error. SKIP. WRITE: / 'Down cast failed 2' COLOR = 6. DATA: ref_animal ref_lion ref_lion_temp ref_cast_error TYPE TYPE TYPE TYPE REF REF REF REF TO TO TO TO lcl_animal. CATCH cx_sy_move_cast_error INTO ref_cast_error. lcl_lion. ref_lion. ENDMETHOD. "downcast (superclass is assigned to subclass) "with setting up the proper object reference in the Super ref erence TRY. IF ref_lion IS NOT INITIAL. ref_lion ?= ref_animal.

PRIVATE SECTION. Following is the output of above code listing. ENDINTERFACE. "lcl_electron DEFINITION CLASS lcl_vehicle DEFINITION. CLASS lcl_electron DEFINITION. PRIVATE SECTION. PUBLIC SECTION. CONSTANTS c TYPE i VALUE 300000. TYPES iref_tab TYPE TABLE OF REF TO lif_drive. serialize IMPORTING iref TYPE REF TO lif_drive. DATA speed_over_c TYPE p DECIMALS 3. PUBLIC SECTION. PRIVATE SECTION. if_serializable_object. "lcl_example DEFINITION 271 . INTERFACES: lif_drive. lcl_example=>main( ). INTERFACE lif_drive. Listing below shows an example of the down cast when using the interfaces. REPORT z_inherit_down_cast02. CLASS-METHODS: msg IMPORTING itab TYPE iref_tab. CLASS-METHODS main. PUBLIC SECTION. ENDCLASS.START-OF-SELECTION. show_speed. "lcl_vehicle DEFINITION CLASS lcl_example DEFINITION. ENDCLASS. INTERFACES lif_drive. ENDCLASS. METHODS: accelerate IMPORTING idelta TYPE i. DATA speed TYPE i.

iref->accelerate( 250000 ). CONCATENATE 'Vehicle Speed: ' output INTO output. ENDMETHOD. CREATE OBJECT iref TYPE lcl_electron. output = me->speed_over_c. DATA iref LIKE LINE OF itab. DATA output TYPE string. ENDMETHOD. APPEND iref TO intrf_refs. "lif_drive~show_speed "lif_drive~accelerate ENDCLASS. output = speed. DATA output TYPE string. APPEND iref TO intrf_refs. CREATE OBJECT iref TYPE lcl_vehicle. ENDMETHOD. METHOD lif_drive~accelerate.CLASS lcl_electron IMPLEMENTATION. lcl_example=>msg( intrf_refs ). DATA: intrf_refs TYPE iref_tab. iref->accelerate( 100 ). "lcl_electron IMPLEMENTATION CLASS lcl_vehicle IMPLEMENTATION. "lif_drive_object~accelerate METHOD lif_drive~show_speed. me->speed_over_c = me->speed_over_c + idelta / c. iref->show_speed( ). "lif_drive~accelerate METHOD lif_drive~show_speed. serialize( iref ). WRITE / output. "main METHOD msg. LOOP AT itab INTO iref. CONCATENATE 'Electron speed/c: ' output INTO output. "lcl_vehicle IMPLEMENTATION CLASS lcl_example IMPLEMENTATION. ENDMETHOD. ENDMETHOD. METHOD lif_drive~accelerate. ENDMETHOD. "lif_drive~show_speed ENDCLASS. ENDLOOP. METHOD main. WRITE / output. speed = speed + idelta. "msg 272 . iref LIKE LINE OF intrf_refs.

Following is the output produced by the above code listing. This happens using the down cast. "Calls the specified XSLT/ST. By integrating the tag interface. Once the IF_SERIALIZABLE_OBJECT is integrated in the class. A tag interface generally does not contain its own interface components. DATA: serl_ref xml_str TRY. ENDTRY. Before serialization takes place. the attributes of that class object can serialized to XML using the CALL TRANSFORMATION statement. ations dited r is The IF_SERIALIZABLE_OBJECT is a predefined tag interface. "serialize ENDCLASS. XSLT of the repository "XSLT/ST is programming language for describing transform "between ABAP data and XML formats. "lcl_example IMPLEMENTATION START-OF-SELECTION. TYPE REF TO if_serializable_object. ENDMETHOD.XSLT/ST programs are e "using the Transformation Editor (STRANS). First paramete "the transformation to use from the repository CALL TRANSFORMATION id SOURCE object = serl_ref RESULT XML xml_str . CATCH cx_sy_move_cast_error. TYPE xstring. 273 . classes or other interfaces stand out against the ABAP runtime environment. the interface reference variable is checked if the referenced object is serializable. serl_ref ?= iref. but instead assigns a particular task to the integrating classes or interfaces and changes the way they are handled by the ABAP Compiler. lcl_example=>main( ). RETURN.METHOD serialize. "The DISPLAY_XML_STRING function module of the repository "displays the result of serialization in an HTML browser cont rol CALL FUNCTION 'DISPLAY_XML_STRING' EXPORTING xml_string = xml_str.

274 . we can use instances of them in the lcl_see_and_say generically. we define the interface of the “play()” method to receive an instance of class lcl_animal. Here. we didn’t have to perform an explicit type cast as narrowing type casts are performed implicitly in method calls. you’ll notice that we create instances of lcl_cat and lcl_dog and pass them to the See-n-Say. However. Furthermore.Implementing Polymorphism The example code below defines an abstract base class called lcl_animal and two concrete subclasses: lcl_cat and lcl_dog. since the lcl_cat and lcl_dog classes inherit the methods “get_type()” and “speak()” from class lcl_animal. In order to make the See-n-Say generic. in the main method.

METHOD speak. speak REDEFINITION. CLASS lcl_dog IMPLEMENTATION. CLASS lcl_animal DEFINITION ABSTRACT. ENDCLASS. ENDMETHOD. "lcl_animal DEFINITION CLASS lcl_cat DEFINITION INHERITING FROM lcl_animal. "lcl_cat DEFINITIO CLASS lcl_dog DEFINITION INHERITING FROM lcl_animal. PUBLIC SECTION. CLASS-METHODS: play IMPORTING im_animal TYPE REF TO lcl_animal. "get_type "speak "lcl_cat IMPLEMENTATION "get_type "speak 275 . ENDCLASS. METHODS: get_type ABSTRACT. "lcl_example DEFINITION CLASS lcl_cat IMPLEMENTATION. ENDCLASS. ENDCLASS. CLASS-METHODS main. METHODS: get_type REDEFINITION. ENDMETHOD. METHOD get_type. ENDMETHOD. METHOD speak. PUBLIC SECTION. METHODS: get_type REDEFINITION.REPORT z_polymorphism01. ENDMETHOD. ENDCLASS. ENDCLASS. WRITE: 'Cat'. METHOD get_type. WRITE: 'Bark'. PUBLIC SECTION. WRITE: 'Dog'. "lcl_see_and_say DEFINITION CLASS lcl_example DEFINITION. speak ABSTRACT. PUBLIC SECTION. "lcl_dog DEFINITIO CLASS lcl_see_and_say DEFINITION. WRITE: 'Meow'. PUBLIC SECTION. speak REDEFINITION.

lcl_example=>main( ). "lcl_example IMPLEMENTATION START-OF-SELECTION. WRITE: 'says'. CALL METHOD im_animal->get_type. Following output is produced by executing the above code. METHOD main. "main ENDCLASS. ENDMETHOD. "lcl_dog IMPLEMENTATION CLASS lcl_see_and_say IMPLEMENTATION. ref_dog TYPE REF TO lcl_dog. DATA: ref_cat TYPE REF TO lcl_cat. CALL METHOD im_animal->speak. As mentioned earlier. NEW-LINE. "lcl_see_and_say IMPLEMENTATION CLASS lcl_example IMPLEMENTATION. lcl_see_and_say=>play( EXPORTING im_animal = ref_dog ). CREATE OBJECT ref_cat. WRITE: 'The'. ENDMETHOD. CREATE OBJECT ref_dog. METHOD play. one of the primary advantages of using polymorphism in a design like this is that we can easily plug in additional animals without having to change anything in class lcl_see_and_say. lcl_see_and_say=>play( EXPORTING im_animal = ref_cat ).ENDCLASS. 276 . "play ENDCLASS.

1. Create and activate the table zt_accounts as shown below: 2.The following example demonstrates the polymorphism using both interfaces and abstract classes. To create and activate the global interface z_if_account open the Class Builder (SE24) as shown below: 277 .

Create and activate the global abstract class z_cl_account as shown below: 278 .3.

as show below: 279 . Next to implement the methods of z_cl_account. double click each method to write code for it.4.

5. The following concrete global class z_cl_checking_account specializes the abstract z_cl_account as shown below: 280 .

6. The

redefined withdraw method of concrete global class z_cl_savings_account throws an exception when the account is overdrawn.

281

The following application program works with bank accounts in a very general way.
REPORT z_interface_banking.

CLASS lcl_account_management DEFINITION. PUBLIC SECTION.

282

ount

METHODS handle_debit_balance FOR EVENT overdraw OF z_cl_checking_acc IMPORTING id amount.

ENDCLASS.

"lcl_bank_management DEFINITION

CLASS lcl_example DEFINITION. PUBLIC SECTION. CLASS-METHODS: main, withdraw IMPORTING account TYPE REF TO z_if_account amount TYPE ztaccounts-amount, transfer IMPORTING source TYPE REF TO z_if_account target TYPE REF TO z_if_account amount TYPE ztaccounts-amount. ENDCLASS. "lcl_example DEFINITION CLASS lcl_account_management IMPLEMENTATION. METHOD handle_debit_balance. DATA text TYPE string. text = amount. CONCATENATE `Handling debit ` text ` for account ` id INTO te xt. MESSAGE text TYPE 'I'. ENDMETHOD. "handle_debit_balance ENDCLASS. "lcl_bank_management IMPLEMENTATION CLASS lcl_example IMPLEMENTATION. METHOD withdraw. DATA txt TYPE string. TRY. account->withdraw( amount ). CATCH zcx_negative_amount. txt = account->id. CONCATENATE 'Withdrawal not possible from ' txt INTO txt. MESSAGE txt TYPE 'I'. ENDTRY. ENDMETHOD. "withdraw METHOD transfer. DATA txt TYPE string. TRY. source->transfer( amount = amount target = target ). CATCH zcx_negative_amount. txt = source->id. CONCATENATE 'Transfer not possible from ' txt INTO txt.

283

MESSAGE txt TYPE 'I'. ENDTRY. ENDMETHOD. "transfer METHOD main. DATA: acc1 TYPE REF TO z_if_account, acc2 TYPE REF TO z_if_account, acc_handler TYPE REF TO zcl_account_management. CREATE OBJECT: acc1 TYPE z_cl_checking_account EXPORTING id = '0000815', acc2 TYPE z_cl_savings_account EXPORTING id = '0000415', acc_handler. "register the event handler SET HANDLER acc_handler->handle_debit_balance FOR ALL INSTANCES. lcl_example=>withdraw( account = acc1 amount = 100 ). lcl_example=>transfer( source = acc1 target = acc2 amount = 500 ). lcl_example=>withdraw( account = acc2 amount = 1000 ). lcl_example=>transfer( source = acc2 target = acc1 amount = 1000 ). ENDMETHOD. "main ENDCLASS. "lcl_example IMPLEMENTATION START-OF-SELECTION. lcl_example=>main( ).

Following is the output of above example.

284

Events and Event Handling
Events enable the objects of a class or a class itself to publish changes to its state, and other objects and classes can then react to this change of state. Before going deep into the details of events lets consider an example how events work. 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 example 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 take interest and react accordingly by executing an appropriate method. But events can not be implemented using normal direct method calls. As to call a normal method, the address must be known and a called method must always react. But in the above case; we don’t know which cabin crew instance is going to react to the button pressed event (address of method not known) and the cabin crew instance can decided not to acknowledge the button pressed event as they are ignored during take-off and landing (method not always react). However; triggering events is an indirect method call. The event concept established through the Publish-and-Subscribe mechanism. This mechanism takes place on two levels; i.e. statically at the time of declaration and dynamically at the time of program execution. The Publish-and Subscribe mechanism in ABAP Objects are implemented as follows:

285

• • •

Events: A class can contain events as static or instance components. Every method of that class can trigger those events. Event 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. Event Handler Registration: The handling of an event by a proper event handler can be explicitly registered, without an appropriate registration, no handling takes place.

Declaring Events
Events declaration is the static publishing of events in Publish-and-Subscribe mechanism. Events can be declared in one of the three visibility sections of the class or in an interface. The syntax for declaring instance and static events are: [CLASS-] EVENTS event_name [EXPORTING … VALUE(param1) TYPE type . . .]. 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 exclusively 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. Note; each instance event also has an implicit output parameter named sender. This output parameter has the type of an object reference variable. After the event has been triggered using the RAISE EVENT statement, sender points to the triggering object. In Class Builder the events are declared on the Events 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.

286

an event handler can be triggered by all objects. This statement interrupts the execution of the method and executes all event handlers registered for the event in the order of their registration.. the same applies to the class. in static methods. the classes of which are equal to or more specific than class or that implements the interface directly or via super class.. Then the triggering method is continued behind the RAISE EVENT statement. The class or interface specified for the event handler determines which objects or classes can trigger the execution of the event handler. eparami = valuei . By doing so. Event handlers are methods that are specifically identified as such shown below: [CLASS-]METHODS handler_name FOR EVENT event_name OF class|interface IMPORTING … eparami … [sender]. we can trigger the instance events and the static events of the corresponding class. The syntax for triggering an event is as follows: RAISE EVENT event_name EXPORTING . In an instance event. An event handler does not need to take all parameters. with exception of the implicit parameter sender. Events cal also be triggered during event handling. we can only trigger the static events.. Every class can contain event handlers for the events of other classes or their own class. Event Handlers Event handler declaration is the static subscription in Publish-and-Subscribe mechanism. The addition FOR EVENT makes a method an event handler and assigns it to exactly one event of a class or an interface. Using the EXPORTING addition. In instance methods.. actual parameters must be attached to all non-optional exporting parameters of the event.Triggering Events The triggering of an event is the dynamic publishing in Publish-and-Subscribe mechanism. In Class Builder the event handler can be defined in the Detail View of methods as shown below: 287 . For a static event. The parameter interface of an event handler may exclusively contain input parameters that were defined with the same names as output parameters when the event was declared. the input parameters of the event handlers are provided with values.

This statement registers the event handlers handler1. The registration couples event handlers to triggers. It must be more specific or equal to the class classes and implement all interfaces that were used when declaring the individual event handlers. The static type of obj_ref is restricted by the specified event handler. using ALL INSTANCES. including the predefined sender parameter can be entered. it must be registered accordingly at runtime. For an event handler to react to a triggered event. When obj_ref is specified. event handlers are registered for the events of exactly one object. 288 . handler2. This registration also applies to all objects that are not created until after the SET HANDLER statement. … for corresponding instance events of the object to which the obj_ref reference variable provided after FOR is pointing.Under the Parameters. event handlers can be registered for all objects. The syntax for registering event handlers for instance event is: SET HANDLER handler1 handler2 … FOR obj_ref|[ALL INSTANCES] [ACTIVATION act]. the instance events of which they can handle. Alternately. The event handlers are specified like the methods of a static method call. This coupling can be dissolved at any time. Registering Event Handlers Event handler registration is the dynamic subscription in Publish-and-Subscribe mechanism. only parameters of the event.

The following example demonstrates the use of event handling in detail. METHODS constructor IMPORTING iseat_no TYPE i icls TYPE string. "lcl_passenger DEFINITION CLASS lcl_flight_attendent DEFINITION. "call_flight_attendent 289 . every registration is equal to a line in a invisible system table. ENDCLASS. PUBLIC SECTION.In static events. PUBLIC SECTION. PRIVATE SECTION. "lcl_pilot DEFINITION CLASS lcl_passenger DEFINITION. PRIVATE SECTION. METHODS call_flight_attendent. REPORT z_event_handling. DATA seat_no TYPE i. METHODS constructor IMPORTING ititle TYPE string. RAISE EVENT button_pressed. PUBLIC SECTION. ENDCLASS. "lcl_example DEFINITION CLASS lcl_pilot IMPLEMENTATION. the addition FOR is omitted and the registration is performed for all classes and interfaces that can be handled by the specified handler. ENDCLASS. METHOD call_flight_attendent. CLASS-METHODS main. DATA cls TYPE string READ-ONLY. EVENTS button_pressed EXPORTING value(eseat_no) TYPE i. Technically. PUBLIC SECTION. The addition ACTIVATION determines if the specified handlers are to be registered (X) or deregistered (“ “). METHODS help_the_pilot FOR EVENT button_pressed OF lcl_pilot. DATA title TYPE string. ENDCLASS. METHODS call_flight_attendent. METHODS help_the_passenger FOR EVENT button_pressed OF lcl_passenger IMPORTING eseat_no sender. either only instance events or only static events can be registered. where registration is the default setting. CLASS lcl_pilot DEFINITION. This means that in one statement. EVENTS button_pressed. ENDMETHOD. "lcl_flight_attendent DEFINITION CLASS lcl_example DEFINITION.

attendent1 TYPE REF TO lcl_flight_attendent. 290 . CONCATENATE me->title ' helps ' sender->cls ' passenger on seat ' txt INTO txt RESPECTING BLANKS. "lcl_pilot IMPLEMENTATION CLASS lcl_passenger IMPLEMENTATION. MESSAGE txt TYPE 'I'. "help_the_passenger ENDCLASS. passenger1 EXPORTING iseat_no = 11 icls = 'Business Class'. SET HANDLER: attendent1->help_the_pilot FOR pilot. "lcl_pessenger IMPLEMENTATION CLASS lcl_flight_attendent IMPLEMENTATION. DATA: pilot TYPE REF TO lcl_pilot. attendent2 EXPORTING ititle = 'Ayesha'. "constructor METHOD help_the_pilot. ENDMETHOD. me->cls = icls. "lcl_flight_attendent IMPLEMENTATION CLASS lcl_example IMPLEMENTATION. passenger2 TYPE REF TO lcl_passenger. DATA txt TYPE string. attendent2 TYPE REF TO lcl_flight_attendent.ENDCLASS. attendent1 EXPORTING ititle = 'Komal'. DATA txt TYPE string. pilot->call_flight_attendent( ). MESSAGE txt TYPE 'I'. CONCATENATE me->title ' helps pilot ' INTO txt RESPECTING BLANKS. ENDMETHOD. txt = eseat_no. CREATE OBJECT: pilot. attendent2->help_the_passenger FOR ALL INSTANCES. METHOD constructor. "help_the_pilot METHOD help_the_passenger. me->title = ititle. METHOD constructor. me->seat_no = iseat_no. METHOD main. "call_flight_attendent ENDCLASS. ENDMETHOD. passenger1 TYPE REF TO lcl_passenger. RAISE EVENT button_pressed EXPORTING eseat_no = me->seat_no. "constructor METHOD call_flight_attendent. passenger2 EXPORTING iseat_no = 233 icls = 'Economy Class'. ENDMETHOD. ENDMETHOD.

lcl_example=>main( ). "main ENDCLASS. ENDMETHOD. 291 . Following is the output of the above code listing. passenger2->call_flight_attendent( ). "lcl_example IMPLEMENTATION START-OF-SELECTION.passenger1->call_flight_attendent( ).

lifetime and so forth. Area calluses provide the only possible means of access from ABAP programs to the shared objects memory. AS ABAP includes an implicit mechanism called SAP buffering. In simple terms. Areas The management and access to the shared objects memory are performed via areas. this is not a template for area instances but for area handles. shared objects have been introduced in SAP NetWeaver 2004. where the raw data from the database is already buffered in the shared memory. This means these objects can be accessed only within an internal session. Shared memory contains an area called Shared Objects Memory where objects can be stored as shared objects. This includes both instances of classes and anonymous data objects (data objects created with CREATE DATA statement). 292 . For frequent database access. The shared objects memory is divided into area instances that can exist in different versions. a global area class of the same name is generated. The term “area” in this context should not be confused with a memory area in the shared object memory. an area is just a collection of settings that describe the properties of area instances. If we recall the topic “Memory Organization of Application Server ABAP” we find that the only shared memory of the application server is suitable for storing objects that can be accessed by all of the programs of ABAP server. An area is a repository object that describes the technical properties of area instances.Shared Objects The objects we dealt with so far reside in the internal session of an ABAP program. The actual shared objects are stored in the area instance versions. There can be several area instances of an area. which applies only to area instances. An area handle is an object 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 objects stored therein. For every area. The following sections introduce the programming interface for shared objects. For explicit and OO access to the shared memory. However. like versioning.

by means of an object of an area class. that is. The root object can contain working data itself and reference other shared objects (instances of shared memory-enabled classes or data objects) of the area instance. In Class Builder. Figure below depicts the access to shared objects. The shared objects are stored in an area instance version in the shared memory.To store objects as shared objects in area instances. 293 . every area must be assigned a global shared memory-enabled class as an area root class. An area handle has an attribute named ROOT that can be used to address the root object. their classes must be identified as shared memory enabled as follows: CLASS cls_name DEFINITION … SHARED MEMORY ENABLED. Accessing Shared Objects The access to shared objects is achieved via an area handle. The properties of area handle and area instance are specified by the corresponding area in the ABAP Workbench. An area instance where shared objects are stored must contain at least one instance of the area root class as a root object. the Shared Memory-Enabled property must be selected as: During definition.

fixed. there should only be references within an area instance version. The same applies to references from shared objects to objects of the internal session. the root object and another object. These are divided into basic properties. which. While an area instance version is attached to an internal session via an area handle. From an internal session.The initial access from internal session to the shared objects of an area instance is always achieved via the area handle ROOT reference variable pointing to the root object. The static attributes of a shared memory-enabled class are not treated differently from those of a normal class. it can be regarded as its extension. inherits from CL_ABAP_MEMORY_AREA. SHMA) to create an area. because this handle provides the required lock of the area instance. Basic Properties 294 . The creation of an area generates the area class of the same name. The figure above shows an area instance version with two shared objects. a reference to a shared object can only be used as long as this session is connected to the area instance via an area handle. When an area is created. The oref reference shown in this figure should therefore be resolved for security reasons before the access via the area handle is terminated. Therefore. Every area class inherits from the predefined class CL_SHM_AREA. Area instance versions to which no area handles are attached are ideally self-contained. the area name should follow the naming conventions for global classes. Creating an Area The ABAP Workbench includes the Area Management tool (TCode. Every area handle therefore contains a set of predefined methods and attributes. that is. dynamic and runtime area properties. the area properties are set. in turn.

Possible contexts are: Application Server. This is also the name of the generated global area class and is therefore unique across the system. Without versioning. With client-dependent areas. Client Dependent Area: An area can be described as client-dependent. • • • • Fixed Properties The fixed properties determine the context of an area and whether versioning takes place as: • • Area Binding: This property determines the visibility and lifetime of the area instance versions of the instance by specifying a context. these methods have an additional input parameter. When the dynamic properties of an area are changed dynamically during operation. are active or are obsolete) are not affected. and use the prefix “CL_“. The new dynamic properties are not used until the next change lock is set in the corresponding version that is being built. Area Root Class: The area root class is a global shared memory-enabled class that has to be assigned to an area when it is defined. and ABAP Memory. a new area instance is created automatically at the time selected in the area build type. there is only one version and the area instance is equivalent to this area instance version. The basic properties are: • Area Name: The name of an area. which enables explicit access to other clients. Area Build Type: If this property is set. External Session. In this case. The ROOT attribute of a corresponding area handle is generated as a reference variable with the static type of the area root class. the current area instance versions (versions that are being built. It is recommended that you follow the naming conventions for global classes in the current system.The basic properties of an area are considered when the area class is generated. Dynamic Properties The dynamic properties of an area are not considered when the area class is generated. • Area Constructor Class: Any global class that implements the IF_SHM_BUILD_INSTANCE interface can be specified as an area constructor 295 . Area Instance Versioning: This property defines whether there can be only one or several area instance versions of an area instance. When the basic properties of an area are changed during operation. all area instance versions of the area are set to expired and the area class is regenerated. Session. Transactional Area: Transactional area enables data or objects in the area instance versions to join such areas to database contents. CLIENT. With client-dependent areas. an area instance of the area is identified by a client identifier as well as by its name. the area class methods refer to accessing an area instance on the current client.

and Lifetime of an Area Instance. Displacement Possible with Backup and Recovery and Displacement Possible. for example by administrators. with the difference that they can only be given default values by a developer and can also be changed without a developer key. we would create a simple area that can be used in applications working with the flight data model. Number of Versions of an Area Instance. Size of an Area Instance Version. Displacement Type: This property determines whether and how instances of the area can be displaced. As an example. The implementation of the IF_SHM_BUILD_INSTANCE~BUILD interface method is used as the area constructor. during Customizing or during operation. 296 . Area Size. Displacement may be necessary if the available addressing area of the shared memory is not sufficient for all area instance versions. Possible displacement types are: Displacement Not Possible. Runtime dependent properties are: Area Build Type.• class. Runtime Dependent Properties The same points apply to runtime-dependent properties of an area as to dynamic area properties.

The global class z_cl_flight_list contains an internal table flight_list of the existing type spfli_tab from the ABAP Dictionary. Next open the Area Management tool (TCode. which is filled by a set_flight_list method. This table contains the unchangeable data that is to be accessed from different programs. SHMA) to set properties for z_cl_flights area as shown below: 297 .

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

Only previous versions can be read-accessed in parallel. Usage as an Exclusive Buffer: An exclusive buffer contains data that is write. • 299 . On AS there can be a maximum of one change lock on an area instance. there can be maximum of one read lock for an area instance. This means that there are exclusive locks for creating or changing shared objects in area instances.or read-accessed by only one user across transaction boundaries. and read locks for accessing shared objects. Write Lock: If a write lock is set for an area in a program. Across several sessions. Without versioning. • • A change lock (write or update lock) locks an area instance version exclusively. a change lock can be set on an area instance even if there are read locks. A lock therefore always refers to all shared objects of an area instance. A typical application of shared buffer is the storage of a catalog or other stable lists. A typical application of an exclusive buffer is the storage of a shopping cart that is first populated by the customer and later read by the salesperson. • Read Lock: If a read lock is set for an area in program. The locks are set when an internal session is attached to an area instance via an area handle. a new area instance version can be created and can be populated with data. a new are instance version is created that can then be changed. the data of the current area instance version can be changed for areas without versioning. In general. For areas with versioning.prevents space in the shared memory from being consumed without actually being used by the program. Locking The access to shared objects is controlled via locks. the current area instance version can be read. there can be several read locks on an area instance versions. Update Lock: If an update lock is set for an area in a program. Within an internal session. With versioning. the data of a shared buffer is provided once by a single program and many users read-access the shared buffer simultaneously. This locking concept supports two application scenarios for shared objects: • Usage as a Shared Buffer: A shared buffer contains a large amount of data that is changed rarely (once a week up to once a day). The locking concept of shared objects is similar to that of a file system. a change lock can only be set if there is currently no read lock. The data can be created by the same user or another user.

no reference may point from the internal session to a shared object and vice versa. Until the attachment is removed. a new empty area instance version is created. If method is not successful. To dissolved the connection. 300 . This is achieved using the following static methods of the area class: • ATTACH_FOR_READ: Creates a new area handle to the current area instance version of an existing area instance and sets a read lock.Working with Shared Objects The shared objects 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. the area instance should be completed. • • In the case of success. which is attached to an area instance version via a change lock. all methods return a reference to an area handle that holds one of the three possible locks on the attached area instance version. Until the attachment is dissolved. we must specify a reference variable of the static type of an area class that points to an area handle. When disconnecting. it is possible o read-access the attached are instance version in the program. it is possible to change access the new area instance version in the program. ATTACH_FOR_WRITE: Creates a new area instance version. it is possible to changeaccess the attached area instance version in the program. To work with area instances. Shared objects can be created from shared memory-enabled classes as follows: CREATE OBJECT obj_ref AREA HANDLE area_handle … Following the addition AREA HANDLE. the current internal session must be attached to them via an area handle. attaches the area handle to it. the DETACH instance method is used to detached the area handle attached to an area instance version via a read lock 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 lock. the area handle is attached to the current area instance version. the new area instance version replaces a potential earlier area instance version. With versioning. and sets a write lock. ATTACH_FOR_UPDATE: Attaches an area handle to an existing area instance and sets an update lock. Without versioning. The addition AREA HANDLE also exists for the CREATE DATA statement for creating anonymous data objects. a new area instance version is created as a copy of the previous versions. With versioning. an exception is thrown that is defined as a subclass of CX_SHM_ATTACH_ERROR. because of no area instances or existing lock denies access. Until the attachment is removed. that is. Without versioning.

If a change lock is detached using DETACH_COMMIT. 301 . For this purpose. Ideally. the SET_ROOT instance method of the area handle must be called while the change lock is set. A broker takes care of the read access to area instances and can also contain the necessary authorization checks (discussed in later chapters). In the following program. The root object is the only shared object 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 work only with these classes. we merged loader and broker into a single class. two classes manage the accessing of shared objects: • • A loader creates and changes area instances. an instance of the area root class must be set as the root object of the area instance version.

Next implement the static constructor and methods as shown below: In an internal session. It sets a read lock on an area instance. Because there can be only one read lock on an area 302 . there can only be one instance of class that is created in the static constructor (Singleton). The get_flight_list method serves as a broker.

DATA: flist_handler TYPE REF TO z_cl_flight_list_handler. ENDCLASS. It tries to set a write lock and to build an area instance with a root object. the latter is possible only if no change access are expected after an area has been built. If the area built has been successful. CLASS-METHODS display IMPORTING value(itable) TYPE ANY TABLE. flist_handler = z_cl_flight_list_handler=>flight_list_handler. METHOD main. "cl_salv_table is used for simple. it is always first queried whether there already is an area handle. "main METHOD display. ENDMETHOD. while a read lock in get_flight_list remains until the end of the internal session. the create_flight_list method is called that acts as a loader. cl_salv_table=>factory( IMPORTING 303 . Without explicitly removing the change lock. get_flight_list creates an object of the z_cl_flight_list class in the current internal session and populates the internal table flight_list. there would be a program crash at the end of the current internal session at the latest. flist TYPE REF TO spfli_tab. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION.instance within an internal session. two-dimensional table DATA alv TYPE REF TO cl_salv_table. TRY. PUBLIC SECTION. Note that the write lock in create_flight_list is explicitly closed. In areas without versioning. MESSAGE 'No flight list available' TYPE 'I' DISPLAY LIKE 'E'. lcl_example=>display( flist->* ). CLASS lcl_example DEFINITION. either in the root object of the shared object or in the local object. RETURN. the return value of the method is assigned a data reference to the flight list. get_fight_list tries to set another read lock. CATCH zcx_no_flights. Lastly. If no area instance could be built. PRIVATE SECTION. flist = flist_handler->get_flight_list( ). In case of a failure. REPORT z_shared_objs. ENDTRY. TRY. The code in listing below shows an application program that works with the data from the share object in the z_cl_flights area. CLASS-METHODS main. Potential exceptions are propagated to the calling method.

r_salv_table = alv CHANGING t_table = itable ). alv->display( ). In SAP Memory Management (TCode ST02). Therefore. It can be called via TCode SHMM or 304 . lcl_example=>main( ). "display ENDCLASS. ENDMETHOD. CATCH cx_salv_msg. and then a reference to the flight list is read. If the flight list was accessed successfully. There is a specific monitor for the shared objects memory. "lcl_example IMPLEMENTATION START-OF-SELECTION. it is output in the display method using the ALV (SAP List Viewer). Shared memory is a valuable resource. Following is the output of above application program. the request for shared objects memory is explicit. MESSAGE 'ALV display not possible' TYPE 'I' DISPLAY LIKE 'E'. ENDTRY. The object of z_cl_flight_list_handler is created. Shared Objects Management Profile parameters specify how large the areas of the shared memory can become for different requests like programs. In contrast to other requests to shared memory. implicit buffers and the shared objects memory. program data. the current memory consumption can be viewed. a programmer must ensure that all unused memory is released.

their versions and the current locks. Delete the area instances. Some of the functions of the shared objects monitor include: • • • • • Display all area instances.from SHMA. If our previous program is run thrice in parallel within five minutes the display of the shared objects monitor looks as shown in figure below: The second area cl_icf_shm_area is used by the ABAP runtime environment. Change the state of area instance versions (from active to obsolete). Display the memory consumption. The monitor shows the properties of current area instances and also enables change actions. Display the contents of area instance versions. 305 .

In the standard setup. it triggers an exception. Every exception class is derived directly or indirectly from the CX_ROOT superclass. a runtime error occurs. Exception classes can be user defined or a series of predefined exception classes is also available. Class Based Exception Handling Class-based exception handling is based on exception classes. in other words. If such an exception is not handled.Exception Handling Exceptions are situations that occur while an ABAP program is being executed. Exception situations can be detected by either the program or the runtime environment. In an exception situation. and provides the option of navigating to the ABAP Debugger. such as CX_SY_ZERODIVIDE. such as user entries. System defined exceptions begin with prefix CX_SY_. Another cause of exception situation is the interaction between a program and external resources. active calls and son on. • Treatable Exceptions: Exceptions that can be handled and where the program can continue executing after the ABAP program has handled the exception. also be defined. In ABAP Objects we distinguish between class-based exceptions (since Release 6. Figure below shows all four classes and their relationships in the inheritance tree. the related exception class. Untreatable Exceptions: Exceptions that cannot be handled. an exception is represented by an exception object. the file system or the memory. There are two main types of exceptions: those that can be handled (treatable) and those that cannot be handled (untreatable). Coding may actually be implemented incorrectly. When the ABAP program or the runtime environment detects an exception situation. however. Treatable exceptions are predefined in the system or can be user defined. without the system ending up in a critical state. Handling is not possible and they always cause a runtime error. They are usually defined globally with the Class Builder of the ABAP Workbench. short dumps are stored in the system for 14 days and managed using transaction ST22. by an instance of an exception class. • After a program has terminated with a runtime error. contents of data objects. These are critical error situations in the runtime environment. Local exception classes can.10) and classic exception handling. the system outputs a short dump that contains the name of the runtime error. there are three other abstract exception classes for structuring possible exceptions. All exception classes must begin with the prefix CX_. 306 . Exception situations can have different causes.

.... [try_block] [CATCH cx_class1 cx_class2 ... CX_STATIC_CHECK: Exceptions from this category must be handled within procedures or declared as part of the interface... an exception object is generated and a handler is searched for this exception.... [INTO obj_ref].. the system attempts to propagate it to the caller of the procedure... If no handler is found in the entire call hierarchy. exceptions from this category must be handled within procedures or declared as part of the interface. 307 . the program flow is interrupted.. the program terminates with a runtime error and a short dump is generated.. not checked statically by the syntax check. This is checked by both the compiler and the runtime environment..The key characteristics of the four classes are as follows: • • • CX_ROOT: This is the super class from which every exception class is directly or indirectly derived.. [catch_block] . [CATCH cx_class3 cx_class4 ... but is checked dynamically at the moment in which an exception of this type is propagated from the procedure. If an exception is not handled in a procedure. CX_NO_CHECK: Neither compiler nor the runtime environment checks whether an exception that leaves the context of a procedure has also been declared in the interface.. [catch_block] . however. This is.. But how exceptions actually caught and what is a handler. creating a corresponding call hierarchy.. A handler is part of the TRY-ENDTRY control structure for catching exceptions. • Catching or Handling of Exceptions If the exception occurs. procedures call other procedures.... [INTO obj_ref]. The syntax is as follows: TRY. As a rule. CX_DYNAMIC_CHECK: Here too.

var = ioperand ** ioperand. the system looks for an exception handler in the same or in an outer TRYENDTRY control structures. When the end of a CATCH block is reached. The coding in the TRY block (try_block) defines a protected area whose exceptions can be handled in the subsequent CATCH blocks. Consider the example below for catching and handling exceptions. along with the exceptions from their respective subclasses. txt = error->get_longtext( ). MESSAGE txt TYPE 'I' DISPLAY LIKE 'E'.. The actual exception handlers consist of one or more optional CATCH blocks (catch_block). PUBLIC SECTION. MESSAGE txt TYPE 'I' DISPLAY LIKE 'E'. CATCH cx_sy_arg_out_of_domain INTO error. txt = error->get_longtext( ). The more specific exception classes must always be listed before more general exception classes. processing continues after ENDTRY. where obj_ref must be an object reference variable whose static type must be compatible with specified exception object. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. A CATCH block handles the exceptions from exception classes cx_class1 cx_class2 . CATCH cx_root INTO error. If the INTO addition is specified. CATCH cx_sy_zerodivide INTO error. error TYPE REF TO cx_root. a reference to the exception object is stored in obj_ref.. [cleanup_block] ENDTRY. txt = error->get_longtext( ). REPORT z_excep_handling. CLASS-METHODS main IMPORTING ioperand TYPE i. processing continues after ENDTRY. var = 1 / ioperand. If exception occurs in the TRY block. These contain the program logic that is executed if the related exception occurs in the TRY block of the same TRY-ENDTRY control structure. If no exception occurs in the TRY block and its end reached. METHOD main.[CLEANUP [INTO obj_ref]. ENDTRY. MESSAGE txt TYPE 'I' DISPLAY LIKE 'E'. var = SQRT( ioperand ). CLASS lcl_example DEFINITION. ENDCLASS. 308 . TRY. txt TYPE string. DATA: var TYPE i.

lcl_example=>main( ioperand = -1 ). lcl_example=>main( ioperand = 100000 ). In each of the handlers. supplying information about the precise reason for the error. The general procedure for finding the correct handler for an exception is shown in the figure below: 309 . "main "lcl_example IMPLEMENTATION START-OF-SELECTION. ENDCLASS. lcl_example=>main( ioperand = 0 ).ENDMETHOD. the relevant error message is output. Following is the output of above code listing.

If the INTO addition is specified. This means that a program or certain objects may come into an inconsistent status. Figure below shows an example of the control flow process when the CLEANUP block is executed. which would cause the CLEANUP block to be left early.If an exception occurs and is caught and handled by a handler. exceptions that occur within CLEANUP block must also be caught and handled there. After the CLEANUP block has been executed. result in runtime error. the normal control flow of the program is changed. the CLEANUP blocks for the surrounding TRY control structures are executed until the corresponding handler code has been executed. Also. The CLEANUP block in TRY-ENDTRY control structure is used to re-establish a consistent status. or that resources have not been released yet. The statements in this block are executed if an exception occurs in a TRY block that is not caught by handler in the same TRY-ENDTRY control structure. where obj_ref must be an object reference variable of the CX_ROOT type. and a procedure is generally left early. but in a surrounding TRY-ENDTRY control structure. 310 . It must be noted that statements like RETURN or LEAVE TO. a reference to the exception object is stored in obj_ref.

the exception object must already exist and the obj_ref reference variable must point to it. Exceptions can be raised in a program-driven manner using the RAISE EXCEPTION statement.an exception object is created.. The arithmetic statement var = 1/0. If the addition TYPE is specified. you can assign appropriate actual parameters to the input parameters of the instance constructor using the same syntax as with CREATE OBJECT. for example. every exception class cx_class visible at this point can be specified. If obj_ref is specified. an exception of the exception class cx_class is raised and . With the addition EXPORTING.. After TYPE.if necessary . If the exception is not caught a runtime error occurs.]}|obj_ref}.Raising Exceptions Exceptions can be raised in two ways: System-driven (by runtime environment) or Program-driven (by the ABAP program). RAISE EXCEPTION {{TYPE cx_class [EXPORTING p1 = a1 p2 = a2 . causes an exception of the CX_SY_ZERODIVDE class to be raised by the runtime environment. For reasons of efficiency. an exception object is only actually generated if the INTO addition of the CATCH statement is used for exception handling. This may be the case if the exception has already been caught once but if the handler wants to raise it again (because it cannot be handled 311 .

CLASS-METHODS main. for example) or if the exception object was generated previously by means of CREATE OBJECT. TRY. lcl_example=>main( ). ENDTRY. "main ENDCLASS. "lcl_example IMPLEMENTATION START-OF-SELECTION. "cx_sy_dynamic_osql_semantics represent the OpenSQL exceptions "textid. txt TYPE string. 312 . "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. ENDCLASS. CLASS-DATA: exp_ref TYPE REF TO cx_sy_dynamic_osql_semantics. MESSAGE txt TYPE 'I' DISPLAY LIKE 'E'. Following is the output of above code listing. ENDMETHOD. PUBLIC SECTION. the predefined exception cx_sy_dynamic_osql_semantics is raised. REPORT z_raise_exceptions.completely. for which an exception text and its placeholder &TOKEN& is filled by passing a value. CATCH cx_sy_dynamic_osql_semantics INTO exp_ref. txt = exp_ref->get_text( ). CLASS lcl_example DEFINITION. In the following example. stor value for Attribute textid RAISE EXCEPTION TYPE cx_sy_dynamic_osql_semantics EXPORTING textid = cx_sy_dynamic_osql_semanti cs=>unknown_table_name token = 'tbl_student'. Key for Access to Message Tex "unknown_table_name. PRIVATE SECTION. METHOD main.

CLASS lcl_example DEFINITION. The Exception Class checkbox must be selected. which is not handled in a procedure. If an exception class is declared in an interface.. it can not leave a procedure. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. the RASING addition is used... RAISING exp1 exp2 . CLASS-METHODS calculate IMPORTING ioperand TYPE i RAISING cx_sy_zerodivide. PUBLIC SECTION. REPORT z_excep_proc_decl. PRIVATE SECTION. the exceptions that can be propagated from the procedure must be declared. The example in listing below shows the effects of an exception declaration in an interface. the declaration is made by listing the exception classes in the Exceptions tab. If an exception is not declared. This tells the caller which exceptions can be expected from the procedure. 313 . as the following simplified syntax for method declaration shows: METHODS meth_name .. ENDCLASS.Declaring Exceptions in Procedure Interfaces As we know that system attempts to propagate an exception. To declare an exception in the interface of a procedure. this declaration also applies to all of its subclasses. In the Class Builder or Function Builder. to the caller of the procedure. This raises an exception from the predefined class CX_SY_NO_HANDLER. CLASS-METHODS main. In the parameter interface of a procedure.

it is propagated to the caller. CATCH cx_sy_arg_out_of_domain INTO err_ref. in other words to the main method. calculate( ioperand = -1 ). var = SQRT( ioperand ). "calculate METHOD main. Within main method. In the first case. calculate( ioperand = 0 ). txt = err_ref->get_longtext( ). MESSAGE txt TYPE 'I' DISPLAY LIKE 'E'. MESSAGE txt TYPE 'I' DISPLAY LIKE 'E'. lcl_example=>main( ). 314 . txt = err_ref->get_longtext( ). DATA: err_ref TYPE REF TO cx_root. DATA var TYPE i. MESSAGE txt TYPE 'I' DISPLAY LIKE 'E'. CATCH cx_sy_zerodivide INTO err_ref. it is therefore not propagated and cannot be identified by the exception handler in the main method.METHOD calculate. txt = err_ref->get_longtext( ). This exception is declared in the interface of the calculate method. the value -1 is transferred. CONCATENATE 'CX_SY_NO_HANDLER: ' txt INTO txt RESPECTING BLANKS. the cx_sy_zerodivide exception is raised by transferring 0. The second time calculate method is called. TRY. the calculate method is called twice with different parameters. "lcl_example IMPLEMENTATION START-OF-SELECTION. ENDMETHOD. Because the exception is not handled locally in the calculate method. CATCH cx_sy_no_handler INTO err_ref. This generates the cx_sy_arg_out_of_domain exception when attempting to determine the square root. ENDTRY. TRY. The cx_sy_no_handler exception handler prevents the interface violation from causing a runtime error. CONCATENATE 'CX_SY_ARG_OUT_OF_DOMAIN: ' txt INTO txt RESPECTING BLANKS. var = 1 / ioperand. CONCATENATE 'CX_SY_ZERODIVDE: ' txt INTO txt RESPECTING BLANKS. "main ENDCLASS. Following is the output of above code listing. txt TYPE string. This exception is not declared in the interface. ENDMETHOD. but which indicates that the procedure was not implemented cleanly. ENDTRY.

The predefined exception classes (CX_SY_.. CX_DYNAMIC_CHECK or CX_NO_CHECK. These three categories (static.The example shows the effects of the violation of the procedure interface in which the exception was declared. Creating Exception Classes All exception classes (global or local) are sub classes of one of the abstract exception classes described in previous section: CX_STATIC_CHECK. No specific class can be directly derived from CX_ROOT.) inherit from CX_DYNAMIC_CHECK or 315 .. The abstract super classes for all exception class CX_STATIC_CHECK. Table below shows in which cases which exception classes are to be used as a basis. 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 exception classes. dynamic and no) determine whether an explicit declaration must be made and how this is checked.

and the line number of the statement that raised the exception. If the correct naming convention (prefix CX_) and the class type Exception Class is chosen when a new class is created. the Class Builder automatically becomes the Exception Builder. because it enables exceptions to be chained. we can define our own methods. Exception classes have the following features: Constructor The constructor must have a predefined structure and a specific interface. GET_SOURCE_POSITION: Returns the program name. YCX_ or ZCX_. The attribute is particularly useful. The following two predefined methods are inherited from the root class CX_ROOT: • • GET_TEXT and GET_LONGTEXT: These methods return the exception text or the long text of the exception text (controlled by the TEXTID attribute) as a character string of the string type. • 316 . and influences the result of the GET_TEXT method. Methods In exception classes. Global exception classes are defined and managed in the Class Builder (SE24).CX_NO_CHECK but not from CX_STATIC_CHECK. All exception classes must begin with the prefix CX_. PREVIOUS: Can contain a reference to a previous exception. Attributes The following attributes are inherited from CX_ROOT: • TEXTID: Used to specify the exception of a class more precisely by using several exception texts. PREVIOUS: This parameter can be used to assign the PREVIOUS attribute of an exception class a previous exception. the Class Builder generates the correct constructor and sets it to an unchangeable status. With global classes. the name of a possible include program. The constructor has two IMPORTING parameters: • • TEXTID: This parameter can be used to determine which of your exception texts the exception will use. The attribuet is genrally set by the constructor. This means that we can track the path of an exception right back to its origin.

These texts can contain a maximum of 72 characters and can be sent to the program user during exception handling with the MESSAGE obj_ref statement. There are two ways of defining exception texts: • Exception Texts in Online Text Repository: The Online Text Repository (OTR) is a central repository for text and provides services for the processing and administration. the short texts for messages in the database table T100 are used as exception texts. The exception text describes an error situation from a technical view. The text is identified by the message class and the message number. the parameters are replaced by the content of the attributes. 317 . Note that here the message class is not a class in the sense of object orientation rather it is an identifier that groups messages in an application area. We can convert attributes into parameters of exception texts by displaying their name using the character '&' in the exception text.Each exception is assigned an explanatory text. If the exception occurs. Exception texts can contain parameters (placeholders) that enable an error situation to be described more precisely. • In the first example we define our own exception class. The text stored in the OTR can contain a maximum of 255 characters. Attributes from the exception class can be assigned to placeholders &1 to &4 or & in the message. Exception Texts in Table T100: If the exception class implements the interface if_t100_message. to which we assigned two alternative OTR texts.

a predefined exception text is used. we have assigned a relevant text to the two exception IDs congaing a place holder &TOKEN& to parameterize the output. If the parameter is not passed. 318 . Another attribute TOKEN (with same name as the parameter) of type string must be created.Next we created another exception ID with name ZCX_EXCEPTION_EXAMPLE02. This can be passed to the TEXTID parameter of the constructor to determine the exception text when the exception is raised. the Class Builder creates a static constant with the same name as the exception text. For each exception text. In addition.

RAISE EXCEPTION TYPE zcx_exception_example EXPORTING textid = zcx_exception_example=>zcx _exception_example token = '"100"'. "main ENDCLASS. ENDCLASS. RAISE EXCEPTION TYPE zcx_exception_example EXPORTING textid = zcx_exception_example=>zcx _exception_example02 token = '"200"'. lcl_example=>main( ). PUBLIC SECTION. CLASS lcl_example DEFINITION. "lcl_example IMPLEMENTATION START-OF-SELECTION. MESSAGE txt TYPE 'I' DISPLAY LIKE 'E'. txt = err_ref->get_text( ). 319 . ENDTRY. CATCH zcx_exception_example INTO err_ref. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. DATA: err_ref TYPE REF TO zcx_exception_example.The following code consumes the zcx_exception_example. MESSAGE txt TYPE 'I' DISPLAY LIKE 'E'. TRY. REPORT z_excep_decl01. TRY. ENDTRY. METHOD main. CLASS-METHODS main. ENDMETHOD. CATCH zcx_exception_example INTO err_ref. txt = err_ref->get_text( ). After execution the following output is produced. txt TYPE string.

First to create the message class. In this case the if_t100_message is included in the class definition automatically and prepare the Class Builder to use messages as exception texts. open the message transaction tool (SE91) and create the zexcp_msg_cls as shown below: Create a new class ZCX_EXCEPTION_EXAMPLE_T100 and select the With Message Class checkbox. 320 .The next example demonstrates the usage of exception texts from database table T100.

and click on the Message Text button the system displays an input template where we entered the message class already created.In the Attributes tab. Next to define message texts. the two attributes TOKEN1 and TOKEN2 are defined as placeholders. go to Texts tab. Place the cursor in the line with the corresponding exception ID. 321 .

"lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. Following is the output of above code listing. 322 . REPORT z_excep_decl02. CLASS-METHODS main. ENDCLASS. TRY. RAISE EXCEPTION TYPE zcx_exception_example_t100 EXPORTING token1 = '"5 00"' token2 = '"F ive Hunderd"'. "main ENDCLASS. METHOD main. ENDMETHOD. CATCH zcx_exception_example_t100 INTO err_ref.The following example utilizes the above exception class. MESSAGE err_ref TYPE 'I' DISPLAY LIKE 'E'. lcl_example=>main( ). "lcl_example IMPLEMENTATION START-OF-SELECTION. DATA err_ref TYPE REF TO zcx_exception_example_t100. CLASS lcl_example DEFINITION. ENDTRY. PUBLIC SECTION.

The CATCH and ENDCATCH statements define control structures that can be nested as deeply as we require. …………………. We can handle catchable runtime errors with the following statement: CATCH SYSTEM-EXCEPTIONS exc1 = rc1 … excn = rcn. ENDCLASS.Classic Exception Handling For reasons of downward compatibility. Instead. The following example demonstrates how to use the catchable runtime errors. PUBLIC SECTION. REPORT z_classic_catchable_errors. 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. after ENDCATCH. Catchable runtime errors are grouped into exception groups that allow similar errors to be handled together. ENDCATCH. "lcl_example DEFINITION 323 . the numeric value rc assigned to the runtime error. these older concepts can still be used to handle exceptions in ABAP. If one of the specified runtime errors occurs in the statement block between CATCH and ENDCATCH the program does not terminate. However. CLASS-METHODS main. these concepts should no longer be used in new programs. The rc expressions are numeric literals. The exc expressions describe either a catchable runtime error or the name of an exception group. The classic exceptions handling has the following types: Catchable Runtime Errors If runtime errors are caused by situations that can be handled in a meaningful way in the program. they are catchable. CLASS lcl_example DEFINITION. which is available as a return value in the sy-subrc system field.

MESSAGE 'Division by Zero error' TYPE 'I' DISPLAY LIKE 'E'. CATCH SYSTEM-EXCEPTIONS arithmetic_errors = 4. Raising exception terminates the procedure and the sy-subrc system field is set. ENDIF. METHOD main. the definition is carried out by assigning a name of the exception in the Class Builder or Function Builder in the Exceptions tab where the Exception Classes checkbox is not selected here. "main ENDCLASS. sysubrc is set to 4. which is contained in the exception group ARITHMETIC_ERRORS. the definition is carried out by assigning a name for the exception after the EXCEPTIONS addition of the [CLASS-]METHODS statement. Self-Defined (Non-Class-Based) Exceptions Self-defined (non-class-based) exceptions can be defined in the interfaces of function modules and methods.CLASS lcl_example IMPLEMENTATION. DATA var TYPE i. RAISE exc. IF sy-subrc = 4. var = 1 / 0. The RAISE EXCEPTION statement for raising class-based exceptions must not be used in 324 . The division by 0 causes the catchable runtime error COMPUTE_INT_ZERODIVIDE. lcl_example=>main( ). For local class methods. Following is the output of above code listing. In this case. The following statement is used to raise the self-defined (non-class-based) exceptions. ENDMETHOD. "lcl_example IMPLEMENTATION START-OF-SELECTION. ENDCATCH. For methods of global classes or function modules.

ENDIF. IF sy-subrc = 4. CLASS lcl_example DEFINITION. If an exception that is raised in the procedure has not been assigned a numeric value. which are moved to the sysubrc system field when the exception occurs. REPORT z_non_cls_based_excp. ELSE. ENDMETHOD. ENDIF.the statement MESSAGE raises a "non-class-based exception MESSAGE 'Division by 0' TYPE 'A' RAISING divide_zero. This is achieved by assigning numeric values to exceptions. CLASS-METHODS: main. IF idenominator = 0. a runtime error occurs. DATA result TYPE i. Self-defined (non-class-based) exceptions are rendered treatable using the EXCREPTIONS addition of the CALL METHOD and CALL FUNCTION statements. the actual handling is carried out after the call by evaluating sy-subrc. "divide METHOD main. however.the same procedure and no class-based exceptions can be declared in the interface with RAISING. Listing below demonstrate the self-defined (non-class-based) exceptions. divide( EXPORTING inumerator = 1 idenominator = 0 IMPORTING eresult = result EXCEPTIONS divide_zero = 4 ). "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. MESSAGE sy-msgv1 TYPE 'I' DISPLAY LIKE 'E'. PUBLIC SECTION. eresult = inumerator / idenominator. ENDCLASS. divide( EXPORTING inumerator = 1 325 . "Type A represents the termination messages "The message text is placed in the system field MSGV1 "RAISING addition. divide IMPORTING inumerator TYPE i idenominator TYPE i EXPORTING eresult TYPE i EXCEPTIONS divide_zero. METHOD divide.

Combining Class-Based and Classic Exceptions As we know from previous sections. and the program terminates. We call the divide method twice with the denominator 0 so that the exception is raised each time. In this case. lcl_example=>main( ). the exception is not handled. As developers. In this case. the system behaves as it does when the RAISE statement is used. and a new. classic exceptions 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 exceptions. Following screen shot shows the output of the above code listing. For example. In this case. we must distinguish strictly between the two concepts. The exception is handled during the first call. the message is processed according to the specified message type (“A”). The two concepts can not be mixed. but you may call procedure which still uses the classic exception concepts. we must opt for class-based exceptions. We can replace the RAISE statement with MESSAGE … RAISING.idenominator = 0 IMPORTING eresult = result ). ENDMETHOD. corresponding class-based exception must be raised as shown in the following example. "lcl_example IMPLEMENTATION START-OF-SELECTION. Therefore. when we call a function module that uses classic exceptions within a method where we are using class-based exceptions. 326 . "divide ENDCLASS. the classic exceptions must be caught. The second time the method is called.

IF idenominator = 0. lcl_example=>main( ). ENDIF. PUBLIC SECTION. ENDCLASS. ELSE. WRITE: / result . ELSE. "lcl_example IMPLEMENTATION START-OF-SELECTION. 327 . perform_cal RAISING cx_sy_zerodivide. perform_cal( ). MESSAGE err_ref TYPE 'I' DISPLAY LIKE 'E'. ENDMETHOD. ENDMETHOD. CLASS lcl_example DEFINITION. METHOD divide. ENDIF. divide IMPORTING inumerator TYPE i idenominator TYPE i EXPORTING eresult TYPE i EXCEPTIONS divide_zero. ENDTRY. eresult = inumerator / idenominator. RAISE EXCEPTION TYPE cx_sy_zerodivide. Following output is produced after the execution of above report. TRY. divide( EXPORTING inumerator = 1 idenominator = 0 IMPORTING eresult = result EXCEPTIONS divide_zero = 4 ). DATA result TYPE i. ENDMETHOD. "divide METHOD main.REPORT z_classic_cls_based_exp. CATCH cx_sy_zerodivide INTO err_ref. "divide METHOD perform_cal. "divide ENDCLASS. RAISE divide_zero. CLASS-METHODS: main. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. DATA err_ref TYPE REF TO cx_sy_zerodivide. IF sy-subrc = 4.

the program branches to the ABAP Debugger. The syntax for the ASSERT statement is: ASSERT [{ID group} CONDITION] log_exp. Assertions are typically used to ensure or check a consistent status at specific points in the program flow. Using assertions can help to find more errors in the program and to improve the quality of a program. the program terminates with the non-catchable runtime error ASSERTION_FAILED. The following settings are possible: • • • • Inactive: In this case. The program execution then continues with the statement following ASSERT. and the program terminates with the ASSERTION_FAILED runtime error. Assertions can be activated or deactivated so that checks do not affect the speed of any productive programs. assertion generally expresses an assumption that must apply in order for the program to continue to be executed. If the result is false. Abort: This option generates the same behavior as an assertion that is always active. The check point group is an ABAP repository object. An untreatable exception is raised. the program flow continues as normal. which can also be evaluated in Checkpoints that Can Be Activated (TCode SAAB). If the result of the check is true. If the ID group addition is specified.Assertions An assertion is the confirmation that a specific status of the data objects in a program actually exists. the statement does not have any impact on the program flow. An assertion that is always active is expressed by just the logical expression log_exp after the ASSERT statement. Therefore. 328 . Break/Log or Break/Abort: If an incorrect result is delivered. an assertion is defined that can be activated externally by linking it to a so called checkpoint group. an entry is written in a special log. The behavior of the assertion can be managed externally by changing the checkpoint group with Checkpoints that Can Be Activated (TCode SAAB). Log: if an incorrect result is delivered.

Exceptions focus more on the “robustness” of the program i.e. even if it is faced with meaningless user entries. The example on next page demonstrates assertions. the focus is on implementing a program so that it corresponds exactly to its specification. The assertions can be used to implement the software development principle. Assertions on the other hand.e. For that reason ASSERT is used at the start of method to check the pre-condition according to which the method may actually be executed. which states whether the method has functioned correctly. focus on “correctness” of the program i. a program should still be able to run. a post-condition is checked. 329 . At the end of the method. “design by contract (DbC)”.

330 . open Checkpoints that Can Be Activated (TCode SAAB).To create a checkpoint group. On initial screen enter the name for checkpoint group in Checkpoint Group frame and click on the Create button.

On activation tab leave default values and click Save. 331 .

On the resulting Activation tab select the Abort from Assertions (Forground) sub frame. Now this assertion is exclusively activated for you (by using personal activation setting). "lcl_example IMPLEMENTATION START-OF-SELECTION. and click Save. "lcl_example DEFINITION CLASS lcl_example IMPLEMENTATION. "main ENDCLASS. METHOD main. click on the Active button. To activate the assertion. PUBLIC SECTION. The following code listing uses the above assertion as: REPORT z_assertion. lcl_example=>main( ). on the initial screen of Checkpoints that Can Be Activated (TCode SAAB). ENDMETHOD. as shown below. CLASS-METHODS main. DATA var TYPE i. ASSERT ID zchk_point_grp CONDITION var IS NOT INITIAL.By default activatable checkpoints are always inactive. CLASS lcl_example DEFINITION. ENDCLASS. 332 .

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

334 .

Sign up to vote on this title
UsefulNot useful